id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_good_552_0
/* -*- Mode: C; c-file-style: "gnu" -*- */ /* Copyright (c) 2000 Petter Reinholdtsen 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. */ /* * scandir.c -- if scandir() is missing, make a replacement */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include "compat.h" /* * XXX This is a simple hack version which doesn't sort the data, and * just passes all unsorted. */ int scandir(const char *dir, struct dirent ***namelist, int (*select) (const struct dirent *), int (*compar) (const struct dirent **, const struct dirent **)) { DIR *d = opendir(dir); struct dirent *current; struct dirent **names; int count = 0; int pos = 0; int result = -1; if (NULL == d) return -1; while (NULL != readdir(d)) count++; closedir(d); names = malloc(sizeof (struct dirent *) * count); if (!names) return -1; d = opendir(dir); if (NULL == d) { free(names); return -1; } while (NULL != (current = readdir(d))) { if (NULL == select || select(current)) { struct dirent *copyentry = malloc(current->d_reclen); /* FIXME: OOM, silently skip it?*/ if (!copyentry) continue; memcpy(copyentry, current, current->d_reclen); names[pos] = copyentry; pos++; } } result = closedir(d); if (pos != count) names = realloc(names, sizeof (struct dirent *) * pos); *namelist = names; return pos; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_552_0
crossvul-cpp_data_bad_3924_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Capability Sets * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "capabilities.h" #include "fastpath.h" #include <winpr/crt.h> #include <winpr/rpc.h> #include <freerdp/log.h> #define TAG FREERDP_TAG("core.capabilities") static const char* const CAPSET_TYPE_STRINGS[] = { "Unknown", "General", "Bitmap", "Order", "Bitmap Cache", "Control", "Unknown", "Window Activation", "Pointer", "Share", "Color Cache", "Unknown", "Sound", "Input", "Font", "Brush", "Glyph Cache", "Offscreen Bitmap Cache", "Bitmap Cache Host Support", "Bitmap Cache v2", "Virtual Channel", "DrawNineGrid Cache", "Draw GDI+ Cache", "Remote Programs", "Window List", "Desktop Composition", "Multifragment Update", "Large Pointer", "Surface Commands", "Bitmap Codecs", "Frame Acknowledge" }; static const char* get_capability_name(UINT16 type) { if (type > CAPSET_TYPE_FRAME_ACKNOWLEDGE) return "<unknown>"; return CAPSET_TYPE_STRINGS[type]; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_capability_sets(wStream* s, UINT16 numberCapabilities, BOOL receiving); #endif /* CODEC_GUID_REMOTEFX: 0x76772F12BD724463AFB3B73C9C6F7886 */ static const GUID CODEC_GUID_REMOTEFX = { 0x76772F12, 0xBD72, 0x4463, { 0xAF, 0xB3, 0xB7, 0x3C, 0x9C, 0x6F, 0x78, 0x86 } }; /* CODEC_GUID_NSCODEC 0xCA8D1BB9000F154F589FAE2D1A87E2D6 */ static const GUID CODEC_GUID_NSCODEC = { 0xCA8D1BB9, 0x000F, 0x154F, { 0x58, 0x9F, 0xAE, 0x2D, 0x1A, 0x87, 0xE2, 0xD6 } }; /* CODEC_GUID_IGNORE 0x9C4351A6353542AE910CCDFCE5760B58 */ static const GUID CODEC_GUID_IGNORE = { 0x9C4351A6, 0x3535, 0x42AE, { 0x91, 0x0C, 0xCD, 0xFC, 0xE5, 0x76, 0x0B, 0x58 } }; /* CODEC_GUID_IMAGE_REMOTEFX 0x2744CCD49D8A4E74803C0ECBEEA19C54 */ static const GUID CODEC_GUID_IMAGE_REMOTEFX = { 0x2744CCD4, 0x9D8A, 0x4E74, { 0x80, 0x3C, 0x0E, 0xCB, 0xEE, 0xA1, 0x9C, 0x54 } }; #if defined(WITH_JPEG) /* CODEC_GUID_JPEG 0x430C9EED1BAF4CE6869ACB8B37B66237 */ static const GUID CODEC_GUID_JPEG = { 0x430C9EED, 0x1BAF, 0x4CE6, { 0x86, 0x9A, 0xCB, 0x8B, 0x37, 0xB6, 0x62, 0x37 } }; #endif static void rdp_read_capability_set_header(wStream* s, UINT16* length, UINT16* type) { Stream_Read_UINT16(s, *type); /* capabilitySetType */ Stream_Read_UINT16(s, *length); /* lengthCapability */ } static void rdp_write_capability_set_header(wStream* s, UINT16 length, UINT16 type) { Stream_Write_UINT16(s, type); /* capabilitySetType */ Stream_Write_UINT16(s, length); /* lengthCapability */ } static size_t rdp_capability_set_start(wStream* s) { size_t header = Stream_GetPosition(s); Stream_Zero(s, CAPSET_HEADER_LENGTH); return header; } static void rdp_capability_set_finish(wStream* s, UINT16 header, UINT16 type) { size_t footer; size_t length; footer = Stream_GetPosition(s); length = footer - header; Stream_SetPosition(s, header); rdp_write_capability_set_header(s, (UINT16)length, type); Stream_SetPosition(s, footer); } /** * Read general capability set.\n * @msdn{cc240549} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_general_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { UINT16 extraFlags; BYTE refreshRectSupport; BYTE suppressOutputSupport; if (length < 24) return FALSE; if (settings->ServerMode) { Stream_Read_UINT16(s, settings->OsMajorType); /* osMajorType (2 bytes) */ Stream_Read_UINT16(s, settings->OsMinorType); /* osMinorType (2 bytes) */ } else { Stream_Seek_UINT16(s); /* osMajorType (2 bytes) */ Stream_Seek_UINT16(s); /* osMinorType (2 bytes) */ } Stream_Seek_UINT16(s); /* protocolVersion (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ Stream_Seek_UINT16(s); /* generalCompressionTypes (2 bytes) */ Stream_Read_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Seek_UINT16(s); /* updateCapabilityFlag (2 bytes) */ Stream_Seek_UINT16(s); /* remoteUnshareFlag (2 bytes) */ Stream_Seek_UINT16(s); /* generalCompressionLevel (2 bytes) */ Stream_Read_UINT8(s, refreshRectSupport); /* refreshRectSupport (1 byte) */ Stream_Read_UINT8(s, suppressOutputSupport); /* suppressOutputSupport (1 byte) */ settings->NoBitmapCompressionHeader = (extraFlags & NO_BITMAP_COMPRESSION_HDR) ? TRUE : FALSE; settings->LongCredentialsSupported = (extraFlags & LONG_CREDENTIALS_SUPPORTED) ? TRUE : FALSE; if (!(extraFlags & FASTPATH_OUTPUT_SUPPORTED)) settings->FastPathOutput = FALSE; if (!(extraFlags & ENC_SALTED_CHECKSUM)) settings->SaltedChecksum = FALSE; if (!settings->ServerMode) { /** * Note: refreshRectSupport and suppressOutputSupport are * server-only flags indicating to the client weather the * respective PDUs are supported. See MS-RDPBCGR 2.2.7.1.1 */ if (!refreshRectSupport) settings->RefreshRect = FALSE; if (!suppressOutputSupport) settings->SuppressOutput = FALSE; } return TRUE; } /** * Write general capability set.\n * @msdn{cc240549} * @param s stream * @param settings settings */ static BOOL rdp_write_general_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT16 extraFlags; if (!Stream_EnsureRemainingCapacity(s, 64)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; extraFlags = 0; if (settings->LongCredentialsSupported) extraFlags |= LONG_CREDENTIALS_SUPPORTED; if (settings->NoBitmapCompressionHeader) extraFlags |= NO_BITMAP_COMPRESSION_HDR; if (settings->AutoReconnectionEnabled) extraFlags |= AUTORECONNECT_SUPPORTED; if (settings->FastPathOutput) extraFlags |= FASTPATH_OUTPUT_SUPPORTED; if (settings->SaltedChecksum) extraFlags |= ENC_SALTED_CHECKSUM; if ((settings->OsMajorType > UINT16_MAX) || (settings->OsMinorType > UINT16_MAX)) { WLog_ERR(TAG, "OsMajorType=%08" PRIx32 ", OsMinorType=%08" PRIx32 " they need to be smaller %04" PRIx16, settings->OsMajorType, settings->OsMinorType, UINT16_MAX); return FALSE; } Stream_Write_UINT16(s, (UINT16)settings->OsMajorType); /* osMajorType (2 bytes) */ Stream_Write_UINT16(s, (UINT16)settings->OsMinorType); /* osMinorType (2 bytes) */ Stream_Write_UINT16(s, CAPS_PROTOCOL_VERSION); /* protocolVersion (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2OctetsA (2 bytes) */ Stream_Write_UINT16(s, 0); /* generalCompressionTypes (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT16(s, 0); /* updateCapabilityFlag (2 bytes) */ Stream_Write_UINT16(s, 0); /* remoteUnshareFlag (2 bytes) */ Stream_Write_UINT16(s, 0); /* generalCompressionLevel (2 bytes) */ Stream_Write_UINT8(s, settings->RefreshRect ? 1 : 0); /* refreshRectSupport (1 byte) */ Stream_Write_UINT8(s, settings->SuppressOutput ? 1 : 0); /* suppressOutputSupport (1 byte) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_GENERAL); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_general_capability_set(wStream* s, UINT16 length) { UINT16 osMajorType; UINT16 osMinorType; UINT16 protocolVersion; UINT16 pad2OctetsA; UINT16 generalCompressionTypes; UINT16 extraFlags; UINT16 updateCapabilityFlag; UINT16 remoteUnshareFlag; UINT16 generalCompressionLevel; BYTE refreshRectSupport; BYTE suppressOutputSupport; if (length < 24) return FALSE; WLog_INFO(TAG, "GeneralCapabilitySet (length %" PRIu16 "):", length); Stream_Read_UINT16(s, osMajorType); /* osMajorType (2 bytes) */ Stream_Read_UINT16(s, osMinorType); /* osMinorType (2 bytes) */ Stream_Read_UINT16(s, protocolVersion); /* protocolVersion (2 bytes) */ Stream_Read_UINT16(s, pad2OctetsA); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT16(s, generalCompressionTypes); /* generalCompressionTypes (2 bytes) */ Stream_Read_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Read_UINT16(s, updateCapabilityFlag); /* updateCapabilityFlag (2 bytes) */ Stream_Read_UINT16(s, remoteUnshareFlag); /* remoteUnshareFlag (2 bytes) */ Stream_Read_UINT16(s, generalCompressionLevel); /* generalCompressionLevel (2 bytes) */ Stream_Read_UINT8(s, refreshRectSupport); /* refreshRectSupport (1 byte) */ Stream_Read_UINT8(s, suppressOutputSupport); /* suppressOutputSupport (1 byte) */ WLog_INFO(TAG, "\tosMajorType: 0x%04" PRIX16 "", osMajorType); WLog_INFO(TAG, "\tosMinorType: 0x%04" PRIX16 "", osMinorType); WLog_INFO(TAG, "\tprotocolVersion: 0x%04" PRIX16 "", protocolVersion); WLog_INFO(TAG, "\tpad2OctetsA: 0x%04" PRIX16 "", pad2OctetsA); WLog_INFO(TAG, "\tgeneralCompressionTypes: 0x%04" PRIX16 "", generalCompressionTypes); WLog_INFO(TAG, "\textraFlags: 0x%04" PRIX16 "", extraFlags); WLog_INFO(TAG, "\tupdateCapabilityFlag: 0x%04" PRIX16 "", updateCapabilityFlag); WLog_INFO(TAG, "\tremoteUnshareFlag: 0x%04" PRIX16 "", remoteUnshareFlag); WLog_INFO(TAG, "\tgeneralCompressionLevel: 0x%04" PRIX16 "", generalCompressionLevel); WLog_INFO(TAG, "\trefreshRectSupport: 0x%02" PRIX8 "", refreshRectSupport); WLog_INFO(TAG, "\tsuppressOutputSupport: 0x%02" PRIX8 "", suppressOutputSupport); return TRUE; } #endif /** * Read bitmap capability set.\n * @msdn{cc240554} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_bitmap_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { BYTE drawingFlags; UINT16 desktopWidth; UINT16 desktopHeight; UINT16 desktopResizeFlag; UINT16 preferredBitsPerPixel; if (length < 28) return FALSE; Stream_Read_UINT16(s, preferredBitsPerPixel); /* preferredBitsPerPixel (2 bytes) */ Stream_Seek_UINT16(s); /* receive1BitPerPixel (2 bytes) */ Stream_Seek_UINT16(s); /* receive4BitsPerPixel (2 bytes) */ Stream_Seek_UINT16(s); /* receive8BitsPerPixel (2 bytes) */ Stream_Read_UINT16(s, desktopWidth); /* desktopWidth (2 bytes) */ Stream_Read_UINT16(s, desktopHeight); /* desktopHeight (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ Stream_Read_UINT16(s, desktopResizeFlag); /* desktopResizeFlag (2 bytes) */ Stream_Seek_UINT16(s); /* bitmapCompressionFlag (2 bytes) */ Stream_Seek_UINT8(s); /* highColorFlags (1 byte) */ Stream_Read_UINT8(s, drawingFlags); /* drawingFlags (1 byte) */ Stream_Seek_UINT16(s); /* multipleRectangleSupport (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsB (2 bytes) */ if (!settings->ServerMode && (preferredBitsPerPixel != settings->ColorDepth)) { /* The client must respect the actual color depth used by the server */ settings->ColorDepth = preferredBitsPerPixel; } if (desktopResizeFlag == FALSE) settings->DesktopResize = FALSE; if (!settings->ServerMode && settings->DesktopResize) { /* The server may request a different desktop size during Deactivation-Reactivation sequence */ settings->DesktopWidth = desktopWidth; settings->DesktopHeight = desktopHeight; } if (settings->DrawAllowSkipAlpha) settings->DrawAllowSkipAlpha = (drawingFlags & DRAW_ALLOW_SKIP_ALPHA) ? TRUE : FALSE; if (settings->DrawAllowDynamicColorFidelity) settings->DrawAllowDynamicColorFidelity = (drawingFlags & DRAW_ALLOW_DYNAMIC_COLOR_FIDELITY) ? TRUE : FALSE; if (settings->DrawAllowColorSubsampling) settings->DrawAllowColorSubsampling = (drawingFlags & DRAW_ALLOW_COLOR_SUBSAMPLING) ? TRUE : FALSE; return TRUE; } /** * Write bitmap capability set.\n * @msdn{cc240554} * @param s stream * @param settings settings */ static BOOL rdp_write_bitmap_capability_set(wStream* s, const rdpSettings* settings) { size_t header; BYTE drawingFlags = 0; UINT16 preferredBitsPerPixel; if (!Stream_EnsureRemainingCapacity(s, 64)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; if (settings->DrawAllowSkipAlpha) drawingFlags |= DRAW_ALLOW_SKIP_ALPHA; if (settings->DrawAllowDynamicColorFidelity) drawingFlags |= DRAW_ALLOW_DYNAMIC_COLOR_FIDELITY; if (settings->DrawAllowColorSubsampling) drawingFlags |= DRAW_ALLOW_COLOR_SUBSAMPLING; /* currently unimplemented */ /* While bitmap_decode.c now implements YCoCg, in turning it * on we have found Microsoft is inconsistent on whether to invert R & B. * And it's not only from one server to another; on Win7/2008R2, it appears * to send the main content with a different inversion than the Windows * button! So... don't advertise that we support YCoCg and the server * will not send it. YCoCg is still needed for EGFX, but it at least * appears consistent in its use. */ if ((settings->ColorDepth > UINT16_MAX) || (settings->DesktopWidth > UINT16_MAX) || (settings->DesktopHeight > UINT16_MAX) || (settings->DesktopResize > UINT16_MAX)) return FALSE; if (settings->RdpVersion >= RDP_VERSION_5_PLUS) preferredBitsPerPixel = (UINT16)settings->ColorDepth; else preferredBitsPerPixel = 8; Stream_Write_UINT16(s, preferredBitsPerPixel); /* preferredBitsPerPixel (2 bytes) */ Stream_Write_UINT16(s, 1); /* receive1BitPerPixel (2 bytes) */ Stream_Write_UINT16(s, 1); /* receive4BitsPerPixel (2 bytes) */ Stream_Write_UINT16(s, 1); /* receive8BitsPerPixel (2 bytes) */ Stream_Write_UINT16(s, (UINT16)settings->DesktopWidth); /* desktopWidth (2 bytes) */ Stream_Write_UINT16(s, (UINT16)settings->DesktopHeight); /* desktopHeight (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2Octets (2 bytes) */ Stream_Write_UINT16(s, (UINT16)settings->DesktopResize); /* desktopResizeFlag (2 bytes) */ Stream_Write_UINT16(s, 1); /* bitmapCompressionFlag (2 bytes) */ Stream_Write_UINT8(s, 0); /* highColorFlags (1 byte) */ Stream_Write_UINT8(s, drawingFlags); /* drawingFlags (1 byte) */ Stream_Write_UINT16(s, 1); /* multipleRectangleSupport (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2OctetsB (2 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_BITMAP); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_bitmap_capability_set(wStream* s, UINT16 length) { UINT16 preferredBitsPerPixel; UINT16 receive1BitPerPixel; UINT16 receive4BitsPerPixel; UINT16 receive8BitsPerPixel; UINT16 desktopWidth; UINT16 desktopHeight; UINT16 pad2Octets; UINT16 desktopResizeFlag; UINT16 bitmapCompressionFlag; BYTE highColorFlags; BYTE drawingFlags; UINT16 multipleRectangleSupport; UINT16 pad2OctetsB; WLog_INFO(TAG, "BitmapCapabilitySet (length %" PRIu16 "):", length); if (length < 28) return FALSE; Stream_Read_UINT16(s, preferredBitsPerPixel); /* preferredBitsPerPixel (2 bytes) */ Stream_Read_UINT16(s, receive1BitPerPixel); /* receive1BitPerPixel (2 bytes) */ Stream_Read_UINT16(s, receive4BitsPerPixel); /* receive4BitsPerPixel (2 bytes) */ Stream_Read_UINT16(s, receive8BitsPerPixel); /* receive8BitsPerPixel (2 bytes) */ Stream_Read_UINT16(s, desktopWidth); /* desktopWidth (2 bytes) */ Stream_Read_UINT16(s, desktopHeight); /* desktopHeight (2 bytes) */ Stream_Read_UINT16(s, pad2Octets); /* pad2Octets (2 bytes) */ Stream_Read_UINT16(s, desktopResizeFlag); /* desktopResizeFlag (2 bytes) */ Stream_Read_UINT16(s, bitmapCompressionFlag); /* bitmapCompressionFlag (2 bytes) */ Stream_Read_UINT8(s, highColorFlags); /* highColorFlags (1 byte) */ Stream_Read_UINT8(s, drawingFlags); /* drawingFlags (1 byte) */ Stream_Read_UINT16(s, multipleRectangleSupport); /* multipleRectangleSupport (2 bytes) */ Stream_Read_UINT16(s, pad2OctetsB); /* pad2OctetsB (2 bytes) */ WLog_INFO(TAG, "\tpreferredBitsPerPixel: 0x%04" PRIX16 "", preferredBitsPerPixel); WLog_INFO(TAG, "\treceive1BitPerPixel: 0x%04" PRIX16 "", receive1BitPerPixel); WLog_INFO(TAG, "\treceive4BitsPerPixel: 0x%04" PRIX16 "", receive4BitsPerPixel); WLog_INFO(TAG, "\treceive8BitsPerPixel: 0x%04" PRIX16 "", receive8BitsPerPixel); WLog_INFO(TAG, "\tdesktopWidth: 0x%04" PRIX16 "", desktopWidth); WLog_INFO(TAG, "\tdesktopHeight: 0x%04" PRIX16 "", desktopHeight); WLog_INFO(TAG, "\tpad2Octets: 0x%04" PRIX16 "", pad2Octets); WLog_INFO(TAG, "\tdesktopResizeFlag: 0x%04" PRIX16 "", desktopResizeFlag); WLog_INFO(TAG, "\tbitmapCompressionFlag: 0x%04" PRIX16 "", bitmapCompressionFlag); WLog_INFO(TAG, "\thighColorFlags: 0x%02" PRIX8 "", highColorFlags); WLog_INFO(TAG, "\tdrawingFlags: 0x%02" PRIX8 "", drawingFlags); WLog_INFO(TAG, "\tmultipleRectangleSupport: 0x%04" PRIX16 "", multipleRectangleSupport); WLog_INFO(TAG, "\tpad2OctetsB: 0x%04" PRIX16 "", pad2OctetsB); return TRUE; } #endif /** * Read order capability set.\n * @msdn{cc240556} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_order_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { int i; UINT16 orderFlags; BYTE orderSupport[32]; UINT16 orderSupportExFlags; BOOL BitmapCacheV3Enabled = FALSE; BOOL FrameMarkerCommandEnabled = FALSE; if (length < 88) return FALSE; Stream_Seek(s, 16); /* terminalDescriptor (16 bytes) */ Stream_Seek_UINT32(s); /* pad4OctetsA (4 bytes) */ Stream_Seek_UINT16(s); /* desktopSaveXGranularity (2 bytes) */ Stream_Seek_UINT16(s); /* desktopSaveYGranularity (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ Stream_Seek_UINT16(s); /* maximumOrderLevel (2 bytes) */ Stream_Seek_UINT16(s); /* numberFonts (2 bytes) */ Stream_Read_UINT16(s, orderFlags); /* orderFlags (2 bytes) */ Stream_Read(s, orderSupport, 32); /* orderSupport (32 bytes) */ Stream_Seek_UINT16(s); /* textFlags (2 bytes) */ Stream_Read_UINT16(s, orderSupportExFlags); /* orderSupportExFlags (2 bytes) */ Stream_Seek_UINT32(s); /* pad4OctetsB (4 bytes) */ Stream_Seek_UINT32(s); /* desktopSaveSize (4 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsC (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsD (2 bytes) */ Stream_Seek_UINT16(s); /* textANSICodePage (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsE (2 bytes) */ for (i = 0; i < 32; i++) { if (orderSupport[i] == FALSE) settings->OrderSupport[i] = FALSE; } if (orderFlags & ORDER_FLAGS_EXTRA_SUPPORT) { if (orderSupportExFlags & CACHE_BITMAP_V3_SUPPORT) BitmapCacheV3Enabled = TRUE; if (orderSupportExFlags & ALTSEC_FRAME_MARKER_SUPPORT) FrameMarkerCommandEnabled = TRUE; } if (settings->BitmapCacheV3Enabled && BitmapCacheV3Enabled) settings->BitmapCacheVersion = 3; else settings->BitmapCacheV3Enabled = FALSE; if (settings->FrameMarkerCommandEnabled && !FrameMarkerCommandEnabled) settings->FrameMarkerCommandEnabled = FALSE; return TRUE; } /** * Write order capability set.\n * @msdn{cc240556} * @param s stream * @param settings settings */ static BOOL rdp_write_order_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT16 orderFlags; UINT16 orderSupportExFlags; UINT16 textANSICodePage = 0; if (!Stream_EnsureRemainingCapacity(s, 64)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; /* see [MSDN-CP]: http://msdn.microsoft.com/en-us/library/dd317756 */ if (!settings->ServerMode) textANSICodePage = CP_UTF8; /* Unicode (UTF-8) */ orderSupportExFlags = 0; orderFlags = NEGOTIATE_ORDER_SUPPORT | ZERO_BOUNDS_DELTA_SUPPORT | COLOR_INDEX_SUPPORT; if (settings->BitmapCacheV3Enabled) { orderSupportExFlags |= CACHE_BITMAP_V3_SUPPORT; orderFlags |= ORDER_FLAGS_EXTRA_SUPPORT; } if (settings->FrameMarkerCommandEnabled) { orderSupportExFlags |= ALTSEC_FRAME_MARKER_SUPPORT; orderFlags |= ORDER_FLAGS_EXTRA_SUPPORT; } Stream_Zero(s, 16); /* terminalDescriptor (16 bytes) */ Stream_Write_UINT32(s, 0); /* pad4OctetsA (4 bytes) */ Stream_Write_UINT16(s, 1); /* desktopSaveXGranularity (2 bytes) */ Stream_Write_UINT16(s, 20); /* desktopSaveYGranularity (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2OctetsA (2 bytes) */ Stream_Write_UINT16(s, 1); /* maximumOrderLevel (2 bytes) */ Stream_Write_UINT16(s, 0); /* numberFonts (2 bytes) */ Stream_Write_UINT16(s, orderFlags); /* orderFlags (2 bytes) */ Stream_Write(s, settings->OrderSupport, 32); /* orderSupport (32 bytes) */ Stream_Write_UINT16(s, 0); /* textFlags (2 bytes) */ Stream_Write_UINT16(s, orderSupportExFlags); /* orderSupportExFlags (2 bytes) */ Stream_Write_UINT32(s, 0); /* pad4OctetsB (4 bytes) */ Stream_Write_UINT32(s, 230400); /* desktopSaveSize (4 bytes) */ Stream_Write_UINT16(s, 0); /* pad2OctetsC (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2OctetsD (2 bytes) */ Stream_Write_UINT16(s, textANSICodePage); /* textANSICodePage (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2OctetsE (2 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_ORDER); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_order_capability_set(wStream* s, UINT16 length) { BYTE terminalDescriptor[16]; UINT32 pad4OctetsA; UINT16 desktopSaveXGranularity; UINT16 desktopSaveYGranularity; UINT16 pad2OctetsA; UINT16 maximumOrderLevel; UINT16 numberFonts; UINT16 orderFlags; BYTE orderSupport[32]; UINT16 textFlags; UINT16 orderSupportExFlags; UINT32 pad4OctetsB; UINT32 desktopSaveSize; UINT16 pad2OctetsC; UINT16 pad2OctetsD; UINT16 textANSICodePage; UINT16 pad2OctetsE; WLog_INFO(TAG, "OrderCapabilitySet (length %" PRIu16 "):", length); if (length < 88) return FALSE; Stream_Read(s, terminalDescriptor, 16); /* terminalDescriptor (16 bytes) */ Stream_Read_UINT32(s, pad4OctetsA); /* pad4OctetsA (4 bytes) */ Stream_Read_UINT16(s, desktopSaveXGranularity); /* desktopSaveXGranularity (2 bytes) */ Stream_Read_UINT16(s, desktopSaveYGranularity); /* desktopSaveYGranularity (2 bytes) */ Stream_Read_UINT16(s, pad2OctetsA); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT16(s, maximumOrderLevel); /* maximumOrderLevel (2 bytes) */ Stream_Read_UINT16(s, numberFonts); /* numberFonts (2 bytes) */ Stream_Read_UINT16(s, orderFlags); /* orderFlags (2 bytes) */ Stream_Read(s, orderSupport, 32); /* orderSupport (32 bytes) */ Stream_Read_UINT16(s, textFlags); /* textFlags (2 bytes) */ Stream_Read_UINT16(s, orderSupportExFlags); /* orderSupportExFlags (2 bytes) */ Stream_Read_UINT32(s, pad4OctetsB); /* pad4OctetsB (4 bytes) */ Stream_Read_UINT32(s, desktopSaveSize); /* desktopSaveSize (4 bytes) */ Stream_Read_UINT16(s, pad2OctetsC); /* pad2OctetsC (2 bytes) */ Stream_Read_UINT16(s, pad2OctetsD); /* pad2OctetsD (2 bytes) */ Stream_Read_UINT16(s, textANSICodePage); /* textANSICodePage (2 bytes) */ Stream_Read_UINT16(s, pad2OctetsE); /* pad2OctetsE (2 bytes) */ WLog_INFO(TAG, "\tpad4OctetsA: 0x%08" PRIX32 "", pad4OctetsA); WLog_INFO(TAG, "\tdesktopSaveXGranularity: 0x%04" PRIX16 "", desktopSaveXGranularity); WLog_INFO(TAG, "\tdesktopSaveYGranularity: 0x%04" PRIX16 "", desktopSaveYGranularity); WLog_INFO(TAG, "\tpad2OctetsA: 0x%04" PRIX16 "", pad2OctetsA); WLog_INFO(TAG, "\tmaximumOrderLevel: 0x%04" PRIX16 "", maximumOrderLevel); WLog_INFO(TAG, "\tnumberFonts: 0x%04" PRIX16 "", numberFonts); WLog_INFO(TAG, "\torderFlags: 0x%04" PRIX16 "", orderFlags); WLog_INFO(TAG, "\torderSupport:"); WLog_INFO(TAG, "\t\tDSTBLT: %" PRIu8 "", orderSupport[NEG_DSTBLT_INDEX]); WLog_INFO(TAG, "\t\tPATBLT: %" PRIu8 "", orderSupport[NEG_PATBLT_INDEX]); WLog_INFO(TAG, "\t\tSCRBLT: %" PRIu8 "", orderSupport[NEG_SCRBLT_INDEX]); WLog_INFO(TAG, "\t\tMEMBLT: %" PRIu8 "", orderSupport[NEG_MEMBLT_INDEX]); WLog_INFO(TAG, "\t\tMEM3BLT: %" PRIu8 "", orderSupport[NEG_MEM3BLT_INDEX]); WLog_INFO(TAG, "\t\tATEXTOUT: %" PRIu8 "", orderSupport[NEG_ATEXTOUT_INDEX]); WLog_INFO(TAG, "\t\tAEXTTEXTOUT: %" PRIu8 "", orderSupport[NEG_AEXTTEXTOUT_INDEX]); WLog_INFO(TAG, "\t\tDRAWNINEGRID: %" PRIu8 "", orderSupport[NEG_DRAWNINEGRID_INDEX]); WLog_INFO(TAG, "\t\tLINETO: %" PRIu8 "", orderSupport[NEG_LINETO_INDEX]); WLog_INFO(TAG, "\t\tMULTI_DRAWNINEGRID: %" PRIu8 "", orderSupport[NEG_MULTI_DRAWNINEGRID_INDEX]); WLog_INFO(TAG, "\t\tOPAQUE_RECT: %" PRIu8 "", orderSupport[NEG_OPAQUE_RECT_INDEX]); WLog_INFO(TAG, "\t\tSAVEBITMAP: %" PRIu8 "", orderSupport[NEG_SAVEBITMAP_INDEX]); WLog_INFO(TAG, "\t\tWTEXTOUT: %" PRIu8 "", orderSupport[NEG_WTEXTOUT_INDEX]); WLog_INFO(TAG, "\t\tMEMBLT_V2: %" PRIu8 "", orderSupport[NEG_MEMBLT_V2_INDEX]); WLog_INFO(TAG, "\t\tMEM3BLT_V2: %" PRIu8 "", orderSupport[NEG_MEM3BLT_V2_INDEX]); WLog_INFO(TAG, "\t\tMULTIDSTBLT: %" PRIu8 "", orderSupport[NEG_MULTIDSTBLT_INDEX]); WLog_INFO(TAG, "\t\tMULTIPATBLT: %" PRIu8 "", orderSupport[NEG_MULTIPATBLT_INDEX]); WLog_INFO(TAG, "\t\tMULTISCRBLT: %" PRIu8 "", orderSupport[NEG_MULTISCRBLT_INDEX]); WLog_INFO(TAG, "\t\tMULTIOPAQUERECT: %" PRIu8 "", orderSupport[NEG_MULTIOPAQUERECT_INDEX]); WLog_INFO(TAG, "\t\tFAST_INDEX: %" PRIu8 "", orderSupport[NEG_FAST_INDEX_INDEX]); WLog_INFO(TAG, "\t\tPOLYGON_SC: %" PRIu8 "", orderSupport[NEG_POLYGON_SC_INDEX]); WLog_INFO(TAG, "\t\tPOLYGON_CB: %" PRIu8 "", orderSupport[NEG_POLYGON_CB_INDEX]); WLog_INFO(TAG, "\t\tPOLYLINE: %" PRIu8 "", orderSupport[NEG_POLYLINE_INDEX]); WLog_INFO(TAG, "\t\tUNUSED23: %" PRIu8 "", orderSupport[NEG_UNUSED23_INDEX]); WLog_INFO(TAG, "\t\tFAST_GLYPH: %" PRIu8 "", orderSupport[NEG_FAST_GLYPH_INDEX]); WLog_INFO(TAG, "\t\tELLIPSE_SC: %" PRIu8 "", orderSupport[NEG_ELLIPSE_SC_INDEX]); WLog_INFO(TAG, "\t\tELLIPSE_CB: %" PRIu8 "", orderSupport[NEG_ELLIPSE_CB_INDEX]); WLog_INFO(TAG, "\t\tGLYPH_INDEX: %" PRIu8 "", orderSupport[NEG_GLYPH_INDEX_INDEX]); WLog_INFO(TAG, "\t\tGLYPH_WEXTTEXTOUT: %" PRIu8 "", orderSupport[NEG_GLYPH_WEXTTEXTOUT_INDEX]); WLog_INFO(TAG, "\t\tGLYPH_WLONGTEXTOUT: %" PRIu8 "", orderSupport[NEG_GLYPH_WLONGTEXTOUT_INDEX]); WLog_INFO(TAG, "\t\tGLYPH_WLONGEXTTEXTOUT: %" PRIu8 "", orderSupport[NEG_GLYPH_WLONGEXTTEXTOUT_INDEX]); WLog_INFO(TAG, "\t\tUNUSED31: %" PRIu8 "", orderSupport[NEG_UNUSED31_INDEX]); WLog_INFO(TAG, "\ttextFlags: 0x%04" PRIX16 "", textFlags); WLog_INFO(TAG, "\torderSupportExFlags: 0x%04" PRIX16 "", orderSupportExFlags); WLog_INFO(TAG, "\tpad4OctetsB: 0x%08" PRIX32 "", pad4OctetsB); WLog_INFO(TAG, "\tdesktopSaveSize: 0x%08" PRIX32 "", desktopSaveSize); WLog_INFO(TAG, "\tpad2OctetsC: 0x%04" PRIX16 "", pad2OctetsC); WLog_INFO(TAG, "\tpad2OctetsD: 0x%04" PRIX16 "", pad2OctetsD); WLog_INFO(TAG, "\ttextANSICodePage: 0x%04" PRIX16 "", textANSICodePage); WLog_INFO(TAG, "\tpad2OctetsE: 0x%04" PRIX16 "", pad2OctetsE); return TRUE; } #endif /** * Read bitmap cache capability set.\n * @msdn{cc240559} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_bitmap_cache_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { WINPR_UNUSED(settings); if (length < 40) return FALSE; Stream_Seek_UINT32(s); /* pad1 (4 bytes) */ Stream_Seek_UINT32(s); /* pad2 (4 bytes) */ Stream_Seek_UINT32(s); /* pad3 (4 bytes) */ Stream_Seek_UINT32(s); /* pad4 (4 bytes) */ Stream_Seek_UINT32(s); /* pad5 (4 bytes) */ Stream_Seek_UINT32(s); /* pad6 (4 bytes) */ Stream_Seek_UINT16(s); /* Cache0Entries (2 bytes) */ Stream_Seek_UINT16(s); /* Cache0MaximumCellSize (2 bytes) */ Stream_Seek_UINT16(s); /* Cache1Entries (2 bytes) */ Stream_Seek_UINT16(s); /* Cache1MaximumCellSize (2 bytes) */ Stream_Seek_UINT16(s); /* Cache2Entries (2 bytes) */ Stream_Seek_UINT16(s); /* Cache2MaximumCellSize (2 bytes) */ return TRUE; } /** * Write bitmap cache capability set.\n * @msdn{cc240559} * @param s stream * @param settings settings */ static BOOL rdp_write_bitmap_cache_capability_set(wStream* s, const rdpSettings* settings) { UINT32 bpp; size_t header; UINT32 size; if (!Stream_EnsureRemainingCapacity(s, 64)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; bpp = (settings->ColorDepth + 7) / 8; if (bpp > UINT16_MAX) return FALSE; Stream_Write_UINT32(s, 0); /* pad1 (4 bytes) */ Stream_Write_UINT32(s, 0); /* pad2 (4 bytes) */ Stream_Write_UINT32(s, 0); /* pad3 (4 bytes) */ Stream_Write_UINT32(s, 0); /* pad4 (4 bytes) */ Stream_Write_UINT32(s, 0); /* pad5 (4 bytes) */ Stream_Write_UINT32(s, 0); /* pad6 (4 bytes) */ size = bpp * 256; if (size > UINT16_MAX) return FALSE; Stream_Write_UINT16(s, 200); /* Cache0Entries (2 bytes) */ Stream_Write_UINT16(s, (UINT16)size); /* Cache0MaximumCellSize (2 bytes) */ size = bpp * 1024; if (size > UINT16_MAX) return FALSE; Stream_Write_UINT16(s, 600); /* Cache1Entries (2 bytes) */ Stream_Write_UINT16(s, (UINT16)size); /* Cache1MaximumCellSize (2 bytes) */ size = bpp * 4096; if (size > UINT16_MAX) return FALSE; Stream_Write_UINT16(s, 1000); /* Cache2Entries (2 bytes) */ Stream_Write_UINT16(s, (UINT16)size); /* Cache2MaximumCellSize (2 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_BITMAP_CACHE); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_bitmap_cache_capability_set(wStream* s, UINT16 length) { UINT32 pad1, pad2, pad3; UINT32 pad4, pad5, pad6; UINT16 Cache0Entries; UINT16 Cache0MaximumCellSize; UINT16 Cache1Entries; UINT16 Cache1MaximumCellSize; UINT16 Cache2Entries; UINT16 Cache2MaximumCellSize; WLog_INFO(TAG, "BitmapCacheCapabilitySet (length %" PRIu16 "):", length); if (length < 40) return FALSE; Stream_Read_UINT32(s, pad1); /* pad1 (4 bytes) */ Stream_Read_UINT32(s, pad2); /* pad2 (4 bytes) */ Stream_Read_UINT32(s, pad3); /* pad3 (4 bytes) */ Stream_Read_UINT32(s, pad4); /* pad4 (4 bytes) */ Stream_Read_UINT32(s, pad5); /* pad5 (4 bytes) */ Stream_Read_UINT32(s, pad6); /* pad6 (4 bytes) */ Stream_Read_UINT16(s, Cache0Entries); /* Cache0Entries (2 bytes) */ Stream_Read_UINT16(s, Cache0MaximumCellSize); /* Cache0MaximumCellSize (2 bytes) */ Stream_Read_UINT16(s, Cache1Entries); /* Cache1Entries (2 bytes) */ Stream_Read_UINT16(s, Cache1MaximumCellSize); /* Cache1MaximumCellSize (2 bytes) */ Stream_Read_UINT16(s, Cache2Entries); /* Cache2Entries (2 bytes) */ Stream_Read_UINT16(s, Cache2MaximumCellSize); /* Cache2MaximumCellSize (2 bytes) */ WLog_INFO(TAG, "\tpad1: 0x%08" PRIX32 "", pad1); WLog_INFO(TAG, "\tpad2: 0x%08" PRIX32 "", pad2); WLog_INFO(TAG, "\tpad3: 0x%08" PRIX32 "", pad3); WLog_INFO(TAG, "\tpad4: 0x%08" PRIX32 "", pad4); WLog_INFO(TAG, "\tpad5: 0x%08" PRIX32 "", pad5); WLog_INFO(TAG, "\tpad6: 0x%08" PRIX32 "", pad6); WLog_INFO(TAG, "\tCache0Entries: 0x%04" PRIX16 "", Cache0Entries); WLog_INFO(TAG, "\tCache0MaximumCellSize: 0x%04" PRIX16 "", Cache0MaximumCellSize); WLog_INFO(TAG, "\tCache1Entries: 0x%04" PRIX16 "", Cache1Entries); WLog_INFO(TAG, "\tCache1MaximumCellSize: 0x%04" PRIX16 "", Cache1MaximumCellSize); WLog_INFO(TAG, "\tCache2Entries: 0x%04" PRIX16 "", Cache2Entries); WLog_INFO(TAG, "\tCache2MaximumCellSize: 0x%04" PRIX16 "", Cache2MaximumCellSize); return TRUE; } #endif /** * Read control capability set.\n * @msdn{cc240568} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_control_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { WINPR_UNUSED(settings); if (length < 12) return FALSE; Stream_Seek_UINT16(s); /* controlFlags (2 bytes) */ Stream_Seek_UINT16(s); /* remoteDetachFlag (2 bytes) */ Stream_Seek_UINT16(s); /* controlInterest (2 bytes) */ Stream_Seek_UINT16(s); /* detachInterest (2 bytes) */ return TRUE; } /** * Write control capability set.\n * @msdn{cc240568} * @param s stream * @param settings settings */ static BOOL rdp_write_control_capability_set(wStream* s, const rdpSettings* settings) { size_t header; WINPR_UNUSED(settings); if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; Stream_Write_UINT16(s, 0); /* controlFlags (2 bytes) */ Stream_Write_UINT16(s, 0); /* remoteDetachFlag (2 bytes) */ Stream_Write_UINT16(s, 2); /* controlInterest (2 bytes) */ Stream_Write_UINT16(s, 2); /* detachInterest (2 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_CONTROL); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_control_capability_set(wStream* s, UINT16 length) { UINT16 controlFlags; UINT16 remoteDetachFlag; UINT16 controlInterest; UINT16 detachInterest; WLog_INFO(TAG, "ControlCapabilitySet (length %" PRIu16 "):", length); if (length < 12) return FALSE; Stream_Read_UINT16(s, controlFlags); /* controlFlags (2 bytes) */ Stream_Read_UINT16(s, remoteDetachFlag); /* remoteDetachFlag (2 bytes) */ Stream_Read_UINT16(s, controlInterest); /* controlInterest (2 bytes) */ Stream_Read_UINT16(s, detachInterest); /* detachInterest (2 bytes) */ WLog_INFO(TAG, "\tcontrolFlags: 0x%04" PRIX16 "", controlFlags); WLog_INFO(TAG, "\tremoteDetachFlag: 0x%04" PRIX16 "", remoteDetachFlag); WLog_INFO(TAG, "\tcontrolInterest: 0x%04" PRIX16 "", controlInterest); WLog_INFO(TAG, "\tdetachInterest: 0x%04" PRIX16 "", detachInterest); return TRUE; } #endif /** * Read window activation capability set.\n * @msdn{cc240569} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_window_activation_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { WINPR_UNUSED(settings); if (length < 12) return FALSE; Stream_Seek_UINT16(s); /* helpKeyFlag (2 bytes) */ Stream_Seek_UINT16(s); /* helpKeyIndexFlag (2 bytes) */ Stream_Seek_UINT16(s); /* helpExtendedKeyFlag (2 bytes) */ Stream_Seek_UINT16(s); /* windowManagerKeyFlag (2 bytes) */ return TRUE; } /** * Write window activation capability set.\n * @msdn{cc240569} * @param s stream * @param settings settings */ static BOOL rdp_write_window_activation_capability_set(wStream* s, const rdpSettings* settings) { size_t header; WINPR_UNUSED(settings); if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; Stream_Write_UINT16(s, 0); /* helpKeyFlag (2 bytes) */ Stream_Write_UINT16(s, 0); /* helpKeyIndexFlag (2 bytes) */ Stream_Write_UINT16(s, 0); /* helpExtendedKeyFlag (2 bytes) */ Stream_Write_UINT16(s, 0); /* windowManagerKeyFlag (2 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_ACTIVATION); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_window_activation_capability_set(wStream* s, UINT16 length) { UINT16 helpKeyFlag; UINT16 helpKeyIndexFlag; UINT16 helpExtendedKeyFlag; UINT16 windowManagerKeyFlag; WLog_INFO(TAG, "WindowActivationCapabilitySet (length %" PRIu16 "):", length); if (length < 12) return FALSE; Stream_Read_UINT16(s, helpKeyFlag); /* helpKeyFlag (2 bytes) */ Stream_Read_UINT16(s, helpKeyIndexFlag); /* helpKeyIndexFlag (2 bytes) */ Stream_Read_UINT16(s, helpExtendedKeyFlag); /* helpExtendedKeyFlag (2 bytes) */ Stream_Read_UINT16(s, windowManagerKeyFlag); /* windowManagerKeyFlag (2 bytes) */ WLog_INFO(TAG, "\thelpKeyFlag: 0x%04" PRIX16 "", helpKeyFlag); WLog_INFO(TAG, "\thelpKeyIndexFlag: 0x%04" PRIX16 "", helpKeyIndexFlag); WLog_INFO(TAG, "\thelpExtendedKeyFlag: 0x%04" PRIX16 "", helpExtendedKeyFlag); WLog_INFO(TAG, "\twindowManagerKeyFlag: 0x%04" PRIX16 "", windowManagerKeyFlag); return TRUE; } #endif /** * Read pointer capability set.\n * @msdn{cc240562} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_pointer_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { UINT16 colorPointerFlag; UINT16 colorPointerCacheSize; UINT16 pointerCacheSize; if (length < 8) return FALSE; Stream_Read_UINT16(s, colorPointerFlag); /* colorPointerFlag (2 bytes) */ Stream_Read_UINT16(s, colorPointerCacheSize); /* colorPointerCacheSize (2 bytes) */ /* pointerCacheSize is optional */ if (length >= 10) Stream_Read_UINT16(s, pointerCacheSize); /* pointerCacheSize (2 bytes) */ else pointerCacheSize = 0; if (colorPointerFlag == FALSE) settings->ColorPointerFlag = FALSE; if (settings->ServerMode) { settings->PointerCacheSize = pointerCacheSize; } return TRUE; } /** * Write pointer capability set.\n * @msdn{cc240562} * @param s stream * @param settings settings */ static BOOL rdp_write_pointer_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT16 colorPointerFlag; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; if (settings->PointerCacheSize > UINT16_MAX) return FALSE; colorPointerFlag = (settings->ColorPointerFlag) ? 1 : 0; Stream_Write_UINT16(s, colorPointerFlag); /* colorPointerFlag (2 bytes) */ Stream_Write_UINT16(s, (UINT16)settings->PointerCacheSize); /* colorPointerCacheSize (2 bytes) */ if (settings->LargePointerFlag) { Stream_Write_UINT16(s, (UINT16)settings->PointerCacheSize); /* pointerCacheSize (2 bytes) */ } rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_POINTER); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_pointer_capability_set(wStream* s, UINT16 length) { UINT16 colorPointerFlag; UINT16 colorPointerCacheSize; UINT16 pointerCacheSize; if (length < 10) return FALSE; WLog_INFO(TAG, "PointerCapabilitySet (length %" PRIu16 "):", length); Stream_Read_UINT16(s, colorPointerFlag); /* colorPointerFlag (2 bytes) */ Stream_Read_UINT16(s, colorPointerCacheSize); /* colorPointerCacheSize (2 bytes) */ Stream_Read_UINT16(s, pointerCacheSize); /* pointerCacheSize (2 bytes) */ WLog_INFO(TAG, "\tcolorPointerFlag: 0x%04" PRIX16 "", colorPointerFlag); WLog_INFO(TAG, "\tcolorPointerCacheSize: 0x%04" PRIX16 "", colorPointerCacheSize); WLog_INFO(TAG, "\tpointerCacheSize: 0x%04" PRIX16 "", pointerCacheSize); return TRUE; } #endif /** * Read share capability set.\n * @msdn{cc240570} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_share_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { WINPR_UNUSED(settings); if (length < 8) return FALSE; Stream_Seek_UINT16(s); /* nodeId (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ return TRUE; } /** * Write share capability set.\n * @msdn{cc240570} * @param s stream * @param settings settings */ static BOOL rdp_write_share_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT16 nodeId; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; nodeId = (settings->ServerMode) ? 0x03EA : 0; Stream_Write_UINT16(s, nodeId); /* nodeId (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2Octets (2 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_SHARE); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_share_capability_set(wStream* s, UINT16 length) { UINT16 nodeId; UINT16 pad2Octets; WLog_INFO(TAG, "ShareCapabilitySet (length %" PRIu16 "):", length); if (length < 8) return FALSE; Stream_Read_UINT16(s, nodeId); /* nodeId (2 bytes) */ Stream_Read_UINT16(s, pad2Octets); /* pad2Octets (2 bytes) */ WLog_INFO(TAG, "\tnodeId: 0x%04" PRIX16 "", nodeId); WLog_INFO(TAG, "\tpad2Octets: 0x%04" PRIX16 "", pad2Octets); return TRUE; } #endif /** * Read color cache capability set.\n * @msdn{cc241564} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_color_cache_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { WINPR_UNUSED(settings); if (length < 8) return FALSE; Stream_Seek_UINT16(s); /* colorTableCacheSize (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ return TRUE; } /** * Write color cache capability set.\n * @msdn{cc241564} * @param s stream * @param settings settings */ static BOOL rdp_write_color_cache_capability_set(wStream* s, const rdpSettings* settings) { size_t header; WINPR_UNUSED(settings); if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; Stream_Write_UINT16(s, 6); /* colorTableCacheSize (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2Octets (2 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_COLOR_CACHE); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_color_cache_capability_set(wStream* s, UINT16 length) { UINT16 colorTableCacheSize; UINT16 pad2Octets; WLog_INFO(TAG, "ColorCacheCapabilitySet (length %" PRIu16 "):", length); if (length < 8) return FALSE; Stream_Read_UINT16(s, colorTableCacheSize); /* colorTableCacheSize (2 bytes) */ Stream_Read_UINT16(s, pad2Octets); /* pad2Octets (2 bytes) */ WLog_INFO(TAG, "\tcolorTableCacheSize: 0x%04" PRIX16 "", colorTableCacheSize); WLog_INFO(TAG, "\tpad2Octets: 0x%04" PRIX16 "", pad2Octets); return TRUE; } #endif /** * Read sound capability set.\n * @msdn{cc240552} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_sound_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { UINT16 soundFlags; if (length < 8) return FALSE; Stream_Read_UINT16(s, soundFlags); /* soundFlags (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ settings->SoundBeepsEnabled = (soundFlags & SOUND_BEEPS_FLAG) ? TRUE : FALSE; return TRUE; } /** * Write sound capability set.\n * @msdn{cc240552} * @param s stream * @param settings settings */ static BOOL rdp_write_sound_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT16 soundFlags; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; soundFlags = (settings->SoundBeepsEnabled) ? SOUND_BEEPS_FLAG : 0; Stream_Write_UINT16(s, soundFlags); /* soundFlags (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2OctetsA (2 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_SOUND); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_sound_capability_set(wStream* s, UINT16 length) { UINT16 soundFlags; UINT16 pad2OctetsA; WLog_INFO(TAG, "SoundCapabilitySet (length %" PRIu16 "):", length); if (length < 8) return FALSE; Stream_Read_UINT16(s, soundFlags); /* soundFlags (2 bytes) */ Stream_Read_UINT16(s, pad2OctetsA); /* pad2OctetsA (2 bytes) */ WLog_INFO(TAG, "\tsoundFlags: 0x%04" PRIX16 "", soundFlags); WLog_INFO(TAG, "\tpad2OctetsA: 0x%04" PRIX16 "", pad2OctetsA); return TRUE; } #endif /** * Read input capability set.\n * @msdn{cc240563} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_input_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { UINT16 inputFlags; if (length < 88) return FALSE; Stream_Read_UINT16(s, inputFlags); /* inputFlags (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ if (settings->ServerMode) { Stream_Read_UINT32(s, settings->KeyboardLayout); /* keyboardLayout (4 bytes) */ Stream_Read_UINT32(s, settings->KeyboardType); /* keyboardType (4 bytes) */ Stream_Read_UINT32(s, settings->KeyboardSubType); /* keyboardSubType (4 bytes) */ Stream_Read_UINT32(s, settings->KeyboardFunctionKey); /* keyboardFunctionKeys (4 bytes) */ } else { Stream_Seek_UINT32(s); /* keyboardLayout (4 bytes) */ Stream_Seek_UINT32(s); /* keyboardType (4 bytes) */ Stream_Seek_UINT32(s); /* keyboardSubType (4 bytes) */ Stream_Seek_UINT32(s); /* keyboardFunctionKeys (4 bytes) */ } Stream_Seek(s, 64); /* imeFileName (64 bytes) */ if (!settings->ServerMode) { if (inputFlags & INPUT_FLAG_FASTPATH_INPUT) { /* advertised by RDP 5.0 and 5.1 servers */ } else if (inputFlags & INPUT_FLAG_FASTPATH_INPUT2) { /* advertised by RDP 5.2, 6.0, 6.1 and 7.0 servers */ } else { /* server does not support fastpath input */ settings->FastPathInput = FALSE; } if (inputFlags & TS_INPUT_FLAG_MOUSE_HWHEEL) settings->HasHorizontalWheel = TRUE; if (inputFlags & INPUT_FLAG_UNICODE) settings->UnicodeInput = TRUE; if (inputFlags & INPUT_FLAG_MOUSEX) settings->HasExtendedMouseEvent = TRUE; } return TRUE; } /** * Write input capability set.\n * @msdn{cc240563} * @param s stream * @param settings settings */ static BOOL rdp_write_input_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT16 inputFlags; if (!Stream_EnsureRemainingCapacity(s, 128)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; inputFlags = INPUT_FLAG_SCANCODES; if (settings->FastPathInput) { inputFlags |= INPUT_FLAG_FASTPATH_INPUT; inputFlags |= INPUT_FLAG_FASTPATH_INPUT2; } if (settings->HasHorizontalWheel) inputFlags |= TS_INPUT_FLAG_MOUSE_HWHEEL; if (settings->UnicodeInput) inputFlags |= INPUT_FLAG_UNICODE; if (settings->HasExtendedMouseEvent) inputFlags |= INPUT_FLAG_MOUSEX; Stream_Write_UINT16(s, inputFlags); /* inputFlags (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2OctetsA (2 bytes) */ Stream_Write_UINT32(s, settings->KeyboardLayout); /* keyboardLayout (4 bytes) */ Stream_Write_UINT32(s, settings->KeyboardType); /* keyboardType (4 bytes) */ Stream_Write_UINT32(s, settings->KeyboardSubType); /* keyboardSubType (4 bytes) */ Stream_Write_UINT32(s, settings->KeyboardFunctionKey); /* keyboardFunctionKeys (4 bytes) */ Stream_Zero(s, 64); /* imeFileName (64 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_INPUT); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_input_capability_set(wStream* s, UINT16 length) { UINT16 inputFlags; UINT16 pad2OctetsA; UINT32 keyboardLayout; UINT32 keyboardType; UINT32 keyboardSubType; UINT32 keyboardFunctionKey; WLog_INFO(TAG, "InputCapabilitySet (length %" PRIu16 ")", length); if (length < 88) return FALSE; Stream_Read_UINT16(s, inputFlags); /* inputFlags (2 bytes) */ Stream_Read_UINT16(s, pad2OctetsA); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT32(s, keyboardLayout); /* keyboardLayout (4 bytes) */ Stream_Read_UINT32(s, keyboardType); /* keyboardType (4 bytes) */ Stream_Read_UINT32(s, keyboardSubType); /* keyboardSubType (4 bytes) */ Stream_Read_UINT32(s, keyboardFunctionKey); /* keyboardFunctionKeys (4 bytes) */ Stream_Seek(s, 64); /* imeFileName (64 bytes) */ WLog_INFO(TAG, "\tinputFlags: 0x%04" PRIX16 "", inputFlags); WLog_INFO(TAG, "\tpad2OctetsA: 0x%04" PRIX16 "", pad2OctetsA); WLog_INFO(TAG, "\tkeyboardLayout: 0x%08" PRIX32 "", keyboardLayout); WLog_INFO(TAG, "\tkeyboardType: 0x%08" PRIX32 "", keyboardType); WLog_INFO(TAG, "\tkeyboardSubType: 0x%08" PRIX32 "", keyboardSubType); WLog_INFO(TAG, "\tkeyboardFunctionKey: 0x%08" PRIX32 "", keyboardFunctionKey); return TRUE; } #endif /** * Read font capability set.\n * @msdn{cc240571} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_font_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { WINPR_UNUSED(settings); if (length > 4) Stream_Seek_UINT16(s); /* fontSupportFlags (2 bytes) */ if (length > 6) Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ return TRUE; } /** * Write font capability set.\n * @msdn{cc240571} * @param s stream * @param settings settings */ static BOOL rdp_write_font_capability_set(wStream* s, const rdpSettings* settings) { size_t header; WINPR_UNUSED(settings); if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; Stream_Write_UINT16(s, FONTSUPPORT_FONTLIST); /* fontSupportFlags (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2Octets (2 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_FONT); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_font_capability_set(wStream* s, UINT16 length) { UINT16 fontSupportFlags = 0; UINT16 pad2Octets = 0; WLog_INFO(TAG, "FontCapabilitySet (length %" PRIu16 "):", length); if (length > 4) Stream_Read_UINT16(s, fontSupportFlags); /* fontSupportFlags (2 bytes) */ if (length > 6) Stream_Read_UINT16(s, pad2Octets); /* pad2Octets (2 bytes) */ WLog_INFO(TAG, "\tfontSupportFlags: 0x%04" PRIX16 "", fontSupportFlags); WLog_INFO(TAG, "\tpad2Octets: 0x%04" PRIX16 "", pad2Octets); return TRUE; } #endif /** * Read brush capability set. * @msdn{cc240564} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_brush_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { WINPR_UNUSED(settings); if (length < 8) return FALSE; Stream_Seek_UINT32(s); /* brushSupportLevel (4 bytes) */ return TRUE; } /** * Write brush capability set.\n * @msdn{cc240564} * @param s stream * @param settings settings */ static BOOL rdp_write_brush_capability_set(wStream* s, const rdpSettings* settings) { size_t header; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; Stream_Write_UINT32(s, settings->BrushSupportLevel); /* brushSupportLevel (4 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_BRUSH); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_brush_capability_set(wStream* s, UINT16 length) { UINT32 brushSupportLevel; WLog_INFO(TAG, "BrushCapabilitySet (length %" PRIu16 "):", length); if (length < 8) return FALSE; Stream_Read_UINT32(s, brushSupportLevel); /* brushSupportLevel (4 bytes) */ WLog_INFO(TAG, "\tbrushSupportLevel: 0x%08" PRIX32 "", brushSupportLevel); return TRUE; } #endif /** * Read cache definition (glyph).\n * @msdn{cc240566} * @param s stream */ static void rdp_read_cache_definition(wStream* s, GLYPH_CACHE_DEFINITION* cache_definition) { Stream_Read_UINT16(s, cache_definition->cacheEntries); /* cacheEntries (2 bytes) */ Stream_Read_UINT16(s, cache_definition->cacheMaximumCellSize); /* cacheMaximumCellSize (2 bytes) */ } /** * Write cache definition (glyph).\n * @msdn{cc240566} * @param s stream */ static void rdp_write_cache_definition(wStream* s, GLYPH_CACHE_DEFINITION* cache_definition) { Stream_Write_UINT16(s, cache_definition->cacheEntries); /* cacheEntries (2 bytes) */ Stream_Write_UINT16( s, cache_definition->cacheMaximumCellSize); /* cacheMaximumCellSize (2 bytes) */ } /** * Read glyph cache capability set.\n * @msdn{cc240565} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_glyph_cache_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { if (length < 52) return FALSE; /* glyphCache (40 bytes) */ rdp_read_cache_definition(s, &(settings->GlyphCache[0])); /* glyphCache0 (4 bytes) */ rdp_read_cache_definition(s, &(settings->GlyphCache[1])); /* glyphCache1 (4 bytes) */ rdp_read_cache_definition(s, &(settings->GlyphCache[2])); /* glyphCache2 (4 bytes) */ rdp_read_cache_definition(s, &(settings->GlyphCache[3])); /* glyphCache3 (4 bytes) */ rdp_read_cache_definition(s, &(settings->GlyphCache[4])); /* glyphCache4 (4 bytes) */ rdp_read_cache_definition(s, &(settings->GlyphCache[5])); /* glyphCache5 (4 bytes) */ rdp_read_cache_definition(s, &(settings->GlyphCache[6])); /* glyphCache6 (4 bytes) */ rdp_read_cache_definition(s, &(settings->GlyphCache[7])); /* glyphCache7 (4 bytes) */ rdp_read_cache_definition(s, &(settings->GlyphCache[8])); /* glyphCache8 (4 bytes) */ rdp_read_cache_definition(s, &(settings->GlyphCache[9])); /* glyphCache9 (4 bytes) */ rdp_read_cache_definition(s, settings->FragCache); /* fragCache (4 bytes) */ Stream_Read_UINT16(s, settings->GlyphSupportLevel); /* glyphSupportLevel (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ return TRUE; } /** * Write glyph cache capability set.\n * @msdn{cc240565} * @param s stream * @param settings settings */ static BOOL rdp_write_glyph_cache_capability_set(wStream* s, const rdpSettings* settings) { size_t header; if (!Stream_EnsureRemainingCapacity(s, 64)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; if (settings->GlyphSupportLevel > UINT16_MAX) return FALSE; /* glyphCache (40 bytes) */ rdp_write_cache_definition(s, &(settings->GlyphCache[0])); /* glyphCache0 (4 bytes) */ rdp_write_cache_definition(s, &(settings->GlyphCache[1])); /* glyphCache1 (4 bytes) */ rdp_write_cache_definition(s, &(settings->GlyphCache[2])); /* glyphCache2 (4 bytes) */ rdp_write_cache_definition(s, &(settings->GlyphCache[3])); /* glyphCache3 (4 bytes) */ rdp_write_cache_definition(s, &(settings->GlyphCache[4])); /* glyphCache4 (4 bytes) */ rdp_write_cache_definition(s, &(settings->GlyphCache[5])); /* glyphCache5 (4 bytes) */ rdp_write_cache_definition(s, &(settings->GlyphCache[6])); /* glyphCache6 (4 bytes) */ rdp_write_cache_definition(s, &(settings->GlyphCache[7])); /* glyphCache7 (4 bytes) */ rdp_write_cache_definition(s, &(settings->GlyphCache[8])); /* glyphCache8 (4 bytes) */ rdp_write_cache_definition(s, &(settings->GlyphCache[9])); /* glyphCache9 (4 bytes) */ rdp_write_cache_definition(s, settings->FragCache); /* fragCache (4 bytes) */ Stream_Write_UINT16(s, (UINT16)settings->GlyphSupportLevel); /* glyphSupportLevel (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2Octets (2 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_GLYPH_CACHE); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_glyph_cache_capability_set(wStream* s, UINT16 length) { GLYPH_CACHE_DEFINITION glyphCache[10]; GLYPH_CACHE_DEFINITION fragCache; UINT16 glyphSupportLevel; UINT16 pad2Octets; WLog_INFO(TAG, "GlyphCacheCapabilitySet (length %" PRIu16 "):", length); if (length < 52) return FALSE; /* glyphCache (40 bytes) */ rdp_read_cache_definition(s, &glyphCache[0]); /* glyphCache0 (4 bytes) */ rdp_read_cache_definition(s, &glyphCache[1]); /* glyphCache1 (4 bytes) */ rdp_read_cache_definition(s, &glyphCache[2]); /* glyphCache2 (4 bytes) */ rdp_read_cache_definition(s, &glyphCache[3]); /* glyphCache3 (4 bytes) */ rdp_read_cache_definition(s, &glyphCache[4]); /* glyphCache4 (4 bytes) */ rdp_read_cache_definition(s, &glyphCache[5]); /* glyphCache5 (4 bytes) */ rdp_read_cache_definition(s, &glyphCache[6]); /* glyphCache6 (4 bytes) */ rdp_read_cache_definition(s, &glyphCache[7]); /* glyphCache7 (4 bytes) */ rdp_read_cache_definition(s, &glyphCache[8]); /* glyphCache8 (4 bytes) */ rdp_read_cache_definition(s, &glyphCache[9]); /* glyphCache9 (4 bytes) */ rdp_read_cache_definition(s, &fragCache); /* fragCache (4 bytes) */ Stream_Read_UINT16(s, glyphSupportLevel); /* glyphSupportLevel (2 bytes) */ Stream_Read_UINT16(s, pad2Octets); /* pad2Octets (2 bytes) */ WLog_INFO(TAG, "\tglyphCache0: Entries: %" PRIu16 " MaximumCellSize: %" PRIu16 "", glyphCache[0].cacheEntries, glyphCache[0].cacheMaximumCellSize); WLog_INFO(TAG, "\tglyphCache1: Entries: %" PRIu16 " MaximumCellSize: %" PRIu16 "", glyphCache[1].cacheEntries, glyphCache[1].cacheMaximumCellSize); WLog_INFO(TAG, "\tglyphCache2: Entries: %" PRIu16 " MaximumCellSize: %" PRIu16 "", glyphCache[2].cacheEntries, glyphCache[2].cacheMaximumCellSize); WLog_INFO(TAG, "\tglyphCache3: Entries: %" PRIu16 " MaximumCellSize: %" PRIu16 "", glyphCache[3].cacheEntries, glyphCache[3].cacheMaximumCellSize); WLog_INFO(TAG, "\tglyphCache4: Entries: %" PRIu16 " MaximumCellSize: %" PRIu16 "", glyphCache[4].cacheEntries, glyphCache[4].cacheMaximumCellSize); WLog_INFO(TAG, "\tglyphCache5: Entries: %" PRIu16 " MaximumCellSize: %" PRIu16 "", glyphCache[5].cacheEntries, glyphCache[5].cacheMaximumCellSize); WLog_INFO(TAG, "\tglyphCache6: Entries: %" PRIu16 " MaximumCellSize: %" PRIu16 "", glyphCache[6].cacheEntries, glyphCache[6].cacheMaximumCellSize); WLog_INFO(TAG, "\tglyphCache7: Entries: %" PRIu16 " MaximumCellSize: %" PRIu16 "", glyphCache[7].cacheEntries, glyphCache[7].cacheMaximumCellSize); WLog_INFO(TAG, "\tglyphCache8: Entries: %" PRIu16 " MaximumCellSize: %" PRIu16 "", glyphCache[8].cacheEntries, glyphCache[8].cacheMaximumCellSize); WLog_INFO(TAG, "\tglyphCache9: Entries: %" PRIu16 " MaximumCellSize: %" PRIu16 "", glyphCache[9].cacheEntries, glyphCache[9].cacheMaximumCellSize); WLog_INFO(TAG, "\tfragCache: Entries: %" PRIu16 " MaximumCellSize: %" PRIu16 "", fragCache.cacheEntries, fragCache.cacheMaximumCellSize); WLog_INFO(TAG, "\tglyphSupportLevel: 0x%04" PRIX16 "", glyphSupportLevel); WLog_INFO(TAG, "\tpad2Octets: 0x%04" PRIX16 "", pad2Octets); return TRUE; } #endif /** * Read offscreen bitmap cache capability set.\n * @msdn{cc240550} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_offscreen_bitmap_cache_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { UINT32 offscreenSupportLevel; if (length < 12) return FALSE; Stream_Read_UINT32(s, offscreenSupportLevel); /* offscreenSupportLevel (4 bytes) */ Stream_Read_UINT16(s, settings->OffscreenCacheSize); /* offscreenCacheSize (2 bytes) */ Stream_Read_UINT16(s, settings->OffscreenCacheEntries); /* offscreenCacheEntries (2 bytes) */ if (offscreenSupportLevel & TRUE) settings->OffscreenSupportLevel = TRUE; return TRUE; } /** * Write offscreen bitmap cache capability set.\n * @msdn{cc240550} * @param s stream * @param settings settings */ static BOOL rdp_write_offscreen_bitmap_cache_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT32 offscreenSupportLevel = 0x00; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; if (settings->OffscreenSupportLevel) { offscreenSupportLevel = 0x01; Stream_Write_UINT32(s, offscreenSupportLevel); /* offscreenSupportLevel (4 bytes) */ Stream_Write_UINT16(s, settings->OffscreenCacheSize); /* offscreenCacheSize (2 bytes) */ Stream_Write_UINT16(s, settings->OffscreenCacheEntries); /* offscreenCacheEntries (2 bytes) */ } else Stream_Zero(s, 8); rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_OFFSCREEN_CACHE); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_offscreen_bitmap_cache_capability_set(wStream* s, UINT16 length) { UINT32 offscreenSupportLevel; UINT16 offscreenCacheSize; UINT16 offscreenCacheEntries; WLog_INFO(TAG, "OffscreenBitmapCacheCapabilitySet (length %" PRIu16 "):", length); if (length < 12) return FALSE; Stream_Read_UINT32(s, offscreenSupportLevel); /* offscreenSupportLevel (4 bytes) */ Stream_Read_UINT16(s, offscreenCacheSize); /* offscreenCacheSize (2 bytes) */ Stream_Read_UINT16(s, offscreenCacheEntries); /* offscreenCacheEntries (2 bytes) */ WLog_INFO(TAG, "\toffscreenSupportLevel: 0x%08" PRIX32 "", offscreenSupportLevel); WLog_INFO(TAG, "\toffscreenCacheSize: 0x%04" PRIX16 "", offscreenCacheSize); WLog_INFO(TAG, "\toffscreenCacheEntries: 0x%04" PRIX16 "", offscreenCacheEntries); return TRUE; } #endif /** * Read bitmap cache host support capability set.\n * @msdn{cc240557} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_bitmap_cache_host_support_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { BYTE cacheVersion; if (length < 8) return FALSE; Stream_Read_UINT8(s, cacheVersion); /* cacheVersion (1 byte) */ Stream_Seek_UINT8(s); /* pad1 (1 byte) */ Stream_Seek_UINT16(s); /* pad2 (2 bytes) */ if (cacheVersion & BITMAP_CACHE_V2) settings->BitmapCachePersistEnabled = TRUE; return TRUE; } /** * Write bitmap cache host support capability set.\n * @msdn{cc240557} * @param s stream * @param settings settings */ static BOOL rdp_write_bitmap_cache_host_support_capability_set(wStream* s, const rdpSettings* settings) { size_t header; WINPR_UNUSED(settings); if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; Stream_Write_UINT8(s, BITMAP_CACHE_V2); /* cacheVersion (1 byte) */ Stream_Write_UINT8(s, 0); /* pad1 (1 byte) */ Stream_Write_UINT16(s, 0); /* pad2 (2 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_BITMAP_CACHE_HOST_SUPPORT); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_bitmap_cache_host_support_capability_set(wStream* s, UINT16 length) { BYTE cacheVersion; BYTE pad1; UINT16 pad2; WLog_INFO(TAG, "BitmapCacheHostSupportCapabilitySet (length %" PRIu16 "):", length); if (length < 8) return FALSE; Stream_Read_UINT8(s, cacheVersion); /* cacheVersion (1 byte) */ Stream_Read_UINT8(s, pad1); /* pad1 (1 byte) */ Stream_Read_UINT16(s, pad2); /* pad2 (2 bytes) */ WLog_INFO(TAG, "\tcacheVersion: 0x%02" PRIX8 "", cacheVersion); WLog_INFO(TAG, "\tpad1: 0x%02" PRIX8 "", pad1); WLog_INFO(TAG, "\tpad2: 0x%04" PRIX16 "", pad2); return TRUE; } static void rdp_read_bitmap_cache_cell_info(wStream* s, BITMAP_CACHE_V2_CELL_INFO* cellInfo) { UINT32 info; /** * numEntries is in the first 31 bits, while the last bit (k) * is used to indicate a persistent bitmap cache. */ Stream_Read_UINT32(s, info); cellInfo->numEntries = (info & 0x7FFFFFFF); cellInfo->persistent = (info & 0x80000000) ? 1 : 0; } #endif static void rdp_write_bitmap_cache_cell_info(wStream* s, BITMAP_CACHE_V2_CELL_INFO* cellInfo) { UINT32 info; /** * numEntries is in the first 31 bits, while the last bit (k) * is used to indicate a persistent bitmap cache. */ info = (cellInfo->numEntries | (cellInfo->persistent << 31)); Stream_Write_UINT32(s, info); } /** * Read bitmap cache v2 capability set.\n * @msdn{cc240560} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_bitmap_cache_v2_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { WINPR_UNUSED(settings); if (length < 40) return FALSE; Stream_Seek_UINT16(s); /* cacheFlags (2 bytes) */ Stream_Seek_UINT8(s); /* pad2 (1 byte) */ Stream_Seek_UINT8(s); /* numCellCaches (1 byte) */ Stream_Seek(s, 4); /* bitmapCache0CellInfo (4 bytes) */ Stream_Seek(s, 4); /* bitmapCache1CellInfo (4 bytes) */ Stream_Seek(s, 4); /* bitmapCache2CellInfo (4 bytes) */ Stream_Seek(s, 4); /* bitmapCache3CellInfo (4 bytes) */ Stream_Seek(s, 4); /* bitmapCache4CellInfo (4 bytes) */ Stream_Seek(s, 12); /* pad3 (12 bytes) */ return TRUE; } /** * Write bitmap cache v2 capability set.\n * @msdn{cc240560} * @param s stream * @param settings settings */ static BOOL rdp_write_bitmap_cache_v2_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT16 cacheFlags; if (!Stream_EnsureRemainingCapacity(s, 64)) return FALSE; header = rdp_capability_set_start(s); cacheFlags = ALLOW_CACHE_WAITING_LIST_FLAG; if (settings->BitmapCachePersistEnabled) cacheFlags |= PERSISTENT_KEYS_EXPECTED_FLAG; Stream_Write_UINT16(s, cacheFlags); /* cacheFlags (2 bytes) */ Stream_Write_UINT8(s, 0); /* pad2 (1 byte) */ Stream_Write_UINT8(s, settings->BitmapCacheV2NumCells); /* numCellCaches (1 byte) */ rdp_write_bitmap_cache_cell_info( s, &settings->BitmapCacheV2CellInfo[0]); /* bitmapCache0CellInfo (4 bytes) */ rdp_write_bitmap_cache_cell_info( s, &settings->BitmapCacheV2CellInfo[1]); /* bitmapCache1CellInfo (4 bytes) */ rdp_write_bitmap_cache_cell_info( s, &settings->BitmapCacheV2CellInfo[2]); /* bitmapCache2CellInfo (4 bytes) */ rdp_write_bitmap_cache_cell_info( s, &settings->BitmapCacheV2CellInfo[3]); /* bitmapCache3CellInfo (4 bytes) */ rdp_write_bitmap_cache_cell_info( s, &settings->BitmapCacheV2CellInfo[4]); /* bitmapCache4CellInfo (4 bytes) */ Stream_Zero(s, 12); /* pad3 (12 bytes) */ rdp_capability_set_finish(s, header, CAPSET_TYPE_BITMAP_CACHE_V2); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_bitmap_cache_v2_capability_set(wStream* s, UINT16 length) { UINT16 cacheFlags; BYTE pad2; BYTE numCellCaches; BITMAP_CACHE_V2_CELL_INFO bitmapCacheV2CellInfo[5]; WLog_INFO(TAG, "BitmapCacheV2CapabilitySet (length %" PRIu16 "):", length); if (length < 40) return FALSE; Stream_Read_UINT16(s, cacheFlags); /* cacheFlags (2 bytes) */ Stream_Read_UINT8(s, pad2); /* pad2 (1 byte) */ Stream_Read_UINT8(s, numCellCaches); /* numCellCaches (1 byte) */ rdp_read_bitmap_cache_cell_info(s, &bitmapCacheV2CellInfo[0]); /* bitmapCache0CellInfo (4 bytes) */ rdp_read_bitmap_cache_cell_info(s, &bitmapCacheV2CellInfo[1]); /* bitmapCache1CellInfo (4 bytes) */ rdp_read_bitmap_cache_cell_info(s, &bitmapCacheV2CellInfo[2]); /* bitmapCache2CellInfo (4 bytes) */ rdp_read_bitmap_cache_cell_info(s, &bitmapCacheV2CellInfo[3]); /* bitmapCache3CellInfo (4 bytes) */ rdp_read_bitmap_cache_cell_info(s, &bitmapCacheV2CellInfo[4]); /* bitmapCache4CellInfo (4 bytes) */ Stream_Seek(s, 12); /* pad3 (12 bytes) */ WLog_INFO(TAG, "\tcacheFlags: 0x%04" PRIX16 "", cacheFlags); WLog_INFO(TAG, "\tpad2: 0x%02" PRIX8 "", pad2); WLog_INFO(TAG, "\tnumCellCaches: 0x%02" PRIX8 "", numCellCaches); WLog_INFO(TAG, "\tbitmapCache0CellInfo: numEntries: %" PRIu32 " persistent: %" PRId32 "", bitmapCacheV2CellInfo[0].numEntries, bitmapCacheV2CellInfo[0].persistent); WLog_INFO(TAG, "\tbitmapCache1CellInfo: numEntries: %" PRIu32 " persistent: %" PRId32 "", bitmapCacheV2CellInfo[1].numEntries, bitmapCacheV2CellInfo[1].persistent); WLog_INFO(TAG, "\tbitmapCache2CellInfo: numEntries: %" PRIu32 " persistent: %" PRId32 "", bitmapCacheV2CellInfo[2].numEntries, bitmapCacheV2CellInfo[2].persistent); WLog_INFO(TAG, "\tbitmapCache3CellInfo: numEntries: %" PRIu32 " persistent: %" PRId32 "", bitmapCacheV2CellInfo[3].numEntries, bitmapCacheV2CellInfo[3].persistent); WLog_INFO(TAG, "\tbitmapCache4CellInfo: numEntries: %" PRIu32 " persistent: %" PRId32 "", bitmapCacheV2CellInfo[4].numEntries, bitmapCacheV2CellInfo[4].persistent); return TRUE; } #endif /** * Read virtual channel capability set.\n * @msdn{cc240551} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_virtual_channel_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { UINT32 flags; UINT32 VCChunkSize; if (length < 8) return FALSE; Stream_Read_UINT32(s, flags); /* flags (4 bytes) */ if (length > 8) Stream_Read_UINT32(s, VCChunkSize); /* VCChunkSize (4 bytes) */ else VCChunkSize = 1600; if (settings->ServerMode != TRUE) settings->VirtualChannelChunkSize = VCChunkSize; return TRUE; } /** * Write virtual channel capability set.\n * @msdn{cc240551} * @param s stream * @param settings settings */ static BOOL rdp_write_virtual_channel_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT32 flags; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); flags = VCCAPS_NO_COMPR; Stream_Write_UINT32(s, flags); /* flags (4 bytes) */ Stream_Write_UINT32(s, settings->VirtualChannelChunkSize); /* VCChunkSize (4 bytes) */ rdp_capability_set_finish(s, header, CAPSET_TYPE_VIRTUAL_CHANNEL); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_virtual_channel_capability_set(wStream* s, UINT16 length) { UINT32 flags; UINT32 VCChunkSize; WLog_INFO(TAG, "VirtualChannelCapabilitySet (length %" PRIu16 "):", length); if (length < 8) return FALSE; Stream_Read_UINT32(s, flags); /* flags (4 bytes) */ if (length > 8) Stream_Read_UINT32(s, VCChunkSize); /* VCChunkSize (4 bytes) */ else VCChunkSize = 1600; WLog_INFO(TAG, "\tflags: 0x%08" PRIX32 "", flags); WLog_INFO(TAG, "\tVCChunkSize: 0x%08" PRIX32 "", VCChunkSize); return TRUE; } #endif /** * Read drawn nine grid cache capability set.\n * @msdn{cc241565} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_draw_nine_grid_cache_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { UINT32 drawNineGridSupportLevel; if (length < 12) return FALSE; Stream_Read_UINT32(s, drawNineGridSupportLevel); /* drawNineGridSupportLevel (4 bytes) */ Stream_Read_UINT16(s, settings->DrawNineGridCacheSize); /* drawNineGridCacheSize (2 bytes) */ Stream_Read_UINT16(s, settings->DrawNineGridCacheEntries); /* drawNineGridCacheEntries (2 bytes) */ if ((drawNineGridSupportLevel & DRAW_NINEGRID_SUPPORTED) || (drawNineGridSupportLevel & DRAW_NINEGRID_SUPPORTED_V2)) settings->DrawNineGridEnabled = TRUE; return TRUE; } /** * Write drawn nine grid cache capability set.\n * @msdn{cc241565} * @param s stream * @param settings settings */ static BOOL rdp_write_draw_nine_grid_cache_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT32 drawNineGridSupportLevel; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); drawNineGridSupportLevel = (settings->DrawNineGridEnabled) ? DRAW_NINEGRID_SUPPORTED_V2 : DRAW_NINEGRID_NO_SUPPORT; Stream_Write_UINT32(s, drawNineGridSupportLevel); /* drawNineGridSupportLevel (4 bytes) */ Stream_Write_UINT16(s, settings->DrawNineGridCacheSize); /* drawNineGridCacheSize (2 bytes) */ Stream_Write_UINT16( s, settings->DrawNineGridCacheEntries); /* drawNineGridCacheEntries (2 bytes) */ rdp_capability_set_finish(s, header, CAPSET_TYPE_DRAW_NINE_GRID_CACHE); return TRUE; } static void rdp_write_gdiplus_cache_entries(wStream* s, UINT16 gce, UINT16 bce, UINT16 pce, UINT16 ice, UINT16 ace) { Stream_Write_UINT16(s, gce); /* gdipGraphicsCacheEntries (2 bytes) */ Stream_Write_UINT16(s, bce); /* gdipBrushCacheEntries (2 bytes) */ Stream_Write_UINT16(s, pce); /* gdipPenCacheEntries (2 bytes) */ Stream_Write_UINT16(s, ice); /* gdipImageCacheEntries (2 bytes) */ Stream_Write_UINT16(s, ace); /* gdipImageAttributesCacheEntries (2 bytes) */ } static void rdp_write_gdiplus_cache_chunk_size(wStream* s, UINT16 gccs, UINT16 obccs, UINT16 opccs, UINT16 oiaccs) { Stream_Write_UINT16(s, gccs); /* gdipGraphicsCacheChunkSize (2 bytes) */ Stream_Write_UINT16(s, obccs); /* gdipObjectBrushCacheChunkSize (2 bytes) */ Stream_Write_UINT16(s, opccs); /* gdipObjectPenCacheChunkSize (2 bytes) */ Stream_Write_UINT16(s, oiaccs); /* gdipObjectImageAttributesCacheChunkSize (2 bytes) */ } static void rdp_write_gdiplus_image_cache_properties(wStream* s, UINT16 oiccs, UINT16 oicts, UINT16 oicms) { Stream_Write_UINT16(s, oiccs); /* gdipObjectImageCacheChunkSize (2 bytes) */ Stream_Write_UINT16(s, oicts); /* gdipObjectImageCacheTotalSize (2 bytes) */ Stream_Write_UINT16(s, oicms); /* gdipObjectImageCacheMaxSize (2 bytes) */ } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_draw_nine_grid_cache_capability_set(wStream* s, UINT16 length) { UINT32 drawNineGridSupportLevel; UINT16 DrawNineGridCacheSize; UINT16 DrawNineGridCacheEntries; WLog_INFO(TAG, "DrawNineGridCacheCapabilitySet (length %" PRIu16 "):", length); if (length < 12) return FALSE; Stream_Read_UINT32(s, drawNineGridSupportLevel); /* drawNineGridSupportLevel (4 bytes) */ Stream_Read_UINT16(s, DrawNineGridCacheSize); /* drawNineGridCacheSize (2 bytes) */ Stream_Read_UINT16(s, DrawNineGridCacheEntries); /* drawNineGridCacheEntries (2 bytes) */ return TRUE; } #endif /** * Read GDI+ cache capability set.\n * @msdn{cc241566} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_draw_gdiplus_cache_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { UINT32 drawGDIPlusSupportLevel; UINT32 drawGdiplusCacheLevel; if (length < 40) return FALSE; Stream_Read_UINT32(s, drawGDIPlusSupportLevel); /* drawGDIPlusSupportLevel (4 bytes) */ Stream_Seek_UINT32(s); /* GdipVersion (4 bytes) */ Stream_Read_UINT32(s, drawGdiplusCacheLevel); /* drawGdiplusCacheLevel (4 bytes) */ Stream_Seek(s, 10); /* GdipCacheEntries (10 bytes) */ Stream_Seek(s, 8); /* GdipCacheChunkSize (8 bytes) */ Stream_Seek(s, 6); /* GdipImageCacheProperties (6 bytes) */ if (drawGDIPlusSupportLevel & DRAW_GDIPLUS_SUPPORTED) settings->DrawGdiPlusEnabled = TRUE; if (drawGdiplusCacheLevel & DRAW_GDIPLUS_CACHE_LEVEL_ONE) settings->DrawGdiPlusCacheEnabled = TRUE; return TRUE; } /** * Write GDI+ cache capability set.\n * @msdn{cc241566} * @param s stream * @param settings settings */ static BOOL rdp_write_draw_gdiplus_cache_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT32 drawGDIPlusSupportLevel; UINT32 drawGdiplusCacheLevel; if (!Stream_EnsureRemainingCapacity(s, 64)) return FALSE; header = rdp_capability_set_start(s); drawGDIPlusSupportLevel = (settings->DrawGdiPlusEnabled) ? DRAW_GDIPLUS_SUPPORTED : DRAW_GDIPLUS_DEFAULT; drawGdiplusCacheLevel = (settings->DrawGdiPlusEnabled) ? DRAW_GDIPLUS_CACHE_LEVEL_ONE : DRAW_GDIPLUS_CACHE_LEVEL_DEFAULT; Stream_Write_UINT32(s, drawGDIPlusSupportLevel); /* drawGDIPlusSupportLevel (4 bytes) */ Stream_Write_UINT32(s, 0); /* GdipVersion (4 bytes) */ Stream_Write_UINT32(s, drawGdiplusCacheLevel); /* drawGdiplusCacheLevel (4 bytes) */ rdp_write_gdiplus_cache_entries(s, 10, 5, 5, 10, 2); /* GdipCacheEntries (10 bytes) */ rdp_write_gdiplus_cache_chunk_size(s, 512, 2048, 1024, 64); /* GdipCacheChunkSize (8 bytes) */ rdp_write_gdiplus_image_cache_properties(s, 4096, 256, 128); /* GdipImageCacheProperties (6 bytes) */ rdp_capability_set_finish(s, header, CAPSET_TYPE_DRAW_GDI_PLUS); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_draw_gdiplus_cache_capability_set(wStream* s, UINT16 length) { UINT32 drawGdiPlusSupportLevel; UINT32 GdipVersion; UINT32 drawGdiplusCacheLevel; WLog_INFO(TAG, "DrawGdiPlusCacheCapabilitySet (length %" PRIu16 "):", length); if (length < 40) return FALSE; Stream_Read_UINT32(s, drawGdiPlusSupportLevel); /* drawGdiPlusSupportLevel (4 bytes) */ Stream_Read_UINT32(s, GdipVersion); /* GdipVersion (4 bytes) */ Stream_Read_UINT32(s, drawGdiplusCacheLevel); /* drawGdiPlusCacheLevel (4 bytes) */ Stream_Seek(s, 10); /* GdipCacheEntries (10 bytes) */ Stream_Seek(s, 8); /* GdipCacheChunkSize (8 bytes) */ Stream_Seek(s, 6); /* GdipImageCacheProperties (6 bytes) */ return TRUE; } #endif /** * Read remote programs capability set.\n * @msdn{cc242518} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_remote_programs_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { UINT32 railSupportLevel; if (length < 8) return FALSE; Stream_Read_UINT32(s, railSupportLevel); /* railSupportLevel (4 bytes) */ if ((railSupportLevel & RAIL_LEVEL_SUPPORTED) == 0) { if (settings->RemoteApplicationMode == TRUE) { /* RemoteApp Failure! */ settings->RemoteApplicationMode = FALSE; } } /* 2.2.2.2.3 HandshakeEx PDU (TS_RAIL_ORDER_HANDSHAKE_EX) * the handshake ex pdu is supported when both, client and server announce * it OR if we are ready to begin enhanced remoteAPP mode. */ if (settings->RemoteApplicationMode) railSupportLevel |= RAIL_LEVEL_HANDSHAKE_EX_SUPPORTED; settings->RemoteApplicationSupportLevel = railSupportLevel & settings->RemoteApplicationSupportMask; return TRUE; } /** * Write remote programs capability set.\n * @msdn{cc242518} * @param s stream * @param settings settings */ static BOOL rdp_write_remote_programs_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT32 railSupportLevel; if (!Stream_EnsureRemainingCapacity(s, 64)) return FALSE; header = rdp_capability_set_start(s); railSupportLevel = RAIL_LEVEL_SUPPORTED; if (settings->RemoteApplicationSupportLevel & RAIL_LEVEL_DOCKED_LANGBAR_SUPPORTED) { if (settings->RemoteAppLanguageBarSupported) railSupportLevel |= RAIL_LEVEL_DOCKED_LANGBAR_SUPPORTED; } railSupportLevel |= RAIL_LEVEL_SHELL_INTEGRATION_SUPPORTED; railSupportLevel |= RAIL_LEVEL_LANGUAGE_IME_SYNC_SUPPORTED; railSupportLevel |= RAIL_LEVEL_SERVER_TO_CLIENT_IME_SYNC_SUPPORTED; railSupportLevel |= RAIL_LEVEL_HIDE_MINIMIZED_APPS_SUPPORTED; railSupportLevel |= RAIL_LEVEL_WINDOW_CLOAKING_SUPPORTED; railSupportLevel |= RAIL_LEVEL_HANDSHAKE_EX_SUPPORTED; /* Mask out everything the server does not support. */ railSupportLevel &= settings->RemoteApplicationSupportLevel; Stream_Write_UINT32(s, railSupportLevel); /* railSupportLevel (4 bytes) */ rdp_capability_set_finish(s, header, CAPSET_TYPE_RAIL); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_remote_programs_capability_set(wStream* s, UINT16 length) { UINT32 railSupportLevel; WLog_INFO(TAG, "RemoteProgramsCapabilitySet (length %" PRIu16 "):", length); if (length < 8) return FALSE; Stream_Read_UINT32(s, railSupportLevel); /* railSupportLevel (4 bytes) */ WLog_INFO(TAG, "\trailSupportLevel: 0x%08" PRIX32 "", railSupportLevel); return TRUE; } #endif /** * Read window list capability set.\n * @msdn{cc242564} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_window_list_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { if (length < 11) return FALSE; Stream_Read_UINT32(s, settings->RemoteWndSupportLevel); /* wndSupportLevel (4 bytes) */ Stream_Read_UINT8(s, settings->RemoteAppNumIconCaches); /* numIconCaches (1 byte) */ Stream_Read_UINT16(s, settings->RemoteAppNumIconCacheEntries); /* numIconCacheEntries (2 bytes) */ return TRUE; } /** * Write window list capability set.\n * @msdn{cc242564} * @param s stream * @param settings settings */ static BOOL rdp_write_window_list_capability_set(wStream* s, const rdpSettings* settings) { size_t header; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); Stream_Write_UINT32(s, settings->RemoteWndSupportLevel); /* wndSupportLevel (4 bytes) */ Stream_Write_UINT8(s, settings->RemoteAppNumIconCaches); /* numIconCaches (1 byte) */ Stream_Write_UINT16(s, settings->RemoteAppNumIconCacheEntries); /* numIconCacheEntries (2 bytes) */ rdp_capability_set_finish(s, header, CAPSET_TYPE_WINDOW); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_window_list_capability_set(wStream* s, UINT16 length) { UINT32 wndSupportLevel; BYTE numIconCaches; UINT16 numIconCacheEntries; WLog_INFO(TAG, "WindowListCapabilitySet (length %" PRIu16 "):", length); if (length < 11) return FALSE; Stream_Read_UINT32(s, wndSupportLevel); /* wndSupportLevel (4 bytes) */ Stream_Read_UINT8(s, numIconCaches); /* numIconCaches (1 byte) */ Stream_Read_UINT16(s, numIconCacheEntries); /* numIconCacheEntries (2 bytes) */ WLog_INFO(TAG, "\twndSupportLevel: 0x%08" PRIX32 "", wndSupportLevel); WLog_INFO(TAG, "\tnumIconCaches: 0x%02" PRIX8 "", numIconCaches); WLog_INFO(TAG, "\tnumIconCacheEntries: 0x%04" PRIX16 "", numIconCacheEntries); return TRUE; } #endif /** * Read desktop composition capability set.\n * @msdn{cc240855} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_desktop_composition_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { if (length < 6) return FALSE; Stream_Seek_UINT16(s); /* compDeskSupportLevel (2 bytes) */ return TRUE; } /** * Write desktop composition capability set.\n * @msdn{cc240855} * @param s stream * @param settings settings */ static BOOL rdp_write_desktop_composition_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT16 compDeskSupportLevel; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); compDeskSupportLevel = (settings->AllowDesktopComposition) ? COMPDESK_SUPPORTED : COMPDESK_NOT_SUPPORTED; Stream_Write_UINT16(s, compDeskSupportLevel); /* compDeskSupportLevel (2 bytes) */ rdp_capability_set_finish(s, header, CAPSET_TYPE_COMP_DESK); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_desktop_composition_capability_set(wStream* s, UINT16 length) { UINT16 compDeskSupportLevel; WLog_INFO(TAG, "DesktopCompositionCapabilitySet (length %" PRIu16 "):", length); if (length < 6) return FALSE; Stream_Read_UINT16(s, compDeskSupportLevel); /* compDeskSupportLevel (2 bytes) */ WLog_INFO(TAG, "\tcompDeskSupportLevel: 0x%04" PRIX16 "", compDeskSupportLevel); return TRUE; } #endif /** * Read multifragment update capability set.\n * @msdn{cc240649} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_multifragment_update_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { UINT32 multifragMaxRequestSize; if (length < 8) return FALSE; Stream_Read_UINT32(s, multifragMaxRequestSize); /* MaxRequestSize (4 bytes) */ if (settings->ServerMode) { /* * Special case: The client announces multifragment update support but sets the maximum * request size to something smaller than maximum size for *one* fast-path PDU. In this case * behave like no multifragment updates were supported and make sure no fragmentation * happens by setting FASTPATH_FRAGMENT_SAFE_SIZE. * * This behaviour was observed with some windows ce rdp clients. */ if (multifragMaxRequestSize < FASTPATH_MAX_PACKET_SIZE) multifragMaxRequestSize = FASTPATH_FRAGMENT_SAFE_SIZE; if (settings->RemoteFxCodec) { /** * If we are using RemoteFX the client MUST use a value greater * than or equal to the value we've previously sent in the server to * client multi-fragment update capability set (MS-RDPRFX 1.5) */ if (multifragMaxRequestSize < settings->MultifragMaxRequestSize) { /** * If it happens to be smaller we honor the client's value but * have to disable RemoteFX */ settings->RemoteFxCodec = FALSE; settings->MultifragMaxRequestSize = multifragMaxRequestSize; } else { /* no need to increase server's max request size setting here */ } } else { settings->MultifragMaxRequestSize = multifragMaxRequestSize; } } else { /** * In client mode we keep up with the server's capabilites. * In RemoteFX mode we MUST do this but it might also be useful to * receive larger related bitmap updates. */ if (multifragMaxRequestSize > settings->MultifragMaxRequestSize) settings->MultifragMaxRequestSize = multifragMaxRequestSize; } return TRUE; } /** * Write multifragment update capability set.\n * @msdn{cc240649} * @param s stream * @param settings settings */ static BOOL rdp_write_multifragment_update_capability_set(wStream* s, rdpSettings* settings) { size_t header; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; if (settings->ServerMode && settings->MultifragMaxRequestSize == 0) { /** * In server mode we prefer to use the highest useful request size that * will allow us to pack a complete screen update into a single fast * path PDU using any of the supported codecs. * However, the client is completely free to accept our proposed * max request size or send a different value in the client-to-server * multi-fragment update capability set and we have to accept that, * unless we are using RemoteFX where the client MUST announce a value * greater than or equal to the value we're sending here. * See [MS-RDPRFX 1.5 capability #2] */ UINT32 tileNumX = (settings->DesktopWidth + 63) / 64; UINT32 tileNumY = (settings->DesktopHeight + 63) / 64; settings->MultifragMaxRequestSize = tileNumX * tileNumY * 16384; /* and add room for headers, regions, frame markers, etc. */ settings->MultifragMaxRequestSize += 16384; } header = rdp_capability_set_start(s); Stream_Write_UINT32(s, settings->MultifragMaxRequestSize); /* MaxRequestSize (4 bytes) */ rdp_capability_set_finish(s, header, CAPSET_TYPE_MULTI_FRAGMENT_UPDATE); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_multifragment_update_capability_set(wStream* s, UINT16 length) { UINT32 maxRequestSize; WLog_INFO(TAG, "MultifragmentUpdateCapabilitySet (length %" PRIu16 "):", length); if (length < 8) return FALSE; Stream_Read_UINT32(s, maxRequestSize); /* maxRequestSize (4 bytes) */ WLog_INFO(TAG, "\tmaxRequestSize: 0x%08" PRIX32 "", maxRequestSize); return TRUE; } #endif /** * Read large pointer capability set.\n * @msdn{cc240650} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_large_pointer_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { UINT16 largePointerSupportFlags; if (length < 6) return FALSE; Stream_Read_UINT16(s, largePointerSupportFlags); /* largePointerSupportFlags (2 bytes) */ settings->LargePointerFlag = largePointerSupportFlags & (LARGE_POINTER_FLAG_96x96 | LARGE_POINTER_FLAG_384x384); if ((largePointerSupportFlags & ~(LARGE_POINTER_FLAG_96x96 | LARGE_POINTER_FLAG_384x384)) != 0) { WLog_WARN( TAG, "TS_LARGE_POINTER_CAPABILITYSET with unsupported flags %04X (all flags %04X) received", largePointerSupportFlags & ~(LARGE_POINTER_FLAG_96x96 | LARGE_POINTER_FLAG_384x384), largePointerSupportFlags); } return TRUE; } /** * Write large pointer capability set.\n * @msdn{cc240650} * @param s stream * @param settings settings */ static BOOL rdp_write_large_pointer_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT16 largePointerSupportFlags; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); largePointerSupportFlags = settings->LargePointerFlag & (LARGE_POINTER_FLAG_96x96 | LARGE_POINTER_FLAG_384x384); Stream_Write_UINT16(s, largePointerSupportFlags); /* largePointerSupportFlags (2 bytes) */ rdp_capability_set_finish(s, header, CAPSET_TYPE_LARGE_POINTER); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_large_pointer_capability_set(wStream* s, UINT16 length) { UINT16 largePointerSupportFlags; WLog_INFO(TAG, "LargePointerCapabilitySet (length %" PRIu16 "):", length); if (length < 6) return FALSE; Stream_Read_UINT16(s, largePointerSupportFlags); /* largePointerSupportFlags (2 bytes) */ WLog_INFO(TAG, "\tlargePointerSupportFlags: 0x%04" PRIX16 "", largePointerSupportFlags); return TRUE; } #endif /** * Read surface commands capability set.\n * @msdn{dd871563} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_surface_commands_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { UINT32 cmdFlags; if (length < 12) return FALSE; Stream_Read_UINT32(s, cmdFlags); /* cmdFlags (4 bytes) */ Stream_Seek_UINT32(s); /* reserved (4 bytes) */ settings->SurfaceCommandsEnabled = TRUE; settings->SurfaceFrameMarkerEnabled = (cmdFlags & SURFCMDS_FRAME_MARKER) ? TRUE : FALSE; return TRUE; } /** * Write surface commands capability set.\n * @msdn{dd871563} * @param s stream * @param settings settings */ static BOOL rdp_write_surface_commands_capability_set(wStream* s, const rdpSettings* settings) { size_t header; UINT32 cmdFlags; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); cmdFlags = SURFCMDS_SET_SURFACE_BITS | SURFCMDS_STREAM_SURFACE_BITS; if (settings->SurfaceFrameMarkerEnabled) cmdFlags |= SURFCMDS_FRAME_MARKER; Stream_Write_UINT32(s, cmdFlags); /* cmdFlags (4 bytes) */ Stream_Write_UINT32(s, 0); /* reserved (4 bytes) */ rdp_capability_set_finish(s, header, CAPSET_TYPE_SURFACE_COMMANDS); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_surface_commands_capability_set(wStream* s, UINT16 length) { UINT32 cmdFlags; UINT32 reserved; WLog_INFO(TAG, "SurfaceCommandsCapabilitySet (length %" PRIu16 "):", length); if (length < 12) return FALSE; Stream_Read_UINT32(s, cmdFlags); /* cmdFlags (4 bytes) */ Stream_Read_UINT32(s, reserved); /* reserved (4 bytes) */ WLog_INFO(TAG, "\tcmdFlags: 0x%08" PRIX32 "", cmdFlags); WLog_INFO(TAG, "\treserved: 0x%08" PRIX32 "", reserved); return TRUE; } static void rdp_print_bitmap_codec_guid(const GUID* guid) { WLog_INFO(TAG, "%08" PRIX32 "%04" PRIX16 "%04" PRIX16 "%02" PRIX8 "%02" PRIX8 "%02" PRIX8 "%02" PRIX8 "%02" PRIX8 "%02" PRIX8 "%02" PRIX8 "%02" PRIX8 "", guid->Data1, guid->Data2, guid->Data3, guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3], guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]); } static char* rdp_get_bitmap_codec_guid_name(const GUID* guid) { RPC_STATUS rpc_status; if (UuidEqual(guid, &CODEC_GUID_REMOTEFX, &rpc_status)) return "CODEC_GUID_REMOTEFX"; else if (UuidEqual(guid, &CODEC_GUID_NSCODEC, &rpc_status)) return "CODEC_GUID_NSCODEC"; else if (UuidEqual(guid, &CODEC_GUID_IGNORE, &rpc_status)) return "CODEC_GUID_IGNORE"; else if (UuidEqual(guid, &CODEC_GUID_IMAGE_REMOTEFX, &rpc_status)) return "CODEC_GUID_IMAGE_REMOTEFX"; #if defined(WITH_JPEG) else if (UuidEqual(guid, &CODEC_GUID_JPEG, &rpc_status)) return "CODEC_GUID_JPEG"; #endif return "CODEC_GUID_UNKNOWN"; } #endif static void rdp_read_bitmap_codec_guid(wStream* s, GUID* guid) { BYTE g[16]; Stream_Read(s, g, 16); guid->Data1 = (g[3] << 24) | (g[2] << 16) | (g[1] << 8) | g[0]; guid->Data2 = (g[5] << 8) | g[4]; guid->Data3 = (g[7] << 8) | g[6]; guid->Data4[0] = g[8]; guid->Data4[1] = g[9]; guid->Data4[2] = g[10]; guid->Data4[3] = g[11]; guid->Data4[4] = g[12]; guid->Data4[5] = g[13]; guid->Data4[6] = g[14]; guid->Data4[7] = g[15]; } static void rdp_write_bitmap_codec_guid(wStream* s, const GUID* guid) { BYTE g[16]; g[0] = guid->Data1 & 0xFF; g[1] = (guid->Data1 >> 8) & 0xFF; g[2] = (guid->Data1 >> 16) & 0xFF; g[3] = (guid->Data1 >> 24) & 0xFF; g[4] = (guid->Data2) & 0xFF; g[5] = (guid->Data2 >> 8) & 0xFF; g[6] = (guid->Data3) & 0xFF; g[7] = (guid->Data3 >> 8) & 0xFF; g[8] = guid->Data4[0]; g[9] = guid->Data4[1]; g[10] = guid->Data4[2]; g[11] = guid->Data4[3]; g[12] = guid->Data4[4]; g[13] = guid->Data4[5]; g[14] = guid->Data4[6]; g[15] = guid->Data4[7]; Stream_Write(s, g, 16); } /** * Read bitmap codecs capability set.\n * @msdn{dd891377} * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_bitmap_codecs_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { BYTE codecId; GUID codecGuid; RPC_STATUS rpc_status; BYTE bitmapCodecCount; UINT16 codecPropertiesLength; UINT16 remainingLength; BOOL guidNSCodec = FALSE; BOOL guidRemoteFx = FALSE; BOOL guidRemoteFxImage = FALSE; if (length < 5) return FALSE; Stream_Read_UINT8(s, bitmapCodecCount); /* bitmapCodecCount (1 byte) */ remainingLength = length - 5; while (bitmapCodecCount > 0) { if (remainingLength < 19) return FALSE; rdp_read_bitmap_codec_guid(s, &codecGuid); /* codecGuid (16 bytes) */ Stream_Read_UINT8(s, codecId); /* codecId (1 byte) */ Stream_Read_UINT16(s, codecPropertiesLength); /* codecPropertiesLength (2 bytes) */ remainingLength -= 19; if (remainingLength < codecPropertiesLength) return FALSE; if (settings->ServerMode) { UINT32 beg; UINT32 end; beg = (UINT32)Stream_GetPosition(s); end = beg + codecPropertiesLength; if (UuidEqual(&codecGuid, &CODEC_GUID_REMOTEFX, &rpc_status)) { UINT32 rfxCapsLength; UINT32 rfxPropsLength; UINT32 captureFlags; guidRemoteFx = TRUE; settings->RemoteFxCodecId = codecId; Stream_Read_UINT32(s, rfxPropsLength); /* length (4 bytes) */ Stream_Read_UINT32(s, captureFlags); /* captureFlags (4 bytes) */ Stream_Read_UINT32(s, rfxCapsLength); /* capsLength (4 bytes) */ settings->RemoteFxCaptureFlags = captureFlags; settings->RemoteFxOnly = (captureFlags & CARDP_CAPS_CAPTURE_NON_CAC) ? TRUE : FALSE; if (rfxCapsLength) { UINT16 blockType; UINT32 blockLen; UINT16 numCapsets; BYTE rfxCodecId; UINT16 capsetType; UINT16 numIcaps; UINT16 icapLen; /* TS_RFX_CAPS */ Stream_Read_UINT16(s, blockType); /* blockType (2 bytes) */ Stream_Read_UINT32(s, blockLen); /* blockLen (4 bytes) */ Stream_Read_UINT16(s, numCapsets); /* numCapsets (2 bytes) */ if (blockType != 0xCBC0) return FALSE; if (blockLen != 8) return FALSE; if (numCapsets != 1) return FALSE; /* TS_RFX_CAPSET */ Stream_Read_UINT16(s, blockType); /* blockType (2 bytes) */ Stream_Read_UINT32(s, blockLen); /* blockLen (4 bytes) */ Stream_Read_UINT8(s, rfxCodecId); /* codecId (1 byte) */ Stream_Read_UINT16(s, capsetType); /* capsetType (2 bytes) */ Stream_Read_UINT16(s, numIcaps); /* numIcaps (2 bytes) */ Stream_Read_UINT16(s, icapLen); /* icapLen (2 bytes) */ if (blockType != 0xCBC1) return FALSE; if (rfxCodecId != 1) return FALSE; if (capsetType != 0xCFC0) return FALSE; while (numIcaps--) { UINT16 version; UINT16 tileSize; BYTE codecFlags; BYTE colConvBits; BYTE transformBits; BYTE entropyBits; /* TS_RFX_ICAP */ Stream_Read_UINT16(s, version); /* version (2 bytes) */ Stream_Read_UINT16(s, tileSize); /* tileSize (2 bytes) */ Stream_Read_UINT8(s, codecFlags); /* flags (1 byte) */ Stream_Read_UINT8(s, colConvBits); /* colConvBits (1 byte) */ Stream_Read_UINT8(s, transformBits); /* transformBits (1 byte) */ Stream_Read_UINT8(s, entropyBits); /* entropyBits (1 byte) */ if (version == 0x0009) { /* Version 0.9 */ if (tileSize != 0x0080) return FALSE; } else if (version == 0x0100) { /* Version 1.0 */ if (tileSize != 0x0040) return FALSE; } else return FALSE; if (colConvBits != 1) return FALSE; if (transformBits != 1) return FALSE; } } } else if (UuidEqual(&codecGuid, &CODEC_GUID_IMAGE_REMOTEFX, &rpc_status)) { /* Microsoft RDP servers ignore CODEC_GUID_IMAGE_REMOTEFX codec properties */ guidRemoteFxImage = TRUE; Stream_Seek(s, codecPropertiesLength); /* codecProperties */ } else if (UuidEqual(&codecGuid, &CODEC_GUID_NSCODEC, &rpc_status)) { BYTE colorLossLevel; BYTE fAllowSubsampling; BYTE fAllowDynamicFidelity; guidNSCodec = TRUE; settings->NSCodecId = codecId; Stream_Read_UINT8(s, fAllowDynamicFidelity); /* fAllowDynamicFidelity (1 byte) */ Stream_Read_UINT8(s, fAllowSubsampling); /* fAllowSubsampling (1 byte) */ Stream_Read_UINT8(s, colorLossLevel); /* colorLossLevel (1 byte) */ if (colorLossLevel < 1) colorLossLevel = 1; if (colorLossLevel > 7) colorLossLevel = 7; settings->NSCodecAllowDynamicColorFidelity = fAllowDynamicFidelity; settings->NSCodecAllowSubsampling = fAllowSubsampling; settings->NSCodecColorLossLevel = colorLossLevel; } else if (UuidEqual(&codecGuid, &CODEC_GUID_IGNORE, &rpc_status)) { Stream_Seek(s, codecPropertiesLength); /* codecProperties */ } else { Stream_Seek(s, codecPropertiesLength); /* codecProperties */ } if (Stream_GetPosition(s) != end) { WLog_ERR(TAG, "error while reading codec properties: actual offset: %" PRIuz " expected offset: %" PRIu32 "", Stream_GetPosition(s), end); Stream_SetPosition(s, end); } remainingLength -= codecPropertiesLength; } else { Stream_Seek(s, codecPropertiesLength); /* codecProperties */ remainingLength -= codecPropertiesLength; } bitmapCodecCount--; } if (settings->ServerMode) { /* only enable a codec if we've announced/enabled it before */ settings->RemoteFxCodec = settings->RemoteFxCodec && guidRemoteFx; settings->RemoteFxImageCodec = settings->RemoteFxImageCodec && guidRemoteFxImage; settings->NSCodec = settings->NSCodec && guidNSCodec; settings->JpegCodec = FALSE; } return TRUE; } /** * Write RemoteFX Client Capability Container.\n * @param s stream * @param settings settings */ static BOOL rdp_write_rfx_client_capability_container(wStream* s, const rdpSettings* settings) { UINT32 captureFlags; BYTE codecMode; if (!Stream_EnsureRemainingCapacity(s, 64)) return FALSE; captureFlags = settings->RemoteFxOnly ? 0 : CARDP_CAPS_CAPTURE_NON_CAC; codecMode = settings->RemoteFxCodecMode; Stream_Write_UINT16(s, 49); /* codecPropertiesLength */ /* TS_RFX_CLNT_CAPS_CONTAINER */ Stream_Write_UINT32(s, 49); /* length */ Stream_Write_UINT32(s, captureFlags); /* captureFlags */ Stream_Write_UINT32(s, 37); /* capsLength */ /* TS_RFX_CAPS */ Stream_Write_UINT16(s, CBY_CAPS); /* blockType */ Stream_Write_UINT32(s, 8); /* blockLen */ Stream_Write_UINT16(s, 1); /* numCapsets */ /* TS_RFX_CAPSET */ Stream_Write_UINT16(s, CBY_CAPSET); /* blockType */ Stream_Write_UINT32(s, 29); /* blockLen */ Stream_Write_UINT8(s, 0x01); /* codecId (MUST be set to 0x01) */ Stream_Write_UINT16(s, CLY_CAPSET); /* capsetType */ Stream_Write_UINT16(s, 2); /* numIcaps */ Stream_Write_UINT16(s, 8); /* icapLen */ /* TS_RFX_ICAP (RLGR1) */ Stream_Write_UINT16(s, CLW_VERSION_1_0); /* version */ Stream_Write_UINT16(s, CT_TILE_64x64); /* tileSize */ Stream_Write_UINT8(s, codecMode); /* flags */ Stream_Write_UINT8(s, CLW_COL_CONV_ICT); /* colConvBits */ Stream_Write_UINT8(s, CLW_XFORM_DWT_53_A); /* transformBits */ Stream_Write_UINT8(s, CLW_ENTROPY_RLGR1); /* entropyBits */ /* TS_RFX_ICAP (RLGR3) */ Stream_Write_UINT16(s, CLW_VERSION_1_0); /* version */ Stream_Write_UINT16(s, CT_TILE_64x64); /* tileSize */ Stream_Write_UINT8(s, codecMode); /* flags */ Stream_Write_UINT8(s, CLW_COL_CONV_ICT); /* colConvBits */ Stream_Write_UINT8(s, CLW_XFORM_DWT_53_A); /* transformBits */ Stream_Write_UINT8(s, CLW_ENTROPY_RLGR3); /* entropyBits */ return TRUE; } /** * Write NSCODEC Client Capability Container.\n * @param s stream * @param settings settings */ static BOOL rdp_write_nsc_client_capability_container(wStream* s, const rdpSettings* settings) { BYTE colorLossLevel; BYTE fAllowSubsampling; BYTE fAllowDynamicFidelity; fAllowDynamicFidelity = settings->NSCodecAllowDynamicColorFidelity; fAllowSubsampling = settings->NSCodecAllowSubsampling; colorLossLevel = settings->NSCodecColorLossLevel; if (colorLossLevel < 1) colorLossLevel = 1; if (colorLossLevel > 7) colorLossLevel = 7; if (!Stream_EnsureRemainingCapacity(s, 8)) return FALSE; Stream_Write_UINT16(s, 3); /* codecPropertiesLength */ /* TS_NSCODEC_CAPABILITYSET */ Stream_Write_UINT8(s, fAllowDynamicFidelity); /* fAllowDynamicFidelity (1 byte) */ Stream_Write_UINT8(s, fAllowSubsampling); /* fAllowSubsampling (1 byte) */ Stream_Write_UINT8(s, colorLossLevel); /* colorLossLevel (1 byte) */ return TRUE; } #if defined(WITH_JPEG) static BOOL rdp_write_jpeg_client_capability_container(wStream* s, const rdpSettings* settings) { if (!Stream_EnsureRemainingCapacity(s, 8)) return FALSE; Stream_Write_UINT16(s, 1); /* codecPropertiesLength */ Stream_Write_UINT8(s, settings->JpegQuality); return TRUE; } #endif /** * Write RemoteFX Server Capability Container.\n * @param s stream * @param settings settings */ static BOOL rdp_write_rfx_server_capability_container(wStream* s, const rdpSettings* settings) { WINPR_UNUSED(settings); if (!Stream_EnsureRemainingCapacity(s, 8)) return FALSE; Stream_Write_UINT16(s, 4); /* codecPropertiesLength */ Stream_Write_UINT32(s, 0); /* reserved */ return TRUE; } static BOOL rdp_write_jpeg_server_capability_container(wStream* s, const rdpSettings* settings) { WINPR_UNUSED(settings); if (!Stream_EnsureRemainingCapacity(s, 8)) return FALSE; Stream_Write_UINT16(s, 1); /* codecPropertiesLength */ Stream_Write_UINT8(s, 75); return TRUE; } /** * Write NSCODEC Server Capability Container.\n * @param s stream * @param settings settings */ static BOOL rdp_write_nsc_server_capability_container(wStream* s, const rdpSettings* settings) { WINPR_UNUSED(settings); if (!Stream_EnsureRemainingCapacity(s, 8)) return FALSE; Stream_Write_UINT16(s, 4); /* codecPropertiesLength */ Stream_Write_UINT32(s, 0); /* reserved */ return TRUE; } /** * Write bitmap codecs capability set.\n * @msdn{dd891377} * @param s stream * @param settings settings */ static BOOL rdp_write_bitmap_codecs_capability_set(wStream* s, const rdpSettings* settings) { size_t header; BYTE bitmapCodecCount; if (!Stream_EnsureRemainingCapacity(s, 64)) return FALSE; header = rdp_capability_set_start(s); bitmapCodecCount = 0; if (settings->RemoteFxCodec) bitmapCodecCount++; if (settings->NSCodec) bitmapCodecCount++; #if defined(WITH_JPEG) if (settings->JpegCodec) bitmapCodecCount++; #endif if (settings->RemoteFxImageCodec) bitmapCodecCount++; Stream_Write_UINT8(s, bitmapCodecCount); if (settings->RemoteFxCodec) { rdp_write_bitmap_codec_guid(s, &CODEC_GUID_REMOTEFX); /* codecGUID */ if (settings->ServerMode) { Stream_Write_UINT8(s, 0); /* codecID is defined by the client */ if (!rdp_write_rfx_server_capability_container(s, settings)) return FALSE; } else { Stream_Write_UINT8(s, RDP_CODEC_ID_REMOTEFX); /* codecID */ if (!rdp_write_rfx_client_capability_container(s, settings)) return FALSE; } } if (settings->NSCodec) { rdp_write_bitmap_codec_guid(s, &CODEC_GUID_NSCODEC); /* codecGUID */ if (settings->ServerMode) { Stream_Write_UINT8(s, 0); /* codecID is defined by the client */ if (!rdp_write_nsc_server_capability_container(s, settings)) return FALSE; } else { Stream_Write_UINT8(s, RDP_CODEC_ID_NSCODEC); /* codecID */ if (!rdp_write_nsc_client_capability_container(s, settings)) return FALSE; } } #if defined(WITH_JPEG) if (settings->JpegCodec) { rdp_write_bitmap_codec_guid(s, &CODEC_GUID_JPEG); /* codecGUID */ if (settings->ServerMode) { Stream_Write_UINT8(s, 0); /* codecID is defined by the client */ if (!rdp_write_jpeg_server_capability_container(s, settings)) return FALSE; } else { Stream_Write_UINT8(s, RDP_CODEC_ID_JPEG); /* codecID */ if (!rdp_write_jpeg_client_capability_container(s, settings)) return FALSE; } } #endif if (settings->RemoteFxImageCodec) { rdp_write_bitmap_codec_guid(s, &CODEC_GUID_IMAGE_REMOTEFX); /* codecGUID */ if (settings->ServerMode) { Stream_Write_UINT8(s, 0); /* codecID is defined by the client */ if (!rdp_write_rfx_server_capability_container(s, settings)) return FALSE; } else { Stream_Write_UINT8(s, RDP_CODEC_ID_IMAGE_REMOTEFX); /* codecID */ if (!rdp_write_rfx_client_capability_container(s, settings)) return FALSE; } } rdp_capability_set_finish(s, header, CAPSET_TYPE_BITMAP_CODECS); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_bitmap_codecs_capability_set(wStream* s, UINT16 length) { GUID codecGuid; BYTE bitmapCodecCount; BYTE codecId; UINT16 codecPropertiesLength; UINT16 remainingLength; WLog_INFO(TAG, "BitmapCodecsCapabilitySet (length %" PRIu16 "):", length); if (length < 5) return FALSE; Stream_Read_UINT8(s, bitmapCodecCount); /* bitmapCodecCount (1 byte) */ remainingLength = length - 5; WLog_INFO(TAG, "\tbitmapCodecCount: %" PRIu8 "", bitmapCodecCount); while (bitmapCodecCount > 0) { if (remainingLength < 19) return FALSE; rdp_read_bitmap_codec_guid(s, &codecGuid); /* codecGuid (16 bytes) */ Stream_Read_UINT8(s, codecId); /* codecId (1 byte) */ WLog_INFO(TAG, "\tcodecGuid: 0x"); rdp_print_bitmap_codec_guid(&codecGuid); WLog_INFO(TAG, " (%s)", rdp_get_bitmap_codec_guid_name(&codecGuid)); WLog_INFO(TAG, "\tcodecId: %" PRIu8 "", codecId); Stream_Read_UINT16(s, codecPropertiesLength); /* codecPropertiesLength (2 bytes) */ WLog_INFO(TAG, "\tcodecPropertiesLength: %" PRIu16 "", codecPropertiesLength); remainingLength -= 19; if (remainingLength < codecPropertiesLength) return FALSE; Stream_Seek(s, codecPropertiesLength); /* codecProperties */ remainingLength -= codecPropertiesLength; bitmapCodecCount--; } return TRUE; } #endif /** * Read frame acknowledge capability set.\n * @param s stream * @param settings settings * @return if the operation completed successfully */ static BOOL rdp_read_frame_acknowledge_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { if (length < 8) return FALSE; if (settings->ServerMode) { Stream_Read_UINT32(s, settings->FrameAcknowledge); /* (4 bytes) */ } else { Stream_Seek_UINT32(s); /* (4 bytes) */ } return TRUE; } /** * Write frame acknowledge capability set.\n * @param s stream * @param settings settings */ static BOOL rdp_write_frame_acknowledge_capability_set(wStream* s, const rdpSettings* settings) { size_t header; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; Stream_Write_UINT32(s, settings->FrameAcknowledge); /* (4 bytes) */ rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_FRAME_ACKNOWLEDGE); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_frame_acknowledge_capability_set(wStream* s, UINT16 length) { UINT32 frameAcknowledge; WLog_INFO(TAG, "FrameAcknowledgeCapabilitySet (length %" PRIu16 "):", length); if (length < 8) return FALSE; Stream_Read_UINT32(s, frameAcknowledge); /* frameAcknowledge (4 bytes) */ WLog_INFO(TAG, "\tframeAcknowledge: 0x%08" PRIX32 "", frameAcknowledge); return TRUE; } #endif static BOOL rdp_read_bitmap_cache_v3_codec_id_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { BYTE bitmapCacheV3CodecId; WINPR_UNUSED(settings); if (length < 5) return FALSE; Stream_Read_UINT8(s, bitmapCacheV3CodecId); /* bitmapCacheV3CodecId (1 byte) */ return TRUE; } static BOOL rdp_write_bitmap_cache_v3_codec_id_capability_set(wStream* s, const rdpSettings* settings) { size_t header; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; header = rdp_capability_set_start(s); if (header > UINT16_MAX) return FALSE; if (settings->BitmapCacheV3CodecId > UINT8_MAX) return FALSE; Stream_Write_UINT8(s, (UINT8)settings->BitmapCacheV3CodecId); rdp_capability_set_finish(s, (UINT16)header, CAPSET_TYPE_BITMAP_CACHE_V3_CODEC_ID); return TRUE; } #ifdef WITH_DEBUG_CAPABILITIES static BOOL rdp_print_bitmap_cache_v3_codec_id_capability_set(wStream* s, UINT16 length) { BYTE bitmapCacheV3CodecId; WLog_INFO(TAG, "BitmapCacheV3CodecIdCapabilitySet (length %" PRIu16 "):", length); if (length < 5) return FALSE; Stream_Read_UINT8(s, bitmapCacheV3CodecId); /* bitmapCacheV3CodecId (1 byte) */ WLog_INFO(TAG, "\tbitmapCacheV3CodecId: 0x%02" PRIX8 "", bitmapCacheV3CodecId); return TRUE; } static BOOL rdp_print_capability_sets(wStream* s, UINT16 numberCapabilities, BOOL receiving) { UINT16 type; UINT16 length; BYTE *bm, *em; while (numberCapabilities > 0) { Stream_GetPointer(s, bm); rdp_read_capability_set_header(s, &length, &type); WLog_INFO(TAG, "%s ", receiving ? "Receiving" : "Sending"); em = bm + length; if (Stream_GetRemainingLength(s) < (size_t)(length - 4)) { WLog_ERR(TAG, "error processing stream"); return FALSE; } switch (type) { case CAPSET_TYPE_GENERAL: if (!rdp_print_general_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_BITMAP: if (!rdp_print_bitmap_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_ORDER: if (!rdp_print_order_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_BITMAP_CACHE: if (!rdp_print_bitmap_cache_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_CONTROL: if (!rdp_print_control_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_ACTIVATION: if (!rdp_print_window_activation_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_POINTER: if (!rdp_print_pointer_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_SHARE: if (!rdp_print_share_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_COLOR_CACHE: if (!rdp_print_color_cache_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_SOUND: if (!rdp_print_sound_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_INPUT: if (!rdp_print_input_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_FONT: if (!rdp_print_font_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_BRUSH: if (!rdp_print_brush_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_GLYPH_CACHE: if (!rdp_print_glyph_cache_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_OFFSCREEN_CACHE: if (!rdp_print_offscreen_bitmap_cache_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_BITMAP_CACHE_HOST_SUPPORT: if (!rdp_print_bitmap_cache_host_support_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_BITMAP_CACHE_V2: if (!rdp_print_bitmap_cache_v2_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_VIRTUAL_CHANNEL: if (!rdp_print_virtual_channel_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_DRAW_NINE_GRID_CACHE: if (!rdp_print_draw_nine_grid_cache_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_DRAW_GDI_PLUS: if (!rdp_print_draw_gdiplus_cache_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_RAIL: if (!rdp_print_remote_programs_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_WINDOW: if (!rdp_print_window_list_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_COMP_DESK: if (!rdp_print_desktop_composition_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_MULTI_FRAGMENT_UPDATE: if (!rdp_print_multifragment_update_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_LARGE_POINTER: if (!rdp_print_large_pointer_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_SURFACE_COMMANDS: if (!rdp_print_surface_commands_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_BITMAP_CODECS: if (!rdp_print_bitmap_codecs_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_FRAME_ACKNOWLEDGE: if (!rdp_print_frame_acknowledge_capability_set(s, length)) return FALSE; break; case CAPSET_TYPE_BITMAP_CACHE_V3_CODEC_ID: if (!rdp_print_bitmap_cache_v3_codec_id_capability_set(s, length)) return FALSE; break; default: WLog_ERR(TAG, "unknown capability type %" PRIu16 "", type); break; } if (Stream_Pointer(s) != em) { WLog_ERR(TAG, "incorrect offset, type:0x%04" PRIX16 " actual:%" PRIuz " expected:%" PRIuz "", type, Stream_Pointer(s) - bm, em - bm); } Stream_SetPointer(s, em); numberCapabilities--; } return TRUE; } #endif static BOOL rdp_read_capability_sets(wStream* s, rdpSettings* settings, UINT16 numberCapabilities, UINT16 totalLength) { BOOL treated; size_t start, end, len; UINT16 count = numberCapabilities; start = Stream_GetPosition(s); while (numberCapabilities > 0 && Stream_GetRemainingLength(s) >= 4) { UINT16 type; UINT16 length; BYTE* em; BYTE* bm = Stream_Pointer(s); rdp_read_capability_set_header(s, &length, &type); if (type < 32) { settings->ReceivedCapabilities[type] = TRUE; } else { WLog_WARN(TAG, "not handling capability type %" PRIu16 " yet", type); } em = bm + length; if (Stream_GetRemainingLength(s) + 4 < ((size_t)length)) { WLog_ERR(TAG, "error processing stream"); return FALSE; } treated = TRUE; switch (type) { case CAPSET_TYPE_GENERAL: if (!rdp_read_general_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_BITMAP: if (!rdp_read_bitmap_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_ORDER: if (!rdp_read_order_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_POINTER: if (!rdp_read_pointer_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_INPUT: if (!rdp_read_input_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_VIRTUAL_CHANNEL: if (!rdp_read_virtual_channel_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_SHARE: if (!rdp_read_share_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_COLOR_CACHE: if (!rdp_read_color_cache_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_FONT: if (!rdp_read_font_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_DRAW_GDI_PLUS: if (!rdp_read_draw_gdiplus_cache_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_RAIL: if (!rdp_read_remote_programs_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_WINDOW: if (!rdp_read_window_list_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_MULTI_FRAGMENT_UPDATE: if (!rdp_read_multifragment_update_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_LARGE_POINTER: if (!rdp_read_large_pointer_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_COMP_DESK: if (!rdp_read_desktop_composition_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_SURFACE_COMMANDS: if (!rdp_read_surface_commands_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_BITMAP_CODECS: if (!rdp_read_bitmap_codecs_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_FRAME_ACKNOWLEDGE: if (!rdp_read_frame_acknowledge_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_BITMAP_CACHE_V3_CODEC_ID: if (!rdp_read_bitmap_cache_v3_codec_id_capability_set(s, length, settings)) return FALSE; break; default: treated = FALSE; break; } if (!treated) { if (settings->ServerMode) { /* treating capabilities that are supposed to be send only from the client */ switch (type) { case CAPSET_TYPE_BITMAP_CACHE: if (!rdp_read_bitmap_cache_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_BITMAP_CACHE_V2: if (!rdp_read_bitmap_cache_v2_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_BRUSH: if (!rdp_read_brush_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_GLYPH_CACHE: if (!rdp_read_glyph_cache_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_OFFSCREEN_CACHE: if (!rdp_read_offscreen_bitmap_cache_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_SOUND: if (!rdp_read_sound_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_CONTROL: if (!rdp_read_control_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_ACTIVATION: if (!rdp_read_window_activation_capability_set(s, length, settings)) return FALSE; break; case CAPSET_TYPE_DRAW_NINE_GRID_CACHE: if (!rdp_read_draw_nine_grid_cache_capability_set(s, length, settings)) return FALSE; break; default: WLog_ERR(TAG, "capability %s(%" PRIu16 ") not expected from client", get_capability_name(type), type); return FALSE; } } else { /* treating capabilities that are supposed to be send only from the server */ switch (type) { case CAPSET_TYPE_BITMAP_CACHE_HOST_SUPPORT: if (!rdp_read_bitmap_cache_host_support_capability_set(s, length, settings)) return FALSE; break; default: WLog_ERR(TAG, "capability %s(%" PRIu16 ") not expected from server", get_capability_name(type), type); return FALSE; } } } if (Stream_Pointer(s) != em) { WLog_ERR(TAG, "incorrect offset, type:0x%04" PRIX16 " actual:%" PRIuz " expected:%" PRIuz "", type, Stream_Pointer(s) - bm, em - bm); Stream_SetPointer(s, em); } numberCapabilities--; } end = Stream_GetPosition(s); len = end - start; if (numberCapabilities) { WLog_ERR(TAG, "strange we haven't read the number of announced capacity sets, read=%d " "expected=%" PRIu16 "", count - numberCapabilities, count); } #ifdef WITH_DEBUG_CAPABILITIES { Stream_SetPosition(s, start); numberCapabilities = count; rdp_print_capability_sets(s, numberCapabilities, TRUE); Stream_SetPosition(s, end); } #endif if (len > totalLength) { WLog_ERR(TAG, "Capability length expected %" PRIu16 ", actual %" PRIdz, totalLength, len); return FALSE; } return TRUE; } BOOL rdp_recv_get_active_header(rdpRdp* rdp, wStream* s, UINT16* pChannelId, UINT16* length) { UINT16 securityFlags = 0; if (!rdp_read_header(rdp, s, length, pChannelId)) return FALSE; if (freerdp_shall_disconnect(rdp->instance)) return TRUE; if (rdp->settings->UseRdpSecurityLayer) { if (!rdp_read_security_header(s, &securityFlags, length)) return FALSE; if (securityFlags & SEC_ENCRYPT) { if (!rdp_decrypt(rdp, s, length, securityFlags)) { WLog_ERR(TAG, "rdp_decrypt failed"); return FALSE; } } } if (*pChannelId != MCS_GLOBAL_CHANNEL_ID) { UINT16 mcsMessageChannelId = rdp->mcs->messageChannelId; if ((mcsMessageChannelId == 0) || (*pChannelId != mcsMessageChannelId)) { WLog_ERR(TAG, "unexpected MCS channel id %04" PRIx16 " received", *pChannelId); return FALSE; } } return TRUE; } BOOL rdp_recv_demand_active(rdpRdp* rdp, wStream* s) { UINT16 channelId; UINT16 pduType; UINT16 pduLength; UINT16 pduSource; UINT16 length; UINT16 numberCapabilities; UINT16 lengthSourceDescriptor; UINT16 lengthCombinedCapabilities; if (!rdp_recv_get_active_header(rdp, s, &channelId, &length)) return FALSE; if (freerdp_shall_disconnect(rdp->instance)) return TRUE; if (!rdp_read_share_control_header(s, &pduLength, &pduType, &pduSource)) { WLog_ERR(TAG, "rdp_read_share_control_header failed"); return FALSE; } if (pduType == PDU_TYPE_DATA) { /** * We can receive a Save Session Info Data PDU containing a LogonErrorInfo * structure at this point from the server to indicate a connection error. */ if (rdp_recv_data_pdu(rdp, s) < 0) return FALSE; return FALSE; } if (pduType != PDU_TYPE_DEMAND_ACTIVE) { if (pduType != PDU_TYPE_SERVER_REDIRECTION) WLog_ERR(TAG, "expected PDU_TYPE_DEMAND_ACTIVE %04x, got %04" PRIx16 "", PDU_TYPE_DEMAND_ACTIVE, pduType); return FALSE; } rdp->settings->PduSource = pduSource; if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT32(s, rdp->settings->ShareId); /* shareId (4 bytes) */ Stream_Read_UINT16(s, lengthSourceDescriptor); /* lengthSourceDescriptor (2 bytes) */ Stream_Read_UINT16(s, lengthCombinedCapabilities); /* lengthCombinedCapabilities (2 bytes) */ if (!Stream_SafeSeek(s, lengthSourceDescriptor) || Stream_GetRemainingLength(s) < 4) /* sourceDescriptor */ return FALSE; Stream_Read_UINT16(s, numberCapabilities); /* numberCapabilities (2 bytes) */ Stream_Seek(s, 2); /* pad2Octets (2 bytes) */ /* capabilitySets */ if (!rdp_read_capability_sets(s, rdp->settings, numberCapabilities, lengthCombinedCapabilities)) { WLog_ERR(TAG, "rdp_read_capability_sets failed"); return FALSE; } if (!Stream_SafeSeek(s, 4)) /* SessionId */ return FALSE; rdp->update->secondary->glyph_v2 = (rdp->settings->GlyphSupportLevel > GLYPH_SUPPORT_FULL); return tpkt_ensure_stream_consumed(s, length); } static BOOL rdp_write_demand_active(wStream* s, rdpSettings* settings) { size_t bm, em, lm; UINT16 numberCapabilities; size_t lengthCombinedCapabilities; if (!Stream_EnsureRemainingCapacity(s, 64)) return FALSE; Stream_Write_UINT32(s, settings->ShareId); /* shareId (4 bytes) */ Stream_Write_UINT16(s, 4); /* lengthSourceDescriptor (2 bytes) */ lm = Stream_GetPosition(s); Stream_Seek_UINT16(s); /* lengthCombinedCapabilities (2 bytes) */ Stream_Write(s, "RDP", 4); /* sourceDescriptor */ bm = Stream_GetPosition(s); Stream_Seek_UINT16(s); /* numberCapabilities (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2Octets (2 bytes) */ numberCapabilities = 14; if (!rdp_write_general_capability_set(s, settings) || !rdp_write_bitmap_capability_set(s, settings) || !rdp_write_order_capability_set(s, settings) || !rdp_write_pointer_capability_set(s, settings) || !rdp_write_input_capability_set(s, settings) || !rdp_write_virtual_channel_capability_set(s, settings) || !rdp_write_share_capability_set(s, settings) || !rdp_write_font_capability_set(s, settings) || !rdp_write_multifragment_update_capability_set(s, settings) || !rdp_write_large_pointer_capability_set(s, settings) || !rdp_write_desktop_composition_capability_set(s, settings) || !rdp_write_surface_commands_capability_set(s, settings) || !rdp_write_bitmap_codecs_capability_set(s, settings) || !rdp_write_frame_acknowledge_capability_set(s, settings)) { return FALSE; } if (settings->BitmapCachePersistEnabled) { numberCapabilities++; if (!rdp_write_bitmap_cache_host_support_capability_set(s, settings)) return FALSE; } if (settings->RemoteApplicationMode) { numberCapabilities += 2; if (!rdp_write_remote_programs_capability_set(s, settings) || !rdp_write_window_list_capability_set(s, settings)) return FALSE; } em = Stream_GetPosition(s); Stream_SetPosition(s, lm); /* go back to lengthCombinedCapabilities */ lengthCombinedCapabilities = (em - bm); if (lengthCombinedCapabilities > UINT16_MAX) return FALSE; Stream_Write_UINT16( s, (UINT16)lengthCombinedCapabilities); /* lengthCombinedCapabilities (2 bytes) */ Stream_SetPosition(s, bm); /* go back to numberCapabilities */ Stream_Write_UINT16(s, numberCapabilities); /* numberCapabilities (2 bytes) */ #ifdef WITH_DEBUG_CAPABILITIES Stream_Seek_UINT16(s); rdp_print_capability_sets(s, numberCapabilities, FALSE); Stream_SetPosition(s, bm); Stream_Seek_UINT16(s); #endif Stream_SetPosition(s, em); Stream_Write_UINT32(s, 0); /* sessionId */ return TRUE; } BOOL rdp_send_demand_active(rdpRdp* rdp) { wStream* s = rdp_send_stream_pdu_init(rdp); BOOL status; if (!s) return FALSE; rdp->settings->ShareId = 0x10000 + rdp->mcs->userId; status = rdp_write_demand_active(s, rdp->settings) && rdp_send_pdu(rdp, s, PDU_TYPE_DEMAND_ACTIVE, rdp->mcs->userId); Stream_Release(s); return status; } BOOL rdp_recv_confirm_active(rdpRdp* rdp, wStream* s, UINT16 pduLength) { rdpSettings* settings; UINT16 lengthSourceDescriptor; UINT16 lengthCombinedCapabilities; UINT16 numberCapabilities; settings = rdp->settings; if (Stream_GetRemainingLength(s) < 10) return FALSE; Stream_Seek_UINT32(s); /* shareId (4 bytes) */ Stream_Seek_UINT16(s); /* originatorId (2 bytes) */ Stream_Read_UINT16(s, lengthSourceDescriptor); /* lengthSourceDescriptor (2 bytes) */ Stream_Read_UINT16(s, lengthCombinedCapabilities); /* lengthCombinedCapabilities (2 bytes) */ if (Stream_GetRemainingLength(s) < lengthSourceDescriptor + 4U) return FALSE; Stream_Seek(s, lengthSourceDescriptor); /* sourceDescriptor */ Stream_Read_UINT16(s, numberCapabilities); /* numberCapabilities (2 bytes) */ Stream_Seek(s, 2); /* pad2Octets (2 bytes) */ if (!rdp_read_capability_sets(s, rdp->settings, numberCapabilities, lengthCombinedCapabilities)) return FALSE; if (!settings->ReceivedCapabilities[CAPSET_TYPE_SURFACE_COMMANDS]) { /* client does not support surface commands */ settings->SurfaceCommandsEnabled = FALSE; settings->SurfaceFrameMarkerEnabled = FALSE; } if (!settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE]) { /* client does not support frame acks */ settings->FrameAcknowledge = 0; } if (!settings->ReceivedCapabilities[CAPSET_TYPE_BITMAP_CACHE_V3_CODEC_ID]) { /* client does not support bitmap cache v3 */ settings->BitmapCacheV3Enabled = FALSE; } if (!settings->ReceivedCapabilities[CAPSET_TYPE_BITMAP_CODECS]) { /* client does not support bitmap codecs */ settings->RemoteFxCodec = FALSE; settings->NSCodec = FALSE; settings->JpegCodec = FALSE; } if (!settings->ReceivedCapabilities[CAPSET_TYPE_MULTI_FRAGMENT_UPDATE]) { /* client does not support multi fragment updates - make sure packages are not fragmented */ settings->MultifragMaxRequestSize = FASTPATH_FRAGMENT_SAFE_SIZE; } if (!settings->ReceivedCapabilities[CAPSET_TYPE_LARGE_POINTER]) { /* client does not support large pointers */ settings->LargePointerFlag = 0; } return tpkt_ensure_stream_consumed(s, pduLength); } static BOOL rdp_write_confirm_active(wStream* s, rdpSettings* settings) { size_t bm, em, lm; UINT16 numberCapabilities; UINT16 lengthSourceDescriptor; size_t lengthCombinedCapabilities; BOOL ret; lengthSourceDescriptor = sizeof(SOURCE_DESCRIPTOR); Stream_Write_UINT32(s, settings->ShareId); /* shareId (4 bytes) */ Stream_Write_UINT16(s, 0x03EA); /* originatorId (2 bytes) */ Stream_Write_UINT16(s, lengthSourceDescriptor); /* lengthSourceDescriptor (2 bytes) */ lm = Stream_GetPosition(s); Stream_Seek_UINT16(s); /* lengthCombinedCapabilities (2 bytes) */ Stream_Write(s, SOURCE_DESCRIPTOR, lengthSourceDescriptor); /* sourceDescriptor */ bm = Stream_GetPosition(s); Stream_Seek_UINT16(s); /* numberCapabilities (2 bytes) */ Stream_Write_UINT16(s, 0); /* pad2Octets (2 bytes) */ /* Capability Sets */ numberCapabilities = 15; if (!rdp_write_general_capability_set(s, settings) || !rdp_write_bitmap_capability_set(s, settings) || !rdp_write_order_capability_set(s, settings)) return FALSE; if (settings->RdpVersion >= RDP_VERSION_5_PLUS) ret = rdp_write_bitmap_cache_v2_capability_set(s, settings); else ret = rdp_write_bitmap_cache_capability_set(s, settings); if (!ret) return FALSE; if (!rdp_write_pointer_capability_set(s, settings) || !rdp_write_input_capability_set(s, settings) || !rdp_write_brush_capability_set(s, settings) || !rdp_write_glyph_cache_capability_set(s, settings) || !rdp_write_virtual_channel_capability_set(s, settings) || !rdp_write_sound_capability_set(s, settings) || !rdp_write_share_capability_set(s, settings) || !rdp_write_font_capability_set(s, settings) || !rdp_write_control_capability_set(s, settings) || !rdp_write_color_cache_capability_set(s, settings) || !rdp_write_window_activation_capability_set(s, settings)) { return FALSE; } if (settings->OffscreenSupportLevel) { numberCapabilities++; if (!rdp_write_offscreen_bitmap_cache_capability_set(s, settings)) return FALSE; } if (settings->DrawNineGridEnabled) { numberCapabilities++; if (!rdp_write_draw_nine_grid_cache_capability_set(s, settings)) return FALSE; } if (settings->ReceivedCapabilities[CAPSET_TYPE_LARGE_POINTER]) { if (settings->LargePointerFlag) { numberCapabilities++; if (!rdp_write_large_pointer_capability_set(s, settings)) return FALSE; } } if (settings->RemoteApplicationMode) { numberCapabilities += 2; if (!rdp_write_remote_programs_capability_set(s, settings) || !rdp_write_window_list_capability_set(s, settings)) return FALSE; } if (settings->ReceivedCapabilities[CAPSET_TYPE_MULTI_FRAGMENT_UPDATE]) { numberCapabilities++; if (!rdp_write_multifragment_update_capability_set(s, settings)) return FALSE; } if (settings->ReceivedCapabilities[CAPSET_TYPE_SURFACE_COMMANDS]) { numberCapabilities++; if (!rdp_write_surface_commands_capability_set(s, settings)) return FALSE; } if (settings->ReceivedCapabilities[CAPSET_TYPE_BITMAP_CODECS]) { numberCapabilities++; if (!rdp_write_bitmap_codecs_capability_set(s, settings)) return FALSE; } if (!settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE]) settings->FrameAcknowledge = 0; if (settings->FrameAcknowledge) { numberCapabilities++; if (!rdp_write_frame_acknowledge_capability_set(s, settings)) return FALSE; } if (settings->ReceivedCapabilities[CAPSET_TYPE_BITMAP_CACHE_V3_CODEC_ID]) { if (settings->BitmapCacheV3CodecId != 0) { numberCapabilities++; if (!rdp_write_bitmap_cache_v3_codec_id_capability_set(s, settings)) return FALSE; } } em = Stream_GetPosition(s); Stream_SetPosition(s, lm); /* go back to lengthCombinedCapabilities */ lengthCombinedCapabilities = (em - bm); if (lengthCombinedCapabilities > UINT16_MAX) return FALSE; Stream_Write_UINT16( s, (UINT16)lengthCombinedCapabilities); /* lengthCombinedCapabilities (2 bytes) */ Stream_SetPosition(s, bm); /* go back to numberCapabilities */ Stream_Write_UINT16(s, numberCapabilities); /* numberCapabilities (2 bytes) */ #ifdef WITH_DEBUG_CAPABILITIES Stream_Seek_UINT16(s); rdp_print_capability_sets(s, numberCapabilities, FALSE); Stream_SetPosition(s, bm); Stream_Seek_UINT16(s); #endif Stream_SetPosition(s, em); return TRUE; } BOOL rdp_send_confirm_active(rdpRdp* rdp) { wStream* s = rdp_send_stream_pdu_init(rdp); BOOL status; if (!s) return FALSE; status = rdp_write_confirm_active(s, rdp->settings) && rdp_send_pdu(rdp, s, PDU_TYPE_CONFIRM_ACTIVE, rdp->mcs->userId); Stream_Release(s); return status; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3924_0
crossvul-cpp_data_bad_2019_1
/* src/interfaces/ecpg/pgtypeslib/datetime.c */ #include "postgres_fe.h" #include <time.h> #include <ctype.h> #include <float.h> #include <limits.h> #include "extern.h" #include "dt.h" #include "pgtypes_error.h" #include "pgtypes_date.h" date * PGTYPESdate_new(void) { date *result; result = (date *) pgtypes_alloc(sizeof(date)); /* result can be NULL if we run out of memory */ return result; } void PGTYPESdate_free(date * d) { free(d); } date PGTYPESdate_from_timestamp(timestamp dt) { date dDate; dDate = 0; /* suppress compiler warning */ if (!TIMESTAMP_NOT_FINITE(dt)) { #ifdef HAVE_INT64_TIMESTAMP /* Microseconds to days */ dDate = (dt / USECS_PER_DAY); #else /* Seconds to days */ dDate = (dt / (double) SECS_PER_DAY); #endif } return dDate; } date PGTYPESdate_from_asc(char *str, char **endptr) { date dDate; fsec_t fsec; struct tm tt, *tm = &tt; int dtype; int nf; char *field[MAXDATEFIELDS]; int ftype[MAXDATEFIELDS]; char lowstr[MAXDATELEN + 1]; char *realptr; char **ptr = (endptr != NULL) ? endptr : &realptr; bool EuroDates = FALSE; errno = 0; if (strlen(str) >= sizeof(lowstr)) { errno = PGTYPES_DATE_BAD_DATE; return INT_MIN; } if (ParseDateTime(str, lowstr, field, ftype, &nf, ptr) != 0 || DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, EuroDates) != 0) { errno = PGTYPES_DATE_BAD_DATE; return INT_MIN; } switch (dtype) { case DTK_DATE: break; case DTK_EPOCH: if (GetEpochTime(tm) < 0) { errno = PGTYPES_DATE_BAD_DATE; return INT_MIN; } break; default: errno = PGTYPES_DATE_BAD_DATE; return INT_MIN; } dDate = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - date2j(2000, 1, 1)); return dDate; } char * PGTYPESdate_to_asc(date dDate) { struct tm tt, *tm = &tt; char buf[MAXDATELEN + 1]; int DateStyle = 1; bool EuroDates = FALSE; j2date(dDate + date2j(2000, 1, 1), &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday)); EncodeDateOnly(tm, DateStyle, buf, EuroDates); return pgtypes_strdup(buf); } void PGTYPESdate_julmdy(date jd, int *mdy) { int y, m, d; j2date((int) (jd + date2j(2000, 1, 1)), &y, &m, &d); mdy[0] = m; mdy[1] = d; mdy[2] = y; } void PGTYPESdate_mdyjul(int *mdy, date * jdate) { /* month is mdy[0] */ /* day is mdy[1] */ /* year is mdy[2] */ *jdate = (date) (date2j(mdy[2], mdy[0], mdy[1]) - date2j(2000, 1, 1)); } int PGTYPESdate_dayofweek(date dDate) { /* * Sunday: 0 Monday: 1 Tuesday: 2 Wednesday: 3 Thursday: 4 * Friday: 5 Saturday: 6 */ return (int) (dDate + date2j(2000, 1, 1) + 1) % 7; } void PGTYPESdate_today(date * d) { struct tm ts; GetCurrentDateTime(&ts); if (errno == 0) *d = date2j(ts.tm_year, ts.tm_mon, ts.tm_mday) - date2j(2000, 1, 1); return; } #define PGTYPES_DATE_NUM_MAX_DIGITS 20 /* should suffice for most * years... */ #define PGTYPES_FMTDATE_DAY_DIGITS_LZ 1 /* LZ means "leading zeroes" */ #define PGTYPES_FMTDATE_DOW_LITERAL_SHORT 2 #define PGTYPES_FMTDATE_MONTH_DIGITS_LZ 3 #define PGTYPES_FMTDATE_MONTH_LITERAL_SHORT 4 #define PGTYPES_FMTDATE_YEAR_DIGITS_SHORT 5 #define PGTYPES_FMTDATE_YEAR_DIGITS_LONG 6 int PGTYPESdate_fmt_asc(date dDate, const char *fmtstring, char *outbuf) { static struct { char *format; int component; } mapping[] = { /* * format items have to be sorted according to their length, since the * first pattern that matches gets replaced by its value */ { "ddd", PGTYPES_FMTDATE_DOW_LITERAL_SHORT }, { "dd", PGTYPES_FMTDATE_DAY_DIGITS_LZ }, { "mmm", PGTYPES_FMTDATE_MONTH_LITERAL_SHORT }, { "mm", PGTYPES_FMTDATE_MONTH_DIGITS_LZ }, { "yyyy", PGTYPES_FMTDATE_YEAR_DIGITS_LONG }, { "yy", PGTYPES_FMTDATE_YEAR_DIGITS_SHORT }, { NULL, 0 } }; union un_fmt_comb replace_val; int replace_type; int i; int dow; char *start_pattern; struct tm tm; /* copy the string over */ strcpy(outbuf, fmtstring); /* get the date */ j2date(dDate + date2j(2000, 1, 1), &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday)); dow = PGTYPESdate_dayofweek(dDate); for (i = 0; mapping[i].format != NULL; i++) { while ((start_pattern = strstr(outbuf, mapping[i].format)) != NULL) { switch (mapping[i].component) { case PGTYPES_FMTDATE_DOW_LITERAL_SHORT: replace_val.str_val = pgtypes_date_weekdays_short[dow]; replace_type = PGTYPES_TYPE_STRING_CONSTANT; break; case PGTYPES_FMTDATE_DAY_DIGITS_LZ: replace_val.uint_val = tm.tm_mday; replace_type = PGTYPES_TYPE_UINT_2_LZ; break; case PGTYPES_FMTDATE_MONTH_LITERAL_SHORT: replace_val.str_val = months[tm.tm_mon - 1]; replace_type = PGTYPES_TYPE_STRING_CONSTANT; break; case PGTYPES_FMTDATE_MONTH_DIGITS_LZ: replace_val.uint_val = tm.tm_mon; replace_type = PGTYPES_TYPE_UINT_2_LZ; break; case PGTYPES_FMTDATE_YEAR_DIGITS_LONG: replace_val.uint_val = tm.tm_year; replace_type = PGTYPES_TYPE_UINT_4_LZ; break; case PGTYPES_FMTDATE_YEAR_DIGITS_SHORT: replace_val.uint_val = tm.tm_year % 100; replace_type = PGTYPES_TYPE_UINT_2_LZ; break; default: /* * should not happen, set something anyway */ replace_val.str_val = " "; replace_type = PGTYPES_TYPE_STRING_CONSTANT; } switch (replace_type) { case PGTYPES_TYPE_STRING_MALLOCED: case PGTYPES_TYPE_STRING_CONSTANT: strncpy(start_pattern, replace_val.str_val, strlen(replace_val.str_val)); if (replace_type == PGTYPES_TYPE_STRING_MALLOCED) free(replace_val.str_val); break; case PGTYPES_TYPE_UINT: { char *t = pgtypes_alloc(PGTYPES_DATE_NUM_MAX_DIGITS); if (!t) return -1; snprintf(t, PGTYPES_DATE_NUM_MAX_DIGITS, "%u", replace_val.uint_val); strncpy(start_pattern, t, strlen(t)); free(t); } break; case PGTYPES_TYPE_UINT_2_LZ: { char *t = pgtypes_alloc(PGTYPES_DATE_NUM_MAX_DIGITS); if (!t) return -1; snprintf(t, PGTYPES_DATE_NUM_MAX_DIGITS, "%02u", replace_val.uint_val); strncpy(start_pattern, t, strlen(t)); free(t); } break; case PGTYPES_TYPE_UINT_4_LZ: { char *t = pgtypes_alloc(PGTYPES_DATE_NUM_MAX_DIGITS); if (!t) return -1; snprintf(t, PGTYPES_DATE_NUM_MAX_DIGITS, "%04u", replace_val.uint_val); strncpy(start_pattern, t, strlen(t)); free(t); } break; default: /* * doesn't happen (we set replace_type to * PGTYPES_TYPE_STRING_CONSTANT in case of an error above) */ break; } } } return 0; } /* * PGTYPESdate_defmt_asc * * function works as follows: * - first we analyze the paramters * - if this is a special case with no delimiters, add delimters * - find the tokens. First we look for numerical values. If we have found * less than 3 tokens, we check for the months' names and thereafter for * the abbreviations of the months' names. * - then we see which parameter should be the date, the month and the * year and from these values we calculate the date */ #define PGTYPES_DATE_MONTH_MAXLENGTH 20 /* probably even less :-) */ int PGTYPESdate_defmt_asc(date * d, const char *fmt, char *str) { /* * token[2] = { 4,6 } means that token 2 starts at position 4 and ends at * (including) position 6 */ int token[3][2]; int token_values[3] = {-1, -1, -1}; char *fmt_token_order; char *fmt_ystart, *fmt_mstart, *fmt_dstart; unsigned int i; int reading_digit; int token_count; char *str_copy; struct tm tm; tm.tm_year = tm.tm_mon = tm.tm_mday = 0; /* keep compiler quiet */ if (!d || !str || !fmt) { errno = PGTYPES_DATE_ERR_EARGS; return -1; } /* analyze the fmt string */ fmt_ystart = strstr(fmt, "yy"); fmt_mstart = strstr(fmt, "mm"); fmt_dstart = strstr(fmt, "dd"); if (!fmt_ystart || !fmt_mstart || !fmt_dstart) { errno = PGTYPES_DATE_ERR_EARGS; return -1; } if (fmt_ystart < fmt_mstart) { /* y m */ if (fmt_dstart < fmt_ystart) { /* d y m */ fmt_token_order = "dym"; } else if (fmt_dstart > fmt_mstart) { /* y m d */ fmt_token_order = "ymd"; } else { /* y d m */ fmt_token_order = "ydm"; } } else { /* fmt_ystart > fmt_mstart */ /* m y */ if (fmt_dstart < fmt_mstart) { /* d m y */ fmt_token_order = "dmy"; } else if (fmt_dstart > fmt_ystart) { /* m y d */ fmt_token_order = "myd"; } else { /* m d y */ fmt_token_order = "mdy"; } } /* * handle the special cases where there is no delimiter between the * digits. If we see this: * * only digits, 6 or 8 bytes then it might be ddmmyy and ddmmyyyy (or * similar) * * we reduce it to a string with delimiters and continue processing */ /* check if we have only digits */ reading_digit = 1; for (i = 0; str[i]; i++) { if (!isdigit((unsigned char) str[i])) { reading_digit = 0; break; } } if (reading_digit) { int frag_length[3]; int target_pos; i = strlen(str); if (i != 8 && i != 6) { errno = PGTYPES_DATE_ERR_ENOSHORTDATE; return -1; } /* okay, this really is the special case */ /* * as long as the string, one additional byte for the terminator and 2 * for the delimiters between the 3 fiedls */ str_copy = pgtypes_alloc(strlen(str) + 1 + 2); if (!str_copy) return -1; /* determine length of the fragments */ if (i == 6) { frag_length[0] = 2; frag_length[1] = 2; frag_length[2] = 2; } else { if (fmt_token_order[0] == 'y') { frag_length[0] = 4; frag_length[1] = 2; frag_length[2] = 2; } else if (fmt_token_order[1] == 'y') { frag_length[0] = 2; frag_length[1] = 4; frag_length[2] = 2; } else { frag_length[0] = 2; frag_length[1] = 2; frag_length[2] = 4; } } target_pos = 0; /* * XXX: Here we could calculate the positions of the tokens and save * the for loop down there where we again check with isdigit() for * digits. */ for (i = 0; i < 3; i++) { int start_pos = 0; if (i >= 1) start_pos += frag_length[0]; if (i == 2) start_pos += frag_length[1]; strncpy(str_copy + target_pos, str + start_pos, frag_length[i]); target_pos += frag_length[i]; if (i != 2) { str_copy[target_pos] = ' '; target_pos++; } } str_copy[target_pos] = '\0'; } else { str_copy = pgtypes_strdup(str); if (!str_copy) return -1; /* convert the whole string to lower case */ for (i = 0; str_copy[i]; i++) str_copy[i] = (char) pg_tolower((unsigned char) str_copy[i]); } /* look for numerical tokens */ reading_digit = 0; token_count = 0; for (i = 0; i < strlen(str_copy); i++) { if (!isdigit((unsigned char) str_copy[i]) && reading_digit) { /* the token is finished */ token[token_count][1] = i - 1; reading_digit = 0; token_count++; } else if (isdigit((unsigned char) str_copy[i]) && !reading_digit) { /* we have found a token */ token[token_count][0] = i; reading_digit = 1; } } /* * we're at the end of the input string, but maybe we are still reading a * number... */ if (reading_digit) { token[token_count][1] = i - 1; token_count++; } if (token_count < 2) { /* * not all tokens found, no way to find 2 missing tokens with string * matches */ free(str_copy); errno = PGTYPES_DATE_ERR_ENOSHORTDATE; return -1; } if (token_count != 3) { /* * not all tokens found but we may find another one with string * matches by testing for the months names and months abbreviations */ char *month_lower_tmp = pgtypes_alloc(PGTYPES_DATE_MONTH_MAXLENGTH); char *start_pos; int j; int offset; int found = 0; char **list; if (!month_lower_tmp) { /* free variables we alloc'ed before */ free(str_copy); return -1; } list = pgtypes_date_months; for (i = 0; list[i]; i++) { for (j = 0; j < PGTYPES_DATE_MONTH_MAXLENGTH; j++) { month_lower_tmp[j] = (char) pg_tolower((unsigned char) list[i][j]); if (!month_lower_tmp[j]) { /* properly terminated */ break; } } if ((start_pos = strstr(str_copy, month_lower_tmp))) { offset = start_pos - str_copy; /* * sort the new token into the numeric tokens, shift them if * necessary */ if (offset < token[0][0]) { token[2][0] = token[1][0]; token[2][1] = token[1][1]; token[1][0] = token[0][0]; token[1][1] = token[0][1]; token_count = 0; } else if (offset < token[1][0]) { token[2][0] = token[1][0]; token[2][1] = token[1][1]; token_count = 1; } else token_count = 2; token[token_count][0] = offset; token[token_count][1] = offset + strlen(month_lower_tmp) - 1; /* * the value is the index of the month in the array of months * + 1 (January is month 0) */ token_values[token_count] = i + 1; found = 1; break; } /* * evil[tm] hack: if we read the pgtypes_date_months and haven't * found a match, reset list to point to pgtypes_date_months_short * and reset the counter variable i */ if (list == pgtypes_date_months) { if (list[i + 1] == NULL) { list = months; i = -1; } } } if (!found) { free(month_lower_tmp); free(str_copy); errno = PGTYPES_DATE_ERR_ENOTDMY; return -1; } /* * here we found a month. token[token_count] and * token_values[token_count] reflect the month's details. * * only the month can be specified with a literal. Here we can do a * quick check if the month is at the right position according to the * format string because we can check if the token that we expect to * be the month is at the position of the only token that already has * a value. If we wouldn't check here we could say "December 4 1990" * with a fmt string of "dd mm yy" for 12 April 1990. */ if (fmt_token_order[token_count] != 'm') { /* deal with the error later on */ token_values[token_count] = -1; } free(month_lower_tmp); } /* terminate the tokens with ASCII-0 and get their values */ for (i = 0; i < 3; i++) { *(str_copy + token[i][1] + 1) = '\0'; /* A month already has a value set, check for token_value == -1 */ if (token_values[i] == -1) { errno = 0; token_values[i] = strtol(str_copy + token[i][0], (char **) NULL, 10); /* strtol sets errno in case of an error */ if (errno) token_values[i] = -1; } if (fmt_token_order[i] == 'd') tm.tm_mday = token_values[i]; else if (fmt_token_order[i] == 'm') tm.tm_mon = token_values[i]; else if (fmt_token_order[i] == 'y') tm.tm_year = token_values[i]; } free(str_copy); if (tm.tm_mday < 1 || tm.tm_mday > 31) { errno = PGTYPES_DATE_BAD_DAY; return -1; } if (tm.tm_mon < 1 || tm.tm_mon > MONTHS_PER_YEAR) { errno = PGTYPES_DATE_BAD_MONTH; return -1; } if (tm.tm_mday == 31 && (tm.tm_mon == 4 || tm.tm_mon == 6 || tm.tm_mon == 9 || tm.tm_mon == 11)) { errno = PGTYPES_DATE_BAD_DAY; return -1; } if (tm.tm_mon == 2 && tm.tm_mday > 29) { errno = PGTYPES_DATE_BAD_DAY; return -1; } *d = date2j(tm.tm_year, tm.tm_mon, tm.tm_mday) - date2j(2000, 1, 1); return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2019_1
crossvul-cpp_data_bad_4779_3
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS IIIII X X EEEEE L % % SS I X X E L % % SSS I X EEE L % % SS I X X E L % % SSSSS IIIII X X EEEEE LLLLL % % % % % % Read/Write DEC SIXEL Format % % % % Software Design % % Hayaki Saito % % September 2014 % % Based on kmiya's sixel (2014-03-28) % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/quantum-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/splay-tree.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/module.h" #include "magick/threshold.h" #include "magick/utility.h" /* Definitions */ #define SIXEL_PALETTE_MAX 256 #define SIXEL_OUTPUT_PACKET_SIZE 1024 /* Macros */ #define SIXEL_RGB(r, g, b) (((r) << 16) + ((g) << 8) + (b)) #define SIXEL_PALVAL(n,a,m) (((n) * (a) + ((m) / 2)) / (m)) #define SIXEL_XRGB(r,g,b) SIXEL_RGB(SIXEL_PALVAL(r, 255, 100), SIXEL_PALVAL(g, 255, 100), SIXEL_PALVAL(b, 255, 100)) /* Structure declarations. */ typedef struct sixel_node { struct sixel_node *next; int color; int left; int right; unsigned char *map; } sixel_node_t; typedef struct sixel_output { /* compatiblity flags */ /* 0: 7bit terminal, * 1: 8bit terminal */ unsigned char has_8bit_control; int save_pixel; int save_count; int active_palette; sixel_node_t *node_top; sixel_node_t *node_free; Image *image; int pos; unsigned char buffer[1]; } sixel_output_t; static int const sixel_default_color_table[] = { SIXEL_XRGB(0, 0, 0), /* 0 Black */ SIXEL_XRGB(20, 20, 80), /* 1 Blue */ SIXEL_XRGB(80, 13, 13), /* 2 Red */ SIXEL_XRGB(20, 80, 20), /* 3 Green */ SIXEL_XRGB(80, 20, 80), /* 4 Magenta */ SIXEL_XRGB(20, 80, 80), /* 5 Cyan */ SIXEL_XRGB(80, 80, 20), /* 6 Yellow */ SIXEL_XRGB(53, 53, 53), /* 7 Gray 50% */ SIXEL_XRGB(26, 26, 26), /* 8 Gray 25% */ SIXEL_XRGB(33, 33, 60), /* 9 Blue* */ SIXEL_XRGB(60, 26, 26), /* 10 Red* */ SIXEL_XRGB(33, 60, 33), /* 11 Green* */ SIXEL_XRGB(60, 33, 60), /* 12 Magenta* */ SIXEL_XRGB(33, 60, 60), /* 13 Cyan* */ SIXEL_XRGB(60, 60, 33), /* 14 Yellow* */ SIXEL_XRGB(80, 80, 80), /* 15 Gray 75% */ }; /* Forward declarations. */ static MagickBooleanType WriteSIXELImage(const ImageInfo *,Image *); static int hue_to_rgb(int n1, int n2, int hue) { const int HLSMAX = 100; if (hue < 0) { hue += HLSMAX; } if (hue > HLSMAX) { hue -= HLSMAX; } if (hue < (HLSMAX / 6)) { return (n1 + (((n2 - n1) * hue + (HLSMAX / 12)) / (HLSMAX / 6))); } if (hue < (HLSMAX / 2)) { return (n2); } if (hue < ((HLSMAX * 2) / 3)) { return (n1 + (((n2 - n1) * (((HLSMAX * 2) / 3) - hue) + (HLSMAX / 12))/(HLSMAX / 6))); } return (n1); } static int hls_to_rgb(int hue, int lum, int sat) { int R, G, B; int Magic1, Magic2; const int RGBMAX = 255; const int HLSMAX = 100; if (sat == 0) { R = G = B = (lum * RGBMAX) / HLSMAX; } else { if (lum <= (HLSMAX / 2)) { Magic2 = (lum * (HLSMAX + sat) + (HLSMAX / 2)) / HLSMAX; } else { Magic2 = lum + sat - ((lum * sat) + (HLSMAX / 2)) / HLSMAX; } Magic1 = 2 * lum - Magic2; R = (hue_to_rgb(Magic1, Magic2, hue + (HLSMAX / 3)) * RGBMAX + (HLSMAX / 2)) / HLSMAX; G = (hue_to_rgb(Magic1, Magic2, hue) * RGBMAX + (HLSMAX / 2)) / HLSMAX; B = (hue_to_rgb(Magic1, Magic2, hue - (HLSMAX / 3)) * RGBMAX + (HLSMAX/2)) / HLSMAX; } return SIXEL_RGB(R, G, B); } static unsigned char *get_params(unsigned char *p, int *param, int *len) { int n; *len = 0; while (*p != '\0') { while (*p == ' ' || *p == '\t') { p++; } if (isdigit(*p)) { for (n = 0; isdigit(*p); p++) { n = n * 10 + (*p - '0'); } if (*len < 10) { param[(*len)++] = n; } while (*p == ' ' || *p == '\t') { p++; } if (*p == ';') { p++; } } else if (*p == ';') { if (*len < 10) { param[(*len)++] = 0; } p++; } else break; } return p; } /* convert sixel data into indexed pixel bytes and palette data */ MagickBooleanType sixel_decode(unsigned char /* in */ *p, /* sixel bytes */ unsigned char /* out */ **pixels, /* decoded pixels */ size_t /* out */ *pwidth, /* image width */ size_t /* out */ *pheight, /* image height */ unsigned char /* out */ **palette, /* ARGB palette */ size_t /* out */ *ncolors /* palette size (<= 256) */) { int n, i, r, g, b, sixel_vertical_mask, c; int posision_x, posision_y; int max_x, max_y; int attributed_pan, attributed_pad; int attributed_ph, attributed_pv; int repeat_count, color_index, max_color_index = 2, background_color_index; int param[10]; int sixel_palet[SIXEL_PALETTE_MAX]; unsigned char *imbuf, *dmbuf; int imsx, imsy; int dmsx, dmsy; int y; posision_x = posision_y = 0; max_x = max_y = 0; attributed_pan = 2; attributed_pad = 1; attributed_ph = attributed_pv = 0; repeat_count = 1; color_index = 0; background_color_index = 0; imsx = 2048; imsy = 2048; imbuf = (unsigned char *) AcquireQuantumMemory(imsx * imsy,1); if (imbuf == NULL) { return(MagickFalse); } for (n = 0; n < 16; n++) { sixel_palet[n] = sixel_default_color_table[n]; } /* colors 16-231 are a 6x6x6 color cube */ for (r = 0; r < 6; r++) { for (g = 0; g < 6; g++) { for (b = 0; b < 6; b++) { sixel_palet[n++] = SIXEL_RGB(r * 51, g * 51, b * 51); } } } /* colors 232-255 are a grayscale ramp, intentionally leaving out */ for (i = 0; i < 24; i++) { sixel_palet[n++] = SIXEL_RGB(i * 11, i * 11, i * 11); } for (; n < SIXEL_PALETTE_MAX; n++) { sixel_palet[n] = SIXEL_RGB(255, 255, 255); } (void) ResetMagickMemory(imbuf, background_color_index, imsx * imsy); while (*p != '\0') { if ((p[0] == '\033' && p[1] == 'P') || *p == 0x90) { if (*p == '\033') { p++; } p = get_params(++p, param, &n); if (*p == 'q') { p++; if (n > 0) { /* Pn1 */ switch(param[0]) { case 0: case 1: attributed_pad = 2; break; case 2: attributed_pad = 5; break; case 3: attributed_pad = 4; break; case 4: attributed_pad = 4; break; case 5: attributed_pad = 3; break; case 6: attributed_pad = 3; break; case 7: attributed_pad = 2; break; case 8: attributed_pad = 2; break; case 9: attributed_pad = 1; break; } } if (n > 2) { /* Pn3 */ if (param[2] == 0) { param[2] = 10; } attributed_pan = attributed_pan * param[2] / 10; attributed_pad = attributed_pad * param[2] / 10; if (attributed_pan <= 0) attributed_pan = 1; if (attributed_pad <= 0) attributed_pad = 1; } } } else if ((p[0] == '\033' && p[1] == '\\') || *p == 0x9C) { break; } else if (*p == '"') { /* DECGRA Set Raster Attributes " Pan; Pad; Ph; Pv */ p = get_params(++p, param, &n); if (n > 0) attributed_pad = param[0]; if (n > 1) attributed_pan = param[1]; if (n > 2 && param[2] > 0) attributed_ph = param[2]; if (n > 3 && param[3] > 0) attributed_pv = param[3]; if (attributed_pan <= 0) attributed_pan = 1; if (attributed_pad <= 0) attributed_pad = 1; if (imsx < attributed_ph || imsy < attributed_pv) { dmsx = imsx > attributed_ph ? imsx : attributed_ph; dmsy = imsy > attributed_pv ? imsy : attributed_pv; dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx * dmsy,1); if (dmbuf == (unsigned char *) NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } (void) ResetMagickMemory(dmbuf, background_color_index, dmsx * dmsy); for (y = 0; y < imsy; ++y) { (void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, imsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } } else if (*p == '!') { /* DECGRI Graphics Repeat Introducer ! Pn Ch */ p = get_params(++p, param, &n); if (n > 0) { repeat_count = param[0]; } } else if (*p == '#') { /* DECGCI Graphics Color Introducer # Pc; Pu; Px; Py; Pz */ p = get_params(++p, param, &n); if (n > 0) { if ((color_index = param[0]) < 0) { color_index = 0; } else if (color_index >= SIXEL_PALETTE_MAX) { color_index = SIXEL_PALETTE_MAX - 1; } } if (n > 4) { if (param[1] == 1) { /* HLS */ if (param[2] > 360) param[2] = 360; if (param[3] > 100) param[3] = 100; if (param[4] > 100) param[4] = 100; sixel_palet[color_index] = hls_to_rgb(param[2] * 100 / 360, param[3], param[4]); } else if (param[1] == 2) { /* RGB */ if (param[2] > 100) param[2] = 100; if (param[3] > 100) param[3] = 100; if (param[4] > 100) param[4] = 100; sixel_palet[color_index] = SIXEL_XRGB(param[2], param[3], param[4]); } } } else if (*p == '$') { /* DECGCR Graphics Carriage Return */ p++; posision_x = 0; repeat_count = 1; } else if (*p == '-') { /* DECGNL Graphics Next Line */ p++; posision_x = 0; posision_y += 6; repeat_count = 1; } else if (*p >= '?' && *p <= '\177') { if (imsx < (posision_x + repeat_count) || imsy < (posision_y + 6)) { int nx = imsx * 2; int ny = imsy * 2; while (nx < (posision_x + repeat_count) || ny < (posision_y + 6)) { nx *= 2; ny *= 2; } dmsx = nx; dmsy = ny; dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx * dmsy,1); if (dmbuf == (unsigned char *) NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } (void) ResetMagickMemory(dmbuf, background_color_index, dmsx * dmsy); for (y = 0; y < imsy; ++y) { (void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, imsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } if (color_index > max_color_index) { max_color_index = color_index; } if ((b = *(p++) - '?') == 0) { posision_x += repeat_count; } else { sixel_vertical_mask = 0x01; if (repeat_count <= 1) { for (i = 0; i < 6; i++) { if ((b & sixel_vertical_mask) != 0) { imbuf[imsx * (posision_y + i) + posision_x] = color_index; if (max_x < posision_x) { max_x = posision_x; } if (max_y < (posision_y + i)) { max_y = posision_y + i; } } sixel_vertical_mask <<= 1; } posision_x += 1; } else { /* repeat_count > 1 */ for (i = 0; i < 6; i++) { if ((b & sixel_vertical_mask) != 0) { c = sixel_vertical_mask << 1; for (n = 1; (i + n) < 6; n++) { if ((b & c) == 0) { break; } c <<= 1; } for (y = posision_y + i; y < posision_y + i + n; ++y) { (void) ResetMagickMemory(imbuf + imsx * y + posision_x, color_index, repeat_count); } if (max_x < (posision_x + repeat_count - 1)) { max_x = posision_x + repeat_count - 1; } if (max_y < (posision_y + i + n - 1)) { max_y = posision_y + i + n - 1; } i += (n - 1); sixel_vertical_mask <<= (n - 1); } sixel_vertical_mask <<= 1; } posision_x += repeat_count; } } repeat_count = 1; } else { p++; } } if (++max_x < attributed_ph) { max_x = attributed_ph; } if (++max_y < attributed_pv) { max_y = attributed_pv; } if (imsx > max_x || imsy > max_y) { dmsx = max_x; dmsy = max_y; if ((dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx * dmsy,1)) == NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } for (y = 0; y < dmsy; ++y) { (void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, dmsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } *pixels = imbuf; *pwidth = imsx; *pheight = imsy; *ncolors = max_color_index + 1; *palette = (unsigned char *) AcquireQuantumMemory(*ncolors,4); for (n = 0; n < (ssize_t) *ncolors; ++n) { (*palette)[n * 4 + 0] = sixel_palet[n] >> 16 & 0xff; (*palette)[n * 4 + 1] = sixel_palet[n] >> 8 & 0xff; (*palette)[n * 4 + 2] = sixel_palet[n] & 0xff; (*palette)[n * 4 + 3] = 0xff; } return(MagickTrue); } sixel_output_t *sixel_output_create(Image *image) { sixel_output_t *output; output = (sixel_output_t *) AcquireQuantumMemory(sizeof(sixel_output_t) + SIXEL_OUTPUT_PACKET_SIZE * 2, 1); output->has_8bit_control = 0; output->save_pixel = 0; output->save_count = 0; output->active_palette = (-1); output->node_top = NULL; output->node_free = NULL; output->image = image; output->pos = 0; return output; } static void sixel_advance(sixel_output_t *context, int nwrite) { if ((context->pos += nwrite) >= SIXEL_OUTPUT_PACKET_SIZE) { WriteBlob(context->image,SIXEL_OUTPUT_PACKET_SIZE,context->buffer); CopyMagickMemory(context->buffer, context->buffer + SIXEL_OUTPUT_PACKET_SIZE, (context->pos -= SIXEL_OUTPUT_PACKET_SIZE)); } } static int sixel_put_flash(sixel_output_t *const context) { int n; int nwrite; #if defined(USE_VT240) /* VT240 Max 255 ? */ while (context->save_count > 255) { nwrite = spritf((char *)context->buffer + context->pos, "!255%c", context->save_pixel); if (nwrite <= 0) { return (-1); } sixel_advance(context, nwrite); context->save_count -= 255; } #endif /* defined(USE_VT240) */ if (context->save_count > 3) { /* DECGRI Graphics Repeat Introducer ! Pn Ch */ nwrite = sprintf((char *)context->buffer + context->pos, "!%d%c", context->save_count, context->save_pixel); if (nwrite <= 0) { return (-1); } sixel_advance(context, nwrite); } else { for (n = 0; n < context->save_count; n++) { context->buffer[context->pos] = (char)context->save_pixel; sixel_advance(context, 1); } } context->save_pixel = 0; context->save_count = 0; return 0; } static void sixel_put_pixel(sixel_output_t *const context, int pix) { if (pix < 0 || pix > '?') { pix = 0; } pix += '?'; if (pix == context->save_pixel) { context->save_count++; } else { sixel_put_flash(context); context->save_pixel = pix; context->save_count = 1; } } static void sixel_node_del(sixel_output_t *const context, sixel_node_t *np) { sixel_node_t *tp; if ((tp = context->node_top) == np) { context->node_top = np->next; } else { while (tp->next != NULL) { if (tp->next == np) { tp->next = np->next; break; } tp = tp->next; } } np->next = context->node_free; context->node_free = np; } static int sixel_put_node(sixel_output_t *const context, int x, sixel_node_t *np, int ncolors, int keycolor) { int nwrite; if (ncolors != 2 || keycolor == -1) { /* designate palette index */ if (context->active_palette != np->color) { nwrite = sprintf((char *)context->buffer + context->pos, "#%d", np->color); sixel_advance(context, nwrite); context->active_palette = np->color; } } for (; x < np->left; x++) { sixel_put_pixel(context, 0); } for (; x < np->right; x++) { sixel_put_pixel(context, np->map[x]); } sixel_put_flash(context); return x; } static MagickBooleanType sixel_encode_impl(unsigned char *pixels, size_t width,size_t height, unsigned char *palette, size_t ncolors, int keycolor, sixel_output_t *context) { #define RelinquishNodesAndMap \ while ((np = context->node_free) != NULL) { \ context->node_free = np->next; \ np=(sixel_node_t *) RelinquishMagickMemory(np); \ } \ map = (unsigned char *) RelinquishMagickMemory(map) int x, y, i, n, c; int left, right; int pix; size_t len; unsigned char *map; sixel_node_t *np, *tp, top; int nwrite; context->pos = 0; if (ncolors < 1) { return (MagickFalse); } len = ncolors * width; context->active_palette = (-1); if ((map = (unsigned char *)AcquireQuantumMemory(len, sizeof(unsigned char))) == NULL) { return (MagickFalse); } (void) ResetMagickMemory(map, 0, len); if (context->has_8bit_control) { nwrite = sprintf((char *)context->buffer, "\x90" "0;0;0" "q"); } else { nwrite = sprintf((char *)context->buffer, "\x1bP" "0;0;0" "q"); } if (nwrite <= 0) { return (MagickFalse); } sixel_advance(context, nwrite); nwrite = sprintf((char *)context->buffer + context->pos, "\"1;1;%d;%d", (int) width, (int) height); if (nwrite <= 0) { RelinquishNodesAndMap; return (MagickFalse); } sixel_advance(context, nwrite); if (ncolors != 2 || keycolor == -1) { for (n = 0; n < (ssize_t) ncolors; n++) { /* DECGCI Graphics Color Introducer # Pc ; Pu; Px; Py; Pz */ nwrite = sprintf((char *)context->buffer + context->pos, "#%d;2;%d;%d;%d", n, (palette[n * 3 + 0] * 100 + 127) / 255, (palette[n * 3 + 1] * 100 + 127) / 255, (palette[n * 3 + 2] * 100 + 127) / 255); if (nwrite <= 0) { RelinquishNodesAndMap; return (MagickFalse); } sixel_advance(context, nwrite); if (nwrite <= 0) { RelinquishNodesAndMap; return (MagickFalse); } } } for (y = i = 0; y < (ssize_t) height; y++) { for (x = 0; x < (ssize_t) width; x++) { pix = pixels[y * width + x]; if (pix >= 0 && pix < (ssize_t) ncolors && pix != keycolor) { map[pix * width + x] |= (1 << i); } } if (++i < 6 && (y + 1) < (ssize_t) height) { continue; } for (c = 0; c < (ssize_t) ncolors; c++) { for (left = 0; left < (ssize_t) width; left++) { if (*(map + c * width + left) == 0) { continue; } for (right = left + 1; right < (ssize_t) width; right++) { if (*(map + c * width + right) != 0) { continue; } for (n = 1; (right + n) < (ssize_t) width; n++) { if (*(map + c * width + right + n) != 0) { break; } } if (n >= 10 || right + n >= (ssize_t) width) { break; } right = right + n - 1; } if ((np = context->node_free) != NULL) { context->node_free = np->next; } else if ((np = (sixel_node_t *)AcquireMagickMemory(sizeof(sixel_node_t))) == NULL) { RelinquishNodesAndMap; return (MagickFalse); } np->color = c; np->left = left; np->right = right; np->map = map + c * width; top.next = context->node_top; tp = &top; while (tp->next != NULL) { if (np->left < tp->next->left) { break; } if (np->left == tp->next->left && np->right > tp->next->right) { break; } tp = tp->next; } np->next = tp->next; tp->next = np; context->node_top = top.next; left = right - 1; } } for (x = 0; (np = context->node_top) != NULL;) { if (x > np->left) { /* DECGCR Graphics Carriage Return */ context->buffer[context->pos] = '$'; sixel_advance(context, 1); x = 0; } x = sixel_put_node(context, x, np, (int) ncolors, keycolor); sixel_node_del(context, np); np = context->node_top; while (np != NULL) { if (np->left < x) { np = np->next; continue; } x = sixel_put_node(context, x, np, (int) ncolors, keycolor); sixel_node_del(context, np); np = context->node_top; } } /* DECGNL Graphics Next Line */ context->buffer[context->pos] = '-'; sixel_advance(context, 1); if (nwrite <= 0) { RelinquishNodesAndMap; return (MagickFalse); } i = 0; (void) ResetMagickMemory(map, 0, len); } if (context->has_8bit_control) { context->buffer[context->pos] = 0x9c; sixel_advance(context, 1); } else { context->buffer[context->pos] = 0x1b; context->buffer[context->pos + 1] = '\\'; sixel_advance(context, 2); } if (nwrite <= 0) { RelinquishNodesAndMap; return (MagickFalse); } /* flush buffer */ if (context->pos > 0) { (void) WriteBlob(context->image,context->pos,context->buffer); } RelinquishNodesAndMap; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s S I X E L % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsSIXEL() returns MagickTrue if the image format type, identified by the % magick string, is SIXEL. % % The format of the IsSIXEL method is: % % MagickBooleanType IsSIXEL(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. or % blob. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsSIXEL(const unsigned char *magick,const size_t length) { const unsigned char *end = magick + length; if (length < 3) return(MagickFalse); if (*magick == 0x90 || (*magick == 0x1b && *++magick == 'P')) { while (++magick != end) { if (*magick == 'q') return(MagickTrue); if (!(*magick >= '0' && *magick <= '9') && *magick != ';') return(MagickFalse); } } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d S I X E L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadSIXELImage() reads an X11 pixmap image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadSIXELImage method is: % % Image *ReadSIXELImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadSIXELImage(const ImageInfo *image_info,ExceptionInfo *exception) { char *sixel_buffer; Image *image; MagickBooleanType status; register char *p; register IndexPacket *indexes; register ssize_t x; register PixelPacket *r; size_t length; ssize_t i, j, y; unsigned char *sixel_pixels, *sixel_palette; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SIXEL file. */ length=MaxTextExtent; sixel_buffer=(char *) AcquireQuantumMemory((size_t) length,sizeof(*sixel_buffer)); p=sixel_buffer; if (sixel_buffer != (char *) NULL) while (ReadBlobString(image,p) != (char *) NULL) { if ((*p == '#') && ((p == sixel_buffer) || (*(p-1) == '\n'))) continue; if ((*p == '}') && (*(p+1) == ';')) break; p+=strlen(p); if ((size_t) (p-sixel_buffer+MaxTextExtent) < length) continue; length<<=1; sixel_buffer=(char *) ResizeQuantumMemory(sixel_buffer,length+MaxTextExtent, sizeof(*sixel_buffer)); if (sixel_buffer == (char *) NULL) break; p=sixel_buffer+strlen(sixel_buffer); } if (sixel_buffer == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Decode SIXEL */ if (sixel_decode((unsigned char *)sixel_buffer, &sixel_pixels, &image->columns, &image->rows, &sixel_palette, &image->colors) == MagickFalse) { sixel_buffer=(char *) RelinquishMagickMemory(sixel_buffer); ThrowReaderException(CorruptImageError,"CorruptImage"); } sixel_buffer=(char *) RelinquishMagickMemory(sixel_buffer); image->depth=24; image->storage_class=PseudoClass; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (AcquireImageColormap(image,image->colors) == MagickFalse) { sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i = 0; i < (ssize_t) image->colors; ++i) { image->colormap[i].red = ScaleCharToQuantum(sixel_palette[i * 4 + 0]); image->colormap[i].green = ScaleCharToQuantum(sixel_palette[i * 4 + 1]); image->colormap[i].blue = ScaleCharToQuantum(sixel_palette[i * 4 + 2]); } j=0; if (image_info->ping == MagickFalse) { /* Read image pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { r=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { j=(ssize_t) sixel_pixels[y * image->columns + x]; SetPixelIndex(indexes+x,j); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (y < (ssize_t) image->rows) { sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette); ThrowReaderException(CorruptImageError,"NotEnoughPixelData"); } } /* Relinquish resources. */ sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r S I X E L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterSIXELImage() adds attributes for the SIXEL image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterSIXELImage method is: % % size_t RegisterSIXELImage(void) % */ ModuleExport size_t RegisterSIXELImage(void) { MagickInfo *entry; entry=SetMagickInfo("SIXEL"); entry->decoder=(DecodeImageHandler *) ReadSIXELImage; entry->encoder=(EncodeImageHandler *) WriteSIXELImage; entry->magick=(IsImageFormatHandler *) IsSIXEL; entry->adjoin=MagickFalse; entry->description=ConstantString("DEC SIXEL Graphics Format"); entry->module=ConstantString("SIXEL"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("SIX"); entry->decoder=(DecodeImageHandler *) ReadSIXELImage; entry->encoder=(EncodeImageHandler *) WriteSIXELImage; entry->magick=(IsImageFormatHandler *) IsSIXEL; entry->adjoin=MagickFalse; entry->description=ConstantString("DEC SIXEL Graphics Format"); entry->module=ConstantString("SIX"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r S I X E L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterSIXELImage() removes format registrations made by the % SIXEL module from the list of supported formats. % % The format of the UnregisterSIXELImage method is: % % UnregisterSIXELImage(void) % */ ModuleExport void UnregisterSIXELImage(void) { (void) UnregisterMagickInfo("SIXEL"); (void) UnregisterMagickInfo("SIX"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e S I X E L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteSIXELImage() writes an image to a file in the X pixmap format. % % The format of the WriteSIXELImage method is: % % MagickBooleanType WriteSIXELImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteSIXELImage(const ImageInfo *image_info,Image *image) { ExceptionInfo *exception; MagickBooleanType status; register const IndexPacket *indexes; register ssize_t i, x; ssize_t opacity, y; sixel_output_t *output; unsigned char sixel_palette[256 * 3], *sixel_pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=(&image->exception); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); opacity=(-1); if (image->matte == MagickFalse) { if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) SetImageType(image,PaletteType); } else { MagickRealType alpha, beta; /* Identify transparent colormap index. */ if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) SetImageType(image,PaletteBilevelMatteType); for (i=0; i < (ssize_t) image->colors; i++) if (image->colormap[i].opacity != OpaqueOpacity) { if (opacity < 0) { opacity=i; continue; } alpha=(MagickRealType) image->colormap[i].opacity; beta=(MagickRealType) image->colormap[opacity].opacity; if (alpha > beta) opacity=i; } if (opacity == -1) { (void) SetImageType(image,PaletteBilevelMatteType); for (i=0; i < (ssize_t) image->colors; i++) if (image->colormap[i].opacity != OpaqueOpacity) { if (opacity < 0) { opacity=i; continue; } alpha=(MagickRealType) image->colormap[i].opacity; beta=(MagickRealType) image->colormap[opacity].opacity; if (alpha > beta) opacity=i; } } if (opacity >= 0) { image->colormap[opacity].red=image->transparent_color.red; image->colormap[opacity].green=image->transparent_color.green; image->colormap[opacity].blue=image->transparent_color.blue; } } /* SIXEL header. */ for (i=0; i < (ssize_t) image->colors; i++) { sixel_palette[i * 3 + 0] = ScaleQuantumToChar(image->colormap[i].red); sixel_palette[i * 3 + 1] = ScaleQuantumToChar(image->colormap[i].green); sixel_palette[i * 3 + 2] = ScaleQuantumToChar(image->colormap[i].blue); } /* Define SIXEL pixels. */ output = sixel_output_create(image); sixel_pixels =(unsigned char *) AcquireQuantumMemory(image->columns * image->rows,1); for (y=0; y < (ssize_t) image->rows; y++) { (void) GetVirtualPixels(image,0,y,image->columns,1,exception); indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) sixel_pixels[y * image->columns + x] = (unsigned char) ((ssize_t) GetPixelIndex(indexes + x)); } status = sixel_encode_impl(sixel_pixels, image->columns, image->rows, sixel_palette, image->colors, -1, output); sixel_pixels =(unsigned char *) RelinquishMagickMemory(sixel_pixels); output = (sixel_output_t *) RelinquishMagickMemory(output); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4779_3
crossvul-cpp_data_bad_3422_0
/* * CDXL video decoder * Copyright (c) 2011-2012 Paul B Mahol * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Commodore CDXL video decoder * @author Paul B Mahol */ #define UNCHECKED_BITSTREAM_READER 1 #include "libavutil/intreadwrite.h" #include "libavutil/imgutils.h" #include "avcodec.h" #include "bytestream.h" #include "get_bits.h" #include "internal.h" #define BIT_PLANAR 0x00 #define CHUNKY 0x20 #define BYTE_PLANAR 0x40 #define BIT_LINE 0x80 #define BYTE_LINE 0xC0 typedef struct CDXLVideoContext { AVCodecContext *avctx; int bpp; int format; int padded_bits; const uint8_t *palette; int palette_size; const uint8_t *video; int video_size; uint8_t *new_video; int new_video_size; } CDXLVideoContext; static av_cold int cdxl_decode_init(AVCodecContext *avctx) { CDXLVideoContext *c = avctx->priv_data; c->new_video_size = 0; c->avctx = avctx; return 0; } static void import_palette(CDXLVideoContext *c, uint32_t *new_palette) { int i; for (i = 0; i < c->palette_size / 2; i++) { unsigned rgb = AV_RB16(&c->palette[i * 2]); unsigned r = ((rgb >> 8) & 0xF) * 0x11; unsigned g = ((rgb >> 4) & 0xF) * 0x11; unsigned b = (rgb & 0xF) * 0x11; AV_WN32(&new_palette[i], (0xFFU << 24) | (r << 16) | (g << 8) | b); } } static void bitplanar2chunky(CDXLVideoContext *c, int linesize, uint8_t *out) { GetBitContext gb; int x, y, plane; if (init_get_bits8(&gb, c->video, c->video_size) < 0) return; for (plane = 0; plane < c->bpp; plane++) { for (y = 0; y < c->avctx->height; y++) { for (x = 0; x < c->avctx->width; x++) out[linesize * y + x] |= get_bits1(&gb) << plane; skip_bits(&gb, c->padded_bits); } } } static void bitline2chunky(CDXLVideoContext *c, int linesize, uint8_t *out) { GetBitContext gb; int x, y, plane; if (init_get_bits8(&gb, c->video, c->video_size) < 0) return; for (y = 0; y < c->avctx->height; y++) { for (plane = 0; plane < c->bpp; plane++) { for (x = 0; x < c->avctx->width; x++) out[linesize * y + x] |= get_bits1(&gb) << plane; skip_bits(&gb, c->padded_bits); } } } static void chunky2chunky(CDXLVideoContext *c, int linesize, uint8_t *out) { GetByteContext gb; int y; bytestream2_init(&gb, c->video, c->video_size); for (y = 0; y < c->avctx->height; y++) { bytestream2_get_buffer(&gb, out + linesize * y, c->avctx->width * 3); } } static void import_format(CDXLVideoContext *c, int linesize, uint8_t *out) { memset(out, 0, linesize * c->avctx->height); switch (c->format) { case BIT_PLANAR: bitplanar2chunky(c, linesize, out); break; case BIT_LINE: bitline2chunky(c, linesize, out); break; case CHUNKY: chunky2chunky(c, linesize, out); break; } } static void cdxl_decode_rgb(CDXLVideoContext *c, AVFrame *frame) { uint32_t *new_palette = (uint32_t *)frame->data[1]; memset(frame->data[1], 0, AVPALETTE_SIZE); import_palette(c, new_palette); import_format(c, frame->linesize[0], frame->data[0]); } static void cdxl_decode_raw(CDXLVideoContext *c, AVFrame *frame) { import_format(c, frame->linesize[0], frame->data[0]); } static void cdxl_decode_ham6(CDXLVideoContext *c, AVFrame *frame) { AVCodecContext *avctx = c->avctx; uint32_t new_palette[16], r, g, b; uint8_t *ptr, *out, index, op; int x, y; ptr = c->new_video; out = frame->data[0]; import_palette(c, new_palette); import_format(c, avctx->width, c->new_video); for (y = 0; y < avctx->height; y++) { r = new_palette[0] & 0xFF0000; g = new_palette[0] & 0xFF00; b = new_palette[0] & 0xFF; for (x = 0; x < avctx->width; x++) { index = *ptr++; op = index >> 4; index &= 15; switch (op) { case 0: r = new_palette[index] & 0xFF0000; g = new_palette[index] & 0xFF00; b = new_palette[index] & 0xFF; break; case 1: b = index * 0x11; break; case 2: r = index * 0x11 << 16; break; case 3: g = index * 0x11 << 8; break; } AV_WL24(out + x * 3, r | g | b); } out += frame->linesize[0]; } } static void cdxl_decode_ham8(CDXLVideoContext *c, AVFrame *frame) { AVCodecContext *avctx = c->avctx; uint32_t new_palette[64], r, g, b; uint8_t *ptr, *out, index, op; int x, y; ptr = c->new_video; out = frame->data[0]; import_palette(c, new_palette); import_format(c, avctx->width, c->new_video); for (y = 0; y < avctx->height; y++) { r = new_palette[0] & 0xFF0000; g = new_palette[0] & 0xFF00; b = new_palette[0] & 0xFF; for (x = 0; x < avctx->width; x++) { index = *ptr++; op = index >> 6; index &= 63; switch (op) { case 0: r = new_palette[index] & 0xFF0000; g = new_palette[index] & 0xFF00; b = new_palette[index] & 0xFF; break; case 1: b = (index << 2) | (b & 3); break; case 2: r = (index << 18) | (r & (3 << 16)); break; case 3: g = (index << 10) | (g & (3 << 8)); break; } AV_WL24(out + x * 3, r | g | b); } out += frame->linesize[0]; } } static int cdxl_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt) { CDXLVideoContext *c = avctx->priv_data; AVFrame * const p = data; int ret, w, h, encoding, aligned_width, buf_size = pkt->size; const uint8_t *buf = pkt->data; if (buf_size < 32) return AVERROR_INVALIDDATA; encoding = buf[1] & 7; c->format = buf[1] & 0xE0; w = AV_RB16(&buf[14]); h = AV_RB16(&buf[16]); c->bpp = buf[19]; c->palette_size = AV_RB16(&buf[20]); c->palette = buf + 32; c->video = c->palette + c->palette_size; c->video_size = buf_size - c->palette_size - 32; if (c->palette_size > 512) return AVERROR_INVALIDDATA; if (buf_size < c->palette_size + 32) return AVERROR_INVALIDDATA; if (c->bpp < 1) return AVERROR_INVALIDDATA; if (c->format != BIT_PLANAR && c->format != BIT_LINE && c->format != CHUNKY) { avpriv_request_sample(avctx, "Pixel format 0x%0x", c->format); return AVERROR_PATCHWELCOME; } if ((ret = ff_set_dimensions(avctx, w, h)) < 0) return ret; if (c->format == CHUNKY) aligned_width = avctx->width; else aligned_width = FFALIGN(c->avctx->width, 16); c->padded_bits = aligned_width - c->avctx->width; if (c->video_size < aligned_width * avctx->height * (int64_t)c->bpp / 8) return AVERROR_INVALIDDATA; if (!encoding && c->palette_size && c->bpp <= 8) { avctx->pix_fmt = AV_PIX_FMT_PAL8; } else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8)) { if (c->palette_size != (1 << (c->bpp - 1))) return AVERROR_INVALIDDATA; avctx->pix_fmt = AV_PIX_FMT_BGR24; } else if (!encoding && c->bpp == 24 && c->format == CHUNKY && !c->palette_size) { avctx->pix_fmt = AV_PIX_FMT_RGB24; } else { avpriv_request_sample(avctx, "Encoding %d, bpp %d and format 0x%x", encoding, c->bpp, c->format); return AVERROR_PATCHWELCOME; } if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; p->pict_type = AV_PICTURE_TYPE_I; if (encoding) { av_fast_padded_malloc(&c->new_video, &c->new_video_size, h * w + AV_INPUT_BUFFER_PADDING_SIZE); if (!c->new_video) return AVERROR(ENOMEM); if (c->bpp == 8) cdxl_decode_ham8(c, p); else cdxl_decode_ham6(c, p); } else if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { cdxl_decode_rgb(c, p); } else { cdxl_decode_raw(c, p); } *got_frame = 1; return buf_size; } static av_cold int cdxl_decode_end(AVCodecContext *avctx) { CDXLVideoContext *c = avctx->priv_data; av_freep(&c->new_video); return 0; } AVCodec ff_cdxl_decoder = { .name = "cdxl", .long_name = NULL_IF_CONFIG_SMALL("Commodore CDXL video"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_CDXL, .priv_data_size = sizeof(CDXLVideoContext), .init = cdxl_decode_init, .close = cdxl_decode_end, .decode = cdxl_decode_frame, .capabilities = AV_CODEC_CAP_DR1, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3422_0
crossvul-cpp_data_bad_159_1
/* * This file is part of Espruino, a JavaScript interpreter for Microcontrollers * * Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * ---------------------------------------------------------------------------- * Recursive descent parser for code execution * ---------------------------------------------------------------------------- */ #include "jsparse.h" #include "jsinteractive.h" #include "jswrapper.h" #include "jsnative.h" #include "jswrap_object.h" // for function_replacewith #include "jswrap_functions.h" // insane check for eval in jspeFunctionCall #include "jswrap_json.h" // for jsfPrintJSON #include "jswrap_espruino.h" // for jswrap_espruino_memoryArea #ifndef SAVE_ON_FLASH #include "jswrap_regexp.h" // for jswrap_regexp_constructor #endif /* Info about execution when Parsing - this saves passing it on the stack * for each call */ JsExecInfo execInfo; // ----------------------------------------------- Forward decls JsVar *jspeAssignmentExpression(); JsVar *jspeExpression(); JsVar *jspeUnaryExpression(); void jspeBlock(); void jspeBlockNoBrackets(); JsVar *jspeStatement(); JsVar *jspeFactor(); void jspEnsureIsPrototype(JsVar *instanceOf, JsVar *prototypeName); #ifndef SAVE_ON_FLASH JsVar *jspeArrowFunction(JsVar *funcVar, JsVar *a); #endif // ----------------------------------------------- Utils #define JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, CLEANUP_CODE, RETURN_VAL) { if (!jslMatch((TOKEN))) { CLEANUP_CODE; return RETURN_VAL; } } #define JSP_MATCH_WITH_RETURN(TOKEN, RETURN_VAL) JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, , RETURN_VAL) #define JSP_MATCH(TOKEN) JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, , 0) // Match where the user could have given us the wrong token #define JSP_ASSERT_MATCH(TOKEN) { assert(lex->tk==(TOKEN));jslGetNextToken(); } // Match where if we have the wrong token, it's an internal error #define JSP_SHOULD_EXECUTE (((execInfo.execute)&EXEC_RUN_MASK)==EXEC_YES) #define JSP_SAVE_EXECUTE() JsExecFlags oldExecute = execInfo.execute #define JSP_RESTORE_EXECUTE() execInfo.execute = (execInfo.execute&(JsExecFlags)(~EXEC_SAVE_RESTORE_MASK)) | (oldExecute&EXEC_SAVE_RESTORE_MASK); #define JSP_HAS_ERROR (((execInfo.execute)&EXEC_ERROR_MASK)!=0) #define JSP_SHOULDNT_PARSE (((execInfo.execute)&EXEC_NO_PARSE_MASK)!=0) ALWAYS_INLINE void jspDebuggerLoopIfCtrlC() { #ifdef USE_DEBUGGER if (execInfo.execute & EXEC_CTRL_C_WAIT && JSP_SHOULD_EXECUTE) jsiDebuggerLoop(); #endif } /// if interrupting execution, this is set bool jspIsInterrupted() { return (execInfo.execute & EXEC_INTERRUPTED)!=0; } /// if interrupting execution, this is set void jspSetInterrupted(bool interrupt) { if (interrupt) execInfo.execute = execInfo.execute | EXEC_INTERRUPTED; else execInfo.execute = execInfo.execute & (JsExecFlags)~EXEC_INTERRUPTED; } /// Set the error flag - set lineReported if we've already output the line number void jspSetError(bool lineReported) { execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_YES) | EXEC_ERROR; if (lineReported) execInfo.execute |= EXEC_ERROR_LINE_REPORTED; } bool jspHasError() { return JSP_HAS_ERROR; } void jspReplaceWith(JsVar *dst, JsVar *src) { // If this is an index in an array buffer, write directly into the array buffer if (jsvIsArrayBufferName(dst)) { size_t idx = (size_t)jsvGetInteger(dst); JsVar *arrayBuffer = jsvLock(jsvGetFirstChild(dst)); jsvArrayBufferSet(arrayBuffer, idx, src); jsvUnLock(arrayBuffer); return; } // if destination isn't there, isn't a 'name', or is used, give an error if (!jsvIsName(dst)) { jsExceptionHere(JSET_ERROR, "Unable to assign value to non-reference %t", dst); return; } jsvSetValueOfName(dst, src); /* If dst is flagged as a new child, it means that * it was previously undefined, and we need to add it to * the given object when it is set. */ if (jsvIsNewChild(dst)) { // Get what it should have been a child of JsVar *parent = jsvLock(jsvGetNextSibling(dst)); if (!jsvIsString(parent)) { // if we can't find a char in a string we still return a NewChild, // but we can't add character back in if (!jsvHasChildren(parent)) { jsExceptionHere(JSET_ERROR, "Field or method \"%s\" does not already exist, and can't create it on %t", dst, parent); } else { // Remove the 'new child' flagging jsvUnRef(parent); jsvSetNextSibling(dst, 0); jsvUnRef(parent); jsvSetPrevSibling(dst, 0); // Add to the parent jsvAddName(parent, dst); } } jsvUnLock(parent); } } bool jspeiAddScope(JsVar *scope) { if (execInfo.scopeCount >= JSPARSE_MAX_SCOPES) { jsExceptionHere(JSET_ERROR, "Maximum number of scopes exceeded"); jspSetError(false); return false; } execInfo.scopes[execInfo.scopeCount++] = jsvLockAgain(scope); return true; } void jspeiRemoveScope() { if (execInfo.scopeCount <= 0) { jsExceptionHere(JSET_INTERNALERROR, "Too many scopes removed"); jspSetError(false); return; } jsvUnLock(execInfo.scopes[--execInfo.scopeCount]); } JsVar *jspeiFindInScopes(const char *name) { int i; for (i=execInfo.scopeCount-1;i>=0;i--) { JsVar *ref = jsvFindChildFromString(execInfo.scopes[i], name, false); if (ref) return ref; } return jsvFindChildFromString(execInfo.root, name, false); } // TODO: get rid of these, use jspeiGetTopScope instead JsVar *jspeiFindOnTop(const char *name, bool createIfNotFound) { if (execInfo.scopeCount>0) return jsvFindChildFromString(execInfo.scopes[execInfo.scopeCount-1], name, createIfNotFound); return jsvFindChildFromString(execInfo.root, name, createIfNotFound); } JsVar *jspeiFindNameOnTop(JsVar *childName, bool createIfNotFound) { if (execInfo.scopeCount>0) return jsvFindChildFromVar(execInfo.scopes[execInfo.scopeCount-1], childName, createIfNotFound); return jsvFindChildFromVar(execInfo.root, childName, createIfNotFound); } /** Here we assume that we have already looked in the parent itself - * and are now going down looking at the stuff it inherited */ JsVar *jspeiFindChildFromStringInParents(JsVar *parent, const char *name) { if (jsvIsObject(parent)) { // If an object, look for an 'inherits' var JsVar *inheritsFrom = jsvObjectGetChild(parent, JSPARSE_INHERITS_VAR, 0); // if there's no inheritsFrom, just default to 'Object.prototype' if (!inheritsFrom) { JsVar *obj = jsvObjectGetChild(execInfo.root, "Object", 0); if (obj) { inheritsFrom = jsvObjectGetChild(obj, JSPARSE_PROTOTYPE_VAR, 0); jsvUnLock(obj); } } if (inheritsFrom && inheritsFrom!=parent) { // we have what it inherits from (this is ACTUALLY the prototype var) // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/proto JsVar *child = jsvFindChildFromString(inheritsFrom, name, false); if (!child) child = jspeiFindChildFromStringInParents(inheritsFrom, name); jsvUnLock(inheritsFrom); if (child) return child; } else jsvUnLock(inheritsFrom); } else { // Not actually an object - but might be an array/string/etc const char *objectName = jswGetBasicObjectName(parent); while (objectName) { JsVar *objName = jsvFindChildFromString(execInfo.root, objectName, false); if (objName) { JsVar *result = 0; JsVar *obj = jsvSkipNameAndUnLock(objName); // could be something the user has made - eg. 'Array=1' if (jsvHasChildren(obj)) { // We have found an object with this name - search for the prototype var JsVar *proto = jsvObjectGetChild(obj, JSPARSE_PROTOTYPE_VAR, 0); if (proto) { result = jsvFindChildFromString(proto, name, false); jsvUnLock(proto); } } jsvUnLock(obj); if (result) return result; } /* We haven't found anything in the actual object, we should check the 'Object' itself eg, we tried 'String', so now we should try 'Object'. Built-in types don't have room for a prototype field, so we hard-code it */ objectName = jswGetBasicObjectPrototypeName(objectName); } } // no luck! return 0; } JsVar *jspeiGetScopesAsVar() { if (execInfo.scopeCount==0) return 0; if (execInfo.scopeCount==1) return jsvLockAgain(execInfo.scopes[0]); JsVar *arr = jsvNewEmptyArray(); int i; for (i=0;i<execInfo.scopeCount;i++) { JsVar *idx = jsvMakeIntoVariableName(jsvNewFromInteger(i), execInfo.scopes[i]); if (!idx) { // out of memory jspSetError(false); return arr; } jsvAddName(arr, idx); jsvUnLock(idx); } return arr; } void jspeiLoadScopesFromVar(JsVar *arr) { execInfo.scopeCount = 0; if (jsvIsArray(arr)) { JsvObjectIterator it; jsvObjectIteratorNew(&it, arr); while (jsvObjectIteratorHasValue(&it)) { execInfo.scopes[execInfo.scopeCount++] = jsvObjectIteratorGetValue(&it); jsvObjectIteratorNext(&it); } jsvObjectIteratorFree(&it); } else execInfo.scopes[execInfo.scopeCount++] = jsvLockAgain(arr); } // ----------------------------------------------- bool jspCheckStackPosition() { if (jsuGetFreeStack() < 512) { // giving us 512 bytes leeway jsExceptionHere(JSET_ERROR, "Too much recursion - the stack is about to overflow"); jspSetInterrupted(true); return false; } return true; } // Set execFlags such that we are not executing void jspSetNoExecute() { execInfo.execute = (execInfo.execute & (JsExecFlags)(int)~EXEC_RUN_MASK) | EXEC_NO; } void jspAppendStackTrace(JsVar *stackTrace) { JsvStringIterator it; jsvStringIteratorNew(&it, stackTrace, 0); jsvStringIteratorGotoEnd(&it); jslPrintPosition((vcbprintf_callback)jsvStringIteratorPrintfCallback, &it, lex->tokenLastStart); jslPrintTokenLineMarker((vcbprintf_callback)jsvStringIteratorPrintfCallback, &it, lex->tokenLastStart, 0); jsvStringIteratorFree(&it); } /// We had an exception (argument is the exception's value) void jspSetException(JsVar *value) { // Add the exception itself to a variable in root scope JsVar *exception = jsvFindChildFromString(execInfo.hiddenRoot, JSPARSE_EXCEPTION_VAR, true); if (exception) { jsvSetValueOfName(exception, value); jsvUnLock(exception); } // Set the exception flag execInfo.execute = execInfo.execute | EXEC_EXCEPTION; // Try and do a stack trace if (lex) { JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); if (stackTrace) { jsvAppendPrintf(stackTrace, " at "); jspAppendStackTrace(stackTrace); jsvUnLock(stackTrace); // stop us from printing the trace in the same block execInfo.execute = execInfo.execute | EXEC_ERROR_LINE_REPORTED; } } } /** Return the reported exception if there was one (and clear it) */ JsVar *jspGetException() { JsVar *exceptionName = jsvFindChildFromString(execInfo.hiddenRoot, JSPARSE_EXCEPTION_VAR, false); if (exceptionName) { JsVar *exception = jsvSkipName(exceptionName); jsvRemoveChild(execInfo.hiddenRoot, exceptionName); jsvUnLock(exceptionName); JsVar *stack = jspGetStackTrace(); if (stack && jsvHasChildren(exception)) { jsvObjectSetChild(exception, "stack", stack); } jsvUnLock(stack); return exception; } return 0; } /** Return a stack trace string if there was one (and clear it) */ JsVar *jspGetStackTrace() { JsVar *stackTraceName = jsvFindChildFromString(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, false); if (stackTraceName) { JsVar *stackTrace = jsvSkipName(stackTraceName); jsvRemoveChild(execInfo.hiddenRoot, stackTraceName); jsvUnLock(stackTraceName); return stackTrace; } return 0; } // ---------------------------------------------- // we return a value so that JSP_MATCH can return 0 if it fails (if we pass 0, we just parse all args) NO_INLINE bool jspeFunctionArguments(JsVar *funcVar) { JSP_MATCH('('); while (lex->tk!=')') { if (funcVar) { char buf[JSLEX_MAX_TOKEN_LENGTH+1]; buf[0] = '\xFF'; strcpy(&buf[1], jslGetTokenValueAsString(lex)); JsVar *param = jsvAddNamedChild(funcVar, 0, buf); if (!param) { // out of memory jspSetError(false); return false; } jsvMakeFunctionParameter(param); // force this to be called a function parameter jsvUnLock(param); } JSP_MATCH(LEX_ID); if (lex->tk!=')') JSP_MATCH(','); } JSP_MATCH(')'); return true; } // Parse function, assuming we're on '{'. funcVar can be 0 NO_INLINE bool jspeFunctionDefinitionInternal(JsVar *funcVar, bool expressionOnly) { if (expressionOnly) { if (funcVar) funcVar->flags = (funcVar->flags & ~JSV_VARTYPEMASK) | JSV_FUNCTION_RETURN; } else { JSP_MATCH('{'); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_STR && !strcmp(jslGetTokenValueAsString(lex), "compiled")) { jsWarn("Function marked with \"compiled\" uploaded in source form"); } #endif /* If the function starts with return, treat it specially - * we don't want to store the 'return' part of it */ if (funcVar && lex->tk==LEX_R_RETURN) { funcVar->flags = (funcVar->flags & ~JSV_VARTYPEMASK) | JSV_FUNCTION_RETURN; JSP_ASSERT_MATCH(LEX_R_RETURN); } } // Get the line number (if needed) JsVarInt lineNumber = 0; if (funcVar && lex->lineNumberOffset) { // jslGetLineNumber is slow, so we only do it if we have debug info lineNumber = (JsVarInt)jslGetLineNumber(lex) + (JsVarInt)lex->lineNumberOffset - 1; } // Get the code - parse it and figure out where it stops JslCharPos funcBegin = jslCharPosClone(&lex->tokenStart); int lastTokenEnd = -1; if (!expressionOnly) { int brackets = 0; while (lex->tk && (brackets || lex->tk != '}')) { if (lex->tk == '{') brackets++; if (lex->tk == '}') brackets--; lastTokenEnd = (int)jsvStringIteratorGetIndex(&lex->it)-1; JSP_ASSERT_MATCH(lex->tk); } } else { JsExecFlags oldExec = execInfo.execute; execInfo.execute = EXEC_NO; jsvUnLock(jspeAssignmentExpression()); execInfo.execute = oldExec; lastTokenEnd = (int)jsvStringIteratorGetIndex(&lex->tokenStart.it)-1; } // Then create var and set (if there was any code!) if (funcVar && lastTokenEnd>0) { // code var JsVar *funcCodeVar; if (jsvIsNativeString(lex->sourceVar)) { /* If we're parsing from a Native String (eg. E.memoryArea, E.setBootCode) then use another Native String to load function code straight from flash */ int s = (int)jsvStringIteratorGetIndex(&funcBegin.it) - 1; funcCodeVar = jsvNewNativeString(lex->sourceVar->varData.nativeStr.ptr + s, (unsigned int)(lastTokenEnd - s)); } else { if (jsfGetFlag(JSF_PRETOKENISE)) { funcCodeVar = jslNewTokenisedStringFromLexer(&funcBegin, (size_t)lastTokenEnd); } else { funcCodeVar = jslNewStringFromLexer(&funcBegin, (size_t)lastTokenEnd); } } jsvUnLock2(jsvAddNamedChild(funcVar, funcCodeVar, JSPARSE_FUNCTION_CODE_NAME), funcCodeVar); // scope var JsVar *funcScopeVar = jspeiGetScopesAsVar(); if (funcScopeVar) { jsvUnLock2(jsvAddNamedChild(funcVar, funcScopeVar, JSPARSE_FUNCTION_SCOPE_NAME), funcScopeVar); } // If we've got a line number, add a var for it if (lineNumber) { JsVar *funcLineNumber = jsvNewFromInteger(lineNumber); if (funcLineNumber) { jsvUnLock2(jsvAddNamedChild(funcVar, funcLineNumber, JSPARSE_FUNCTION_LINENUMBER_NAME), funcLineNumber); } } } jslCharPosFree(&funcBegin); if (!expressionOnly) JSP_MATCH('}'); return 0; } // Parse function (after 'function' has occurred NO_INLINE JsVar *jspeFunctionDefinition(bool parseNamedFunction) { // actually parse a function... We assume that the LEX_FUNCTION and name // have already been parsed JsVar *funcVar = 0; bool actuallyCreateFunction = JSP_SHOULD_EXECUTE; if (actuallyCreateFunction) funcVar = jsvNewWithFlags(JSV_FUNCTION); JsVar *functionInternalName = 0; if (parseNamedFunction && lex->tk==LEX_ID) { // you can do `var a = function foo() { foo(); };` - so cope with this if (funcVar) functionInternalName = jslGetTokenValueAsVar(lex); // note that we don't add it to the beginning, because it would mess up our function call code JSP_ASSERT_MATCH(LEX_ID); } // Get arguments save them to the structure if (!jspeFunctionArguments(funcVar)) { jsvUnLock2(functionInternalName, funcVar); // parse failed return 0; } // Parse the actual function block jspeFunctionDefinitionInternal(funcVar, false); // if we had a function name, add it to the end (if we don't it gets confused with arguments) if (funcVar && functionInternalName) jsvObjectSetChildAndUnLock(funcVar, JSPARSE_FUNCTION_NAME_NAME, functionInternalName); return funcVar; } /* Parse just the brackets of a function - and throw * everything away */ NO_INLINE bool jspeParseFunctionCallBrackets() { assert(!JSP_SHOULD_EXECUTE); JSP_MATCH('('); while (!JSP_SHOULDNT_PARSE && lex->tk != ')') { jsvUnLock(jspeAssignmentExpression()); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_ARROW_FUNCTION) { jsvUnLock(jspeArrowFunction(0, 0)); } #endif if (lex->tk!=')') JSP_MATCH(','); } if (!JSP_SHOULDNT_PARSE) JSP_MATCH(')'); return 0; } /** Handle a function call (assumes we've parsed the function name and we're * on the start bracket). 'thisArg' is the value of the 'this' variable when the * function is executed (it's usually the parent object) * * * NOTE: this does not set the execInfo flags - so if execInfo==EXEC_NO, it won't execute * * If !isParsing and arg0!=0, argument 0 is set to what is supplied (same with arg1) * * functionName is used only for error reporting - and can be 0 */ NO_INLINE JsVar *jspeFunctionCall(JsVar *function, JsVar *functionName, JsVar *thisArg, bool isParsing, int argCount, JsVar **argPtr) { if (JSP_SHOULD_EXECUTE && !function) { if (functionName) jsExceptionHere(JSET_ERROR, "Function %q not found!", functionName); else jsExceptionHere(JSET_ERROR, "Function not found!", functionName); return 0; } if (JSP_SHOULD_EXECUTE) if (!jspCheckStackPosition()) return 0; // try and ensure that we won't overflow our stack if (JSP_SHOULD_EXECUTE && function) { JsVar *returnVar = 0; if (!jsvIsFunction(function)) { jsExceptionHere(JSET_ERROR, "Expecting a function to call, got %t", function); return 0; } JsVar *thisVar = jsvLockAgainSafe(thisArg); if (isParsing) JSP_MATCH('('); /* Ok, so we have 4 options here. * * 1: we're native. * a) args have been pre-parsed, which is awesome * b) we have to parse our own args into an array * 2: we're not native * a) args were pre-parsed and we have to populate the function * b) we parse our own args, which is possibly better */ if (jsvIsNative(function)) { // ------------------------------------- NATIVE unsigned int argPtrSize = 0; int boundArgs = 0; // Add 'bound' parameters if there were any JsvObjectIterator it; jsvObjectIteratorNew(&it, function); JsVar *param = jsvObjectIteratorGetKey(&it); while (jsvIsFunctionParameter(param)) { if ((unsigned)argCount>=argPtrSize) { // allocate more space on stack if needed unsigned int newArgPtrSize = argPtrSize?argPtrSize*4:16; JsVar **newArgPtr = (JsVar**)alloca(sizeof(JsVar*)*newArgPtrSize); memcpy(newArgPtr, argPtr, (unsigned)argCount*sizeof(JsVar*)); argPtr = newArgPtr; argPtrSize = newArgPtrSize; } // if we already had arguments - shift them up... int i; for (i=argCount-1;i>=boundArgs;i--) argPtr[i+1] = argPtr[i]; // add bound argument argPtr[boundArgs] = jsvSkipName(param); argCount++; boundArgs++; jsvUnLock(param); jsvObjectIteratorNext(&it); param = jsvObjectIteratorGetKey(&it); } // check if 'this' was defined while (param) { if (jsvIsStringEqual(param, JSPARSE_FUNCTION_THIS_NAME)) { jsvUnLock(thisVar); thisVar = jsvSkipName(param); break; } jsvUnLock(param); jsvObjectIteratorNext(&it); param = jsvObjectIteratorGetKey(&it); } jsvUnLock(param); jsvObjectIteratorFree(&it); // Now, if we're parsing add the rest of the arguments int allocatedArgCount = boundArgs; if (isParsing) { while (!JSP_HAS_ERROR && lex->tk!=')' && lex->tk!=LEX_EOF) { if ((unsigned)argCount>=argPtrSize) { // allocate more space on stack unsigned int newArgPtrSize = argPtrSize?argPtrSize*4:16; JsVar **newArgPtr = (JsVar**)alloca(sizeof(JsVar*)*newArgPtrSize); memcpy(newArgPtr, argPtr, (unsigned)argCount*sizeof(JsVar*)); argPtr = newArgPtr; argPtrSize = newArgPtrSize; } argPtr[argCount++] = jsvSkipNameAndUnLock(jspeAssignmentExpression()); if (lex->tk!=')') JSP_MATCH_WITH_CLEANUP_AND_RETURN(',',jsvUnLockMany((unsigned)argCount, argPtr);jsvUnLock(thisVar);, 0); } JSP_MATCH(')'); allocatedArgCount = argCount; } void *nativePtr = jsvGetNativeFunctionPtr(function); JsVar *oldThisVar = execInfo.thisVar; if (thisVar) execInfo.thisVar = jsvRef(thisVar); else { if (nativePtr==jswrap_eval) { // eval gets to use the current scope /* Note: proper JS has some utterly insane code that depends on whether * eval is an lvalue or not: * * http://stackoverflow.com/questions/9107240/1-evalthis-vs-evalthis-in-javascript * * Doing this in Espruino is quite an upheaval for that one * slightly insane case - so it's not implemented. */ if (execInfo.thisVar) execInfo.thisVar = jsvRef(execInfo.thisVar); } else { execInfo.thisVar = jsvRef(execInfo.root); // 'this' should always default to root } } if (nativePtr && !JSP_HAS_ERROR) { returnVar = jsnCallFunction(nativePtr, function->varData.native.argTypes, thisVar, argPtr, argCount); } else { returnVar = 0; } // unlock values if we locked them jsvUnLockMany((unsigned)allocatedArgCount, argPtr); /* Return to old 'this' var. No need to unlock as we never locked before */ if (execInfo.thisVar) jsvUnRef(execInfo.thisVar); execInfo.thisVar = oldThisVar; } else { // ----------------------------------------------------- NOT NATIVE // create a new symbol table entry for execution of this function // OPT: can we cache this function execution environment + param variables? // OPT: Probably when calling a function ONCE, use it, otherwise when recursing, make new? JsVar *functionRoot = jsvNewWithFlags(JSV_FUNCTION); if (!functionRoot) { // out of memory jspSetError(false); jsvUnLock(thisVar); return 0; } JsVar *functionScope = 0; JsVar *functionCode = 0; JsVar *functionInternalName = 0; uint16_t functionLineNumber = 0; /** NOTE: We expect that the function object will have: * * * Parameters * * Code/Scope/Name * * IN THAT ORDER. */ JsvObjectIterator it; jsvObjectIteratorNew(&it, function); JsVar *param = jsvObjectIteratorGetKey(&it); JsVar *value = jsvObjectIteratorGetValue(&it); while (jsvIsFunctionParameter(param) && value) { JsVar *paramName = jsvNewFromStringVar(param,1,JSVAPPENDSTRINGVAR_MAXLENGTH); if (paramName) { // could be out of memory jsvMakeFunctionParameter(paramName); // force this to be called a function parameter jsvSetValueOfName(paramName, value); jsvAddName(functionRoot, paramName); jsvUnLock(paramName); } else jspSetError(false); jsvUnLock2(value, param); jsvObjectIteratorNext(&it); param = jsvObjectIteratorGetKey(&it); value = jsvObjectIteratorGetValue(&it); } jsvUnLock2(value, param); if (isParsing) { int hadParams = 0; // grab in all parameters. We go around this loop until we've run out // of named parameters AND we've parsed all the supplied arguments while (!JSP_SHOULDNT_PARSE && lex->tk!=')') { JsVar *param = jsvObjectIteratorGetKey(&it); bool paramDefined = jsvIsFunctionParameter(param); if (lex->tk!=')' || paramDefined) { hadParams++; JsVar *value = 0; // ONLY parse this if it was supplied, otherwise leave 0 (undefined) if (lex->tk!=')') value = jspeAssignmentExpression(); // and if execute, copy it over value = jsvSkipNameAndUnLock(value); JsVar *paramName = paramDefined ? jsvNewFromStringVar(param,1,JSVAPPENDSTRINGVAR_MAXLENGTH) : jsvNewFromEmptyString(); if (paramName) { // could be out of memory jsvMakeFunctionParameter(paramName); // force this to be called a function parameter jsvSetValueOfName(paramName, value); jsvAddName(functionRoot, paramName); jsvUnLock(paramName); } else jspSetError(false); jsvUnLock(value); if (lex->tk!=')') JSP_MATCH(','); } jsvUnLock(param); if (paramDefined) jsvObjectIteratorNext(&it); } JSP_MATCH(')'); } else { // and NOT isParsing int args = 0; while (args<argCount) { JsVar *param = jsvObjectIteratorGetKey(&it); bool paramDefined = jsvIsFunctionParameter(param); JsVar *paramName = paramDefined ? jsvNewFromStringVar(param,1,JSVAPPENDSTRINGVAR_MAXLENGTH) : jsvNewFromEmptyString(); if (paramName) { jsvMakeFunctionParameter(paramName); // force this to be called a function parameter jsvSetValueOfName(paramName, argPtr[args]); jsvAddName(functionRoot, paramName); jsvUnLock(paramName); } else jspSetError(false); args++; jsvUnLock(param); if (paramDefined) jsvObjectIteratorNext(&it); } } // Now go through what's left while (jsvObjectIteratorHasValue(&it)) { JsVar *param = jsvObjectIteratorGetKey(&it); if (jsvIsString(param)) { if (jsvIsStringEqual(param, JSPARSE_FUNCTION_SCOPE_NAME)) functionScope = jsvSkipName(param); else if (jsvIsStringEqual(param, JSPARSE_FUNCTION_CODE_NAME)) functionCode = jsvSkipName(param); else if (jsvIsStringEqual(param, JSPARSE_FUNCTION_NAME_NAME)) functionInternalName = jsvSkipName(param); else if (jsvIsStringEqual(param, JSPARSE_FUNCTION_THIS_NAME)) { jsvUnLock(thisVar); thisVar = jsvSkipName(param); } else if (jsvIsStringEqual(param, JSPARSE_FUNCTION_LINENUMBER_NAME)) functionLineNumber = (uint16_t)jsvGetIntegerAndUnLock(jsvSkipName(param)); else if (jsvIsFunctionParameter(param)) { JsVar *paramName = jsvNewFromStringVar(param,1,JSVAPPENDSTRINGVAR_MAXLENGTH); // paramName is already a name (it's a function parameter) if (paramName) {// could be out of memory - or maybe just not supplied! jsvMakeFunctionParameter(paramName); JsVar *defaultVal = jsvSkipName(param); if (defaultVal) jsvUnLock(jsvSetValueOfName(paramName, defaultVal)); jsvAddName(functionRoot, paramName); jsvUnLock(paramName); } } } jsvUnLock(param); jsvObjectIteratorNext(&it); } jsvObjectIteratorFree(&it); // setup a the function's name (if a named function) if (functionInternalName) { JsVar *name = jsvMakeIntoVariableName(jsvNewFromStringVar(functionInternalName,0,JSVAPPENDSTRINGVAR_MAXLENGTH), function); jsvAddName(functionRoot, name); jsvUnLock2(name, functionInternalName); } if (!JSP_HAS_ERROR) { // save old scopes JsVar *oldScopes[JSPARSE_MAX_SCOPES]; int oldScopeCount; int i; oldScopeCount = execInfo.scopeCount; for (i=0;i<execInfo.scopeCount;i++) oldScopes[i] = execInfo.scopes[i]; // if we have a scope var, load it up. We may not have one if there were no scopes apart from root if (functionScope) { jspeiLoadScopesFromVar(functionScope); jsvUnLock(functionScope); } else { // no scope var defined? We have no scopes at all! execInfo.scopeCount = 0; } // add the function's execute space to the symbol table so we can recurse if (jspeiAddScope(functionRoot)) { /* Adding scope may have failed - we may have descended too deep - so be sure * not to pull somebody else's scope off */ JsVar *oldThisVar = execInfo.thisVar; if (thisVar) execInfo.thisVar = jsvRef(thisVar); else execInfo.thisVar = jsvRef(execInfo.root); // 'this' should always default to root /* we just want to execute the block, but something could * have messed up and left us with the wrong Lexer, so * we want to be careful here... */ if (functionCode) { #ifdef USE_DEBUGGER bool hadDebuggerNextLineOnly = false; if (execInfo.execute&EXEC_DEBUGGER_STEP_INTO) { if (functionName) jsiConsolePrintf("Stepping into %v\n", functionName); else jsiConsolePrintf("Stepping into function\n", functionName); } else { hadDebuggerNextLineOnly = execInfo.execute&EXEC_DEBUGGER_NEXT_LINE; if (hadDebuggerNextLineOnly) execInfo.execute &= (JsExecFlags)~EXEC_DEBUGGER_NEXT_LINE; } #endif JsLex newLex; JsLex *oldLex = jslSetLex(&newLex); jslInit(functionCode); newLex.lineNumberOffset = functionLineNumber; JSP_SAVE_EXECUTE(); // force execute without any previous state #ifdef USE_DEBUGGER execInfo.execute = EXEC_YES | (execInfo.execute&(EXEC_CTRL_C_MASK|EXEC_ERROR_MASK|EXEC_DEBUGGER_NEXT_LINE)); #else execInfo.execute = EXEC_YES | (execInfo.execute&(EXEC_CTRL_C_MASK|EXEC_ERROR_MASK)); #endif if (jsvIsFunctionReturn(function)) { #ifdef USE_DEBUGGER // we didn't parse a statement so wouldn't trigger the debugger otherwise if (execInfo.execute&EXEC_DEBUGGER_NEXT_LINE && JSP_SHOULD_EXECUTE) { lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it)-1; jsiDebuggerLoop(); } #endif // implicit return - we just need an expression (optional) if (lex->tk != ';' && lex->tk != '}') returnVar = jsvSkipNameAndUnLock(jspeExpression()); } else { // setup a return variable JsVar *returnVarName = jsvAddNamedChild(functionRoot, 0, JSPARSE_RETURN_VAR); // parse the whole block jspeBlockNoBrackets(); /* get the real return var before we remove it from our function. * We can unlock below because returnVarName is still part of * functionRoot, so won't get freed. */ returnVar = jsvSkipNameAndUnLock(returnVarName); if (returnVarName) // could have failed with out of memory jsvSetValueOfName(returnVarName, 0); // remove return value (which helps stops circular references) } // Store a stack trace if we had an error JsExecFlags hasError = execInfo.execute&EXEC_ERROR_MASK; JSP_RESTORE_EXECUTE(); // because return will probably have set execute to false #ifdef USE_DEBUGGER bool calledDebugger = false; if (execInfo.execute & EXEC_DEBUGGER_MASK) { jsiConsolePrint("Value returned is ="); jsfPrintJSON(returnVar, JSON_LIMIT | JSON_SOME_NEWLINES | JSON_PRETTY | JSON_SHOW_DEVICES); jsiConsolePrintChar('\n'); if (execInfo.execute & EXEC_DEBUGGER_FINISH_FUNCTION) { calledDebugger = true; jsiDebuggerLoop(); } } if (hadDebuggerNextLineOnly && !calledDebugger) execInfo.execute |= EXEC_DEBUGGER_NEXT_LINE; #endif jslKill(); jslSetLex(oldLex); if (hasError) { execInfo.execute |= hasError; // propogate error JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); if (stackTrace) { jsvAppendPrintf(stackTrace, jsvIsString(functionName)?"in function %q called from ": "in function called from ", functionName); if (lex) { jspAppendStackTrace(stackTrace); } else jsvAppendPrintf(stackTrace, "system\n"); jsvUnLock(stackTrace); } } } /* Return to old 'this' var. No need to unlock as we never locked before */ if (execInfo.thisVar) jsvUnRef(execInfo.thisVar); execInfo.thisVar = oldThisVar; jspeiRemoveScope(); } // Unref old scopes for (i=0;i<execInfo.scopeCount;i++) jsvUnLock(execInfo.scopes[i]); // restore function scopes for (i=0;i<oldScopeCount;i++) execInfo.scopes[i] = oldScopes[i]; execInfo.scopeCount = oldScopeCount; } jsvUnLock(functionCode); jsvUnLock(functionRoot); } jsvUnLock(thisVar); return returnVar; } else if (isParsing) { // ---------------------------------- function, but not executing - just parse args and be done jspeParseFunctionCallBrackets(); /* Do not return function, as it will be unlocked! */ return 0; } else return 0; } // Find a variable (or built-in function) based on the current scopes JsVar *jspGetNamedVariable(const char *tokenName) { JsVar *a = JSP_SHOULD_EXECUTE ? jspeiFindInScopes(tokenName) : 0; if (JSP_SHOULD_EXECUTE && !a) { /* Special case! We haven't found the variable, so check out * and see if it's one of our builtins... */ if (jswIsBuiltInObject(tokenName)) { // Check if we have a built-in function for it // OPT: Could we instead have jswIsBuiltInObjectWithoutConstructor? JsVar *obj = jswFindBuiltInFunction(0, tokenName); // If not, make one if (!obj) obj = jspNewBuiltin(tokenName); if (obj) { // not out of memory a = jsvAddNamedChild(execInfo.root, obj, tokenName); jsvUnLock(obj); } } else { a = jswFindBuiltInFunction(0, tokenName); if (!a) { /* Variable doesn't exist! JavaScript says we should create it * (we won't add it here. This is done in the assignment operator)*/ a = jsvMakeIntoVariableName(jsvNewFromString(tokenName), 0); } } } return a; } /// Used by jspGetNamedField / jspGetVarNamedField static NO_INLINE JsVar *jspGetNamedFieldInParents(JsVar *object, const char* name, bool returnName) { // Now look in prototypes JsVar * child = jspeiFindChildFromStringInParents(object, name); /* Check for builtins via separate function * This way we save on RAM for built-ins because everything comes out of program code */ if (!child) { child = jswFindBuiltInFunction(object, name); } /* We didn't get here if we found a child in the object itself, so * if we're here then we probably have the wrong name - so for example * with `a.b = c;` could end up setting `a.prototype.b` (bug #360) * * Also we might have got a built-in, which wouldn't have a name on it * anyway - so in both cases, strip the name if it is there, and create * a new name. */ if (child && returnName) { // Get rid of existing name child = jsvSkipNameAndUnLock(child); // create a new name JsVar *nameVar = jsvNewFromString(name); JsVar *newChild = jsvCreateNewChild(object, nameVar, child); jsvUnLock2(nameVar, child); child = newChild; } // If not found and is the prototype, create it if (!child) { if (jsvIsFunction(object) && strcmp(name, JSPARSE_PROTOTYPE_VAR)==0) { // prototype is supposed to be an object JsVar *proto = jsvNewObject(); // make sure it has a 'constructor' variable that points to the object it was part of jsvObjectSetChild(proto, JSPARSE_CONSTRUCTOR_VAR, object); child = jsvAddNamedChild(object, proto, JSPARSE_PROTOTYPE_VAR); jspEnsureIsPrototype(object, child); jsvUnLock(proto); } else if (strcmp(name, JSPARSE_INHERITS_VAR)==0) { const char *objName = jswGetBasicObjectName(object); if (objName) { child = jspNewPrototype(objName); } } } return child; } /** Get the named function/variable on the object - whether it's built in, or predefined. * If !returnName, returns the function/variable itself or undefined, but * if returnName, return a name (could be fake) referencing the parent. * * NOTE: ArrayBuffer/Strings are not handled here. We assume that if we're * passing a char* rather than a JsVar it's because we're looking up via * a symbol rather than a variable. To handle these use jspGetVarNamedField */ JsVar *jspGetNamedField(JsVar *object, const char* name, bool returnName) { JsVar *child = 0; // if we're an object (or pretending to be one) if (jsvHasChildren(object)) child = jsvFindChildFromString(object, name, false); if (!child) { child = jspGetNamedFieldInParents(object, name, returnName); // If not found and is the prototype, create it if (!child && jsvIsFunction(object) && strcmp(name, JSPARSE_PROTOTYPE_VAR)==0) { JsVar *value = jsvNewObject(); // prototype is supposed to be an object child = jsvAddNamedChild(object, value, JSPARSE_PROTOTYPE_VAR); jsvUnLock(value); } } if (returnName) return child; else return jsvSkipNameAndUnLock(child); } /// see jspGetNamedField - note that nameVar should have had jsvAsArrayIndex called on it first JsVar *jspGetVarNamedField(JsVar *object, JsVar *nameVar, bool returnName) { JsVar *child = 0; // if we're an object (or pretending to be one) if (jsvHasChildren(object)) child = jsvFindChildFromVar(object, nameVar, false); if (!child) { if (jsvIsArrayBuffer(object) && jsvIsInt(nameVar)) { // for array buffers, we actually create a NAME, and hand that back - then when we assign (or use SkipName) we pull out the correct data child = jsvMakeIntoVariableName(jsvNewFromInteger(jsvGetInteger(nameVar)), object); if (child) // turn into an 'array buffer name' child->flags = (child->flags & ~JSV_VARTYPEMASK) | JSV_ARRAYBUFFERNAME; } else if (jsvIsString(object) && jsvIsInt(nameVar)) { JsVarInt idx = jsvGetInteger(nameVar); if (idx>=0 && idx<(JsVarInt)jsvGetStringLength(object)) { char ch = jsvGetCharInString(object, (size_t)idx); child = jsvNewStringOfLength(1, &ch); } else if (returnName) child = jsvCreateNewChild(object, nameVar, 0); // just return *something* to show this is handled } else { // get the name as a string char name[JSLEX_MAX_TOKEN_LENGTH]; jsvGetString(nameVar, name, JSLEX_MAX_TOKEN_LENGTH); // try and find it in parents child = jspGetNamedFieldInParents(object, name, returnName); // If not found and is the prototype, create it if (!child && jsvIsFunction(object) && jsvIsStringEqual(nameVar, JSPARSE_PROTOTYPE_VAR)) { JsVar *value = jsvNewObject(); // prototype is supposed to be an object child = jsvAddNamedChild(object, value, JSPARSE_PROTOTYPE_VAR); jsvUnLock(value); } } } if (returnName) return child; else return jsvSkipNameAndUnLock(child); } /// Call the named function on the object - whether it's built in, or predefined. Returns the return value of the function. JsVar *jspCallNamedFunction(JsVar *object, char* name, int argCount, JsVar **argPtr) { JsVar *child = jspGetNamedField(object, name, false); JsVar *r = 0; if (jsvIsFunction(child)) r = jspeFunctionCall(child, 0, object, false, argCount, argPtr); jsvUnLock(child); return r; } NO_INLINE JsVar *jspeFactorMember(JsVar *a, JsVar **parentResult) { /* The parent if we're executing a method call */ JsVar *parent = 0; while (lex->tk=='.' || lex->tk=='[') { if (lex->tk == '.') { // ------------------------------------- Record Access JSP_ASSERT_MATCH('.'); if (jslIsIDOrReservedWord(lex)) { if (JSP_SHOULD_EXECUTE) { // Note: name will go away when we parse something else! const char *name = jslGetTokenValueAsString(lex); JsVar *aVar = jsvSkipName(a); JsVar *child = 0; if (aVar) child = jspGetNamedField(aVar, name, true); if (!child) { if (!jsvIsUndefined(aVar)) { // if no child found, create a pointer to where it could be // as we don't want to allocate it until it's written JsVar *nameVar = jslGetTokenValueAsVar(lex); child = jsvCreateNewChild(aVar, nameVar, 0); jsvUnLock(nameVar); } else { // could have been a string... jsExceptionHere(JSET_ERROR, "Cannot read property '%s' of undefined", name); } } jsvUnLock(parent); parent = aVar; jsvUnLock(a); a = child; } // skip over current token (we checked above that it was an ID or reserved word) jslGetNextToken(lex); } else { // incorrect token - force a match fail by asking for an ID JSP_MATCH_WITH_RETURN(LEX_ID, a); } } else if (lex->tk == '[') { // ------------------------------------- Array Access JsVar *index; JSP_ASSERT_MATCH('['); if (!jspCheckStackPosition()) return parent; index = jsvSkipNameAndUnLock(jspeAssignmentExpression()); JSP_MATCH_WITH_CLEANUP_AND_RETURN(']', jsvUnLock2(parent, index);, a); if (JSP_SHOULD_EXECUTE) { index = jsvAsArrayIndexAndUnLock(index); JsVar *aVar = jsvSkipName(a); JsVar *child = 0; if (aVar) child = jspGetVarNamedField(aVar, index, true); if (!child) { if (jsvHasChildren(aVar)) { // if no child found, create a pointer to where it could be // as we don't want to allocate it until it's written child = jsvCreateNewChild(aVar, index, 0); } else { jsExceptionHere(JSET_ERROR, "Field or method %q does not already exist, and can't create it on %t", index, aVar); } } jsvUnLock(parent); parent = jsvLockAgainSafe(aVar); jsvUnLock(a); a = child; jsvUnLock(aVar); } jsvUnLock(index); } else { assert(0); } } if (parentResult) *parentResult = parent; else jsvUnLock(parent); return a; } NO_INLINE JsVar *jspeConstruct(JsVar *func, JsVar *funcName, bool hasArgs) { assert(JSP_SHOULD_EXECUTE); if (!jsvIsFunction(func)) { jsExceptionHere(JSET_ERROR, "Constructor should be a function, but is %t", func); return 0; } JsVar *thisObj = jsvNewObject(); if (!thisObj) return 0; // out of memory // Make sure the function has a 'prototype' var JsVar *prototypeName = jsvFindChildFromString(func, JSPARSE_PROTOTYPE_VAR, true); jspEnsureIsPrototype(func, prototypeName); // make sure it's an object JsVar *prototypeVar = jsvSkipName(prototypeName); jsvUnLock3(jsvAddNamedChild(thisObj, prototypeVar, JSPARSE_INHERITS_VAR), prototypeVar, prototypeName); JsVar *a = jspeFunctionCall(func, funcName, thisObj, hasArgs, 0, 0); /* FIXME: we should ignore return values that aren't objects (bug #848), but then we need * to be aware of `new String()` and `new Uint8Array()`. Ideally we'd let through * arrays/etc, and then String/etc should return 'boxed' values. * * But they don't return boxed values at the moment, so let's just * pass the return value through. If you try and return a string from * a function it's broken JS code anyway. */ if (a) { jsvUnLock(thisObj); thisObj = a; } else { jsvUnLock(a); } return thisObj; } NO_INLINE JsVar *jspeFactorFunctionCall() { /* The parent if we're executing a method call */ bool isConstructor = false; if (lex->tk==LEX_R_NEW) { JSP_ASSERT_MATCH(LEX_R_NEW); isConstructor = true; if (lex->tk==LEX_R_NEW) { jsExceptionHere(JSET_ERROR, "Nesting 'new' operators is unsupported"); jspSetError(false); return 0; } } JsVar *parent = 0; #ifndef SAVE_ON_FLASH bool wasSuper = lex->tk==LEX_R_SUPER; #endif JsVar *a = jspeFactorMember(jspeFactor(), &parent); #ifndef SAVE_ON_FLASH if (wasSuper) { /* if this was 'super.something' then we need * to overwrite the parent, because it'll be * set to the prototype otherwise. */ jsvUnLock(parent); parent = jsvLockAgainSafe(execInfo.thisVar); } #endif while ((lex->tk=='(' || (isConstructor && JSP_SHOULD_EXECUTE)) && !jspIsInterrupted()) { JsVar *funcName = a; JsVar *func = jsvSkipName(funcName); /* The constructor function doesn't change parsing, so if we're * not executing, just short-cut it. */ if (isConstructor && JSP_SHOULD_EXECUTE) { // If we have '(' parse an argument list, otherwise don't look for any args bool parseArgs = lex->tk=='('; a = jspeConstruct(func, funcName, parseArgs); isConstructor = false; // don't treat subsequent brackets as constructors } else a = jspeFunctionCall(func, funcName, parent, true, 0, 0); jsvUnLock3(funcName, func, parent); parent=0; a = jspeFactorMember(a, &parent); } jsvUnLock(parent); return a; } NO_INLINE JsVar *jspeFactorObject() { if (JSP_SHOULD_EXECUTE) { JsVar *contents = jsvNewObject(); if (!contents) { // out of memory jspSetError(false); return 0; } /* JSON-style object definition */ JSP_MATCH_WITH_RETURN('{', contents); while (!JSP_SHOULDNT_PARSE && lex->tk != '}') { JsVar *varName = 0; // we only allow strings or IDs on the left hand side of an initialisation if (jslIsIDOrReservedWord(lex)) { if (JSP_SHOULD_EXECUTE) varName = jslGetTokenValueAsVar(lex); jslGetNextToken(lex); // skip over current token } else if ( lex->tk==LEX_STR || lex->tk==LEX_TEMPLATE_LITERAL || lex->tk==LEX_FLOAT || lex->tk==LEX_INT || lex->tk==LEX_R_TRUE || lex->tk==LEX_R_FALSE || lex->tk==LEX_R_NULL || lex->tk==LEX_R_UNDEFINED) { varName = jspeFactor(); } else { JSP_MATCH_WITH_RETURN(LEX_ID, contents); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(':', jsvUnLock(varName), contents); if (JSP_SHOULD_EXECUTE) { varName = jsvAsArrayIndexAndUnLock(varName); JsVar *contentsName = jsvFindChildFromVar(contents, varName, true); if (contentsName) { JsVar *value = jsvSkipNameAndUnLock(jspeAssignmentExpression()); // value can be 0 (could be undefined!) jsvUnLock2(jsvSetValueOfName(contentsName, value), value); } } jsvUnLock(varName); // no need to clean here, as it will definitely be used if (lex->tk != '}') JSP_MATCH_WITH_RETURN(',', contents); } JSP_MATCH_WITH_RETURN('}', contents); return contents; } else { // Not executing so do fast skip jspeBlock(); return 0; } } NO_INLINE JsVar *jspeFactorArray() { int idx = 0; JsVar *contents = 0; if (JSP_SHOULD_EXECUTE) { contents = jsvNewEmptyArray(); if (!contents) { // out of memory jspSetError(false); return 0; } } /* JSON-style array */ JSP_MATCH_WITH_RETURN('[', contents); while (!JSP_SHOULDNT_PARSE && lex->tk != ']') { if (JSP_SHOULD_EXECUTE) { JsVar *aVar = 0; JsVar *indexName = 0; if (lex->tk != ',') { // #287 - [,] and [1,2,,4] are allowed aVar = jsvSkipNameAndUnLock(jspeAssignmentExpression()); indexName = jsvMakeIntoVariableName(jsvNewFromInteger(idx), aVar); } if (indexName) { // could be out of memory jsvAddName(contents, indexName); jsvUnLock(indexName); } jsvUnLock(aVar); } else { jsvUnLock(jspeAssignmentExpression()); } // no need to clean here, as it will definitely be used if (lex->tk != ']') JSP_MATCH_WITH_RETURN(',', contents); idx++; } if (contents) jsvSetArrayLength(contents, idx, false); JSP_MATCH_WITH_RETURN(']', contents); return contents; } NO_INLINE void jspEnsureIsPrototype(JsVar *instanceOf, JsVar *prototypeName) { if (!prototypeName) return; JsVar *prototypeVar = jsvSkipName(prototypeName); if (!jsvIsObject(prototypeVar)) { if (!jsvIsUndefined(prototypeVar)) jsExceptionHere(JSET_TYPEERROR, "Prototype should be an object, got %t", prototypeVar); jsvUnLock(prototypeVar); prototypeVar = jsvNewObject(); // prototype is supposed to be an object JsVar *lastName = jsvSkipToLastName(prototypeName); jsvSetValueOfName(lastName, prototypeVar); jsvUnLock(lastName); } JsVar *constructor = jsvFindChildFromString(prototypeVar, JSPARSE_CONSTRUCTOR_VAR, true); if (constructor) jsvSetValueOfName(constructor, instanceOf); jsvUnLock2(constructor, prototypeVar); } NO_INLINE JsVar *jspeFactorTypeOf() { JSP_ASSERT_MATCH(LEX_R_TYPEOF); JsVar *a = jspeUnaryExpression(); JsVar *result = 0; if (JSP_SHOULD_EXECUTE) { if (!jsvIsVariableDefined(a)) { // so we don't get a ReferenceError when accessing an undefined var result=jsvNewFromString("undefined"); } else { a = jsvSkipNameAndUnLock(a); result=jsvNewFromString(jsvGetTypeOf(a)); } } jsvUnLock(a); return result; } NO_INLINE JsVar *jspeFactorDelete() { JSP_ASSERT_MATCH(LEX_R_DELETE); JsVar *parent = 0; JsVar *a = jspeFactorMember(jspeFactor(), &parent); JsVar *result = 0; if (JSP_SHOULD_EXECUTE) { bool ok = false; if (jsvIsName(a) && !jsvIsNewChild(a)) { // if no parent, check in root? if (!parent && jsvIsChild(execInfo.root, a)) parent = jsvLockAgain(execInfo.root); if (parent && !jsvIsFunction(parent)) { // else remove properly. if (jsvIsArray(parent)) { // For arrays, we must make sure we don't change the length JsVarInt l = jsvGetArrayLength(parent); jsvRemoveChild(parent, a); jsvSetArrayLength(parent, l, false); } else { jsvRemoveChild(parent, a); } ok = true; } } result = jsvNewFromBool(ok); } jsvUnLock2(a, parent); return result; } #ifndef SAVE_ON_FLASH JsVar *jspeTemplateLiteral() { JsVar *a = 0; if (JSP_SHOULD_EXECUTE) { JsVar *template = jslGetTokenValueAsVar(lex); a = jsvNewFromEmptyString(); if (a && template) { JsvStringIterator it, dit; jsvStringIteratorNew(&it, template, 0); jsvStringIteratorNew(&dit, a, 0); while (jsvStringIteratorHasChar(&it)) { char ch = jsvStringIteratorGetChar(&it); if (ch=='$') { jsvStringIteratorNext(&it); ch = jsvStringIteratorGetChar(&it); if (ch=='{') { // Now parse out the expression jsvStringIteratorNext(&it); int brackets = 1; JsVar *expr = jsvNewFromEmptyString(); if (!expr) break; JsvStringIterator eit; jsvStringIteratorNew(&eit, expr, 0); while (jsvStringIteratorHasChar(&it)) { ch = jsvStringIteratorGetChar(&it); jsvStringIteratorNext(&it); if (ch=='{') brackets++; if (ch=='}') { brackets--; if (!brackets) break; } jsvStringIteratorAppend(&eit, ch); } jsvStringIteratorFree(&eit); JsVar *result = jspEvaluateExpressionVar(expr); jsvUnLock(expr); result = jsvAsString(result, true); jsvStringIteratorAppendString(&dit, result, 0); jsvUnLock(result); } else { jsvStringIteratorAppend(&dit, '$'); } } else { jsvStringIteratorAppend(&dit, ch); jsvStringIteratorNext(&it); } } jsvStringIteratorFree(&it); jsvStringIteratorFree(&dit); } jsvUnLock(template); } JSP_ASSERT_MATCH(LEX_TEMPLATE_LITERAL); return a; } #endif NO_INLINE JsVar *jspeAddNamedFunctionParameter(JsVar *funcVar, JsVar *name) { if (!funcVar) funcVar = jsvNewWithFlags(JSV_FUNCTION); char buf[JSLEX_MAX_TOKEN_LENGTH+1]; buf[0] = '\xFF'; jsvGetString(name, &buf[1], JSLEX_MAX_TOKEN_LENGTH); JsVar *param = jsvAddNamedChild(funcVar, 0, buf); jsvMakeFunctionParameter(param); jsvUnLock(param); return funcVar; } #ifndef SAVE_ON_FLASH // parse an arrow function NO_INLINE JsVar *jspeArrowFunction(JsVar *funcVar, JsVar *a) { assert(!a || jsvIsName(a)); JSP_ASSERT_MATCH(LEX_ARROW_FUNCTION); funcVar = jspeAddNamedFunctionParameter(funcVar, a); bool expressionOnly = lex->tk!='{'; jspeFunctionDefinitionInternal(funcVar, expressionOnly); if (execInfo.thisVar) { jsvObjectSetChild(funcVar, JSPARSE_FUNCTION_THIS_NAME, execInfo.thisVar); } return funcVar; } // parse expressions with commas, maybe followed by an arrow function (bracket already matched) NO_INLINE JsVar *jspeExpressionOrArrowFunction() { JsVar *a = 0; JsVar *funcVar = 0; bool allNames = true; while (lex->tk!=')' && !JSP_SHOULDNT_PARSE) { if (allNames && a) { // we never get here if this isn't a name and a string funcVar = jspeAddNamedFunctionParameter(funcVar, a); } jsvUnLock(a); a = jspeAssignmentExpression(); if (!(jsvIsName(a) && jsvIsString(a))) allNames = false; if (lex->tk!=')') JSP_MATCH_WITH_CLEANUP_AND_RETURN(',', jsvUnLock2(a,funcVar), 0); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock2(a,funcVar), 0); // if arrow is found, create a function if (allNames && lex->tk==LEX_ARROW_FUNCTION) { funcVar = jspeArrowFunction(funcVar, a); jsvUnLock(a); return funcVar; } else { jsvUnLock(funcVar); return a; } } /// Parse an ES6 class, expects LEX_R_CLASS already parsed NO_INLINE JsVar *jspeClassDefinition(bool parseNamedClass) { JsVar *classFunction = 0; JsVar *classPrototype = 0; JsVar *classInternalName = 0; bool actuallyCreateClass = JSP_SHOULD_EXECUTE; if (actuallyCreateClass) classFunction = jsvNewWithFlags(JSV_FUNCTION); if (parseNamedClass && lex->tk==LEX_ID) { if (classFunction) classInternalName = jslGetTokenValueAsVar(lex); JSP_ASSERT_MATCH(LEX_ID); } if (classFunction) { JsVar *prototypeName = jsvFindChildFromString(classFunction, JSPARSE_PROTOTYPE_VAR, true); jspEnsureIsPrototype(classFunction, prototypeName); // make sure it's an object classPrototype = jsvSkipName(prototypeName); jsvUnLock(prototypeName); } if (lex->tk==LEX_R_EXTENDS) { JSP_ASSERT_MATCH(LEX_R_EXTENDS); JsVar *extendsFrom = actuallyCreateClass ? jsvSkipNameAndUnLock(jspGetNamedVariable(jslGetTokenValueAsString(lex))) : 0; JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock4(extendsFrom,classFunction,classInternalName,classPrototype),0); if (classPrototype) { if (jsvIsFunction(extendsFrom)) { jsvObjectSetChild(classPrototype, JSPARSE_INHERITS_VAR, extendsFrom); // link in default constructor if ours isn't supplied jsvObjectSetChildAndUnLock(classFunction, JSPARSE_FUNCTION_CODE_NAME, jsvNewFromString("if(this.__proto__.__proto__)this.__proto__.__proto__.apply(this,arguments)")); } else jsExceptionHere(JSET_SYNTAXERROR, "'extends' argument should be a function, got %t", extendsFrom); } jsvUnLock(extendsFrom); } JSP_MATCH_WITH_CLEANUP_AND_RETURN('{',jsvUnLock3(classFunction,classInternalName,classPrototype),0); while ((lex->tk==LEX_ID || lex->tk==LEX_R_STATIC) && !jspIsInterrupted()) { bool isStatic = lex->tk==LEX_R_STATIC; if (isStatic) JSP_ASSERT_MATCH(LEX_R_STATIC); JsVar *funcName = jslGetTokenValueAsVar(lex); JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock3(classFunction,classInternalName,classPrototype),0); JsVar *method = jspeFunctionDefinition(false); if (classFunction && classPrototype) { if (jsvIsStringEqual(funcName, "get") || jsvIsStringEqual(funcName, "set")) { jsExceptionHere(JSET_SYNTAXERROR, "'get' and 'set' and not supported in Espruino"); } else if (jsvIsStringEqual(funcName, "constructor")) { jswrap_function_replaceWith(classFunction, method); } else { funcName = jsvMakeIntoVariableName(funcName, 0); jsvSetValueOfName(funcName, method); jsvAddName(isStatic ? classFunction : classPrototype, funcName); } } jsvUnLock2(method,funcName); } jsvUnLock(classPrototype); // If we had a name, add it to the end (or it gets confused with the constructor arguments) if (classInternalName) jsvObjectSetChildAndUnLock(classFunction, JSPARSE_FUNCTION_NAME_NAME, classInternalName); JSP_MATCH_WITH_CLEANUP_AND_RETURN('}',jsvUnLock(classFunction),0); return classFunction; } #endif NO_INLINE JsVar *jspeFactor() { if (lex->tk==LEX_ID) { JsVar *a = jspGetNamedVariable(jslGetTokenValueAsString(lex)); JSP_ASSERT_MATCH(LEX_ID); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_TEMPLATE_LITERAL) jsExceptionHere(JSET_SYNTAXERROR, "Tagged template literals not supported"); else if (lex->tk==LEX_ARROW_FUNCTION && jsvIsName(a)) { JsVar *funcVar = jspeArrowFunction(0,a); jsvUnLock(a); a=funcVar; } #endif return a; } else if (lex->tk==LEX_INT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromLongInteger(stringToInt(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_INT); return v; } else if (lex->tk==LEX_FLOAT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromFloat(stringToFloat(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_FLOAT); return v; } else if (lex->tk=='(') { JSP_ASSERT_MATCH('('); if (!jspCheckStackPosition()) return 0; #ifdef SAVE_ON_FLASH // Just parse a normal expression (which can include commas) JsVar *a = jspeExpression(); if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN(')',a); return a; #else return jspeExpressionOrArrowFunction(); #endif } else if (lex->tk==LEX_R_TRUE) { JSP_ASSERT_MATCH(LEX_R_TRUE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0; } else if (lex->tk==LEX_R_FALSE) { JSP_ASSERT_MATCH(LEX_R_FALSE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0; } else if (lex->tk==LEX_R_NULL) { JSP_ASSERT_MATCH(LEX_R_NULL); return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0; } else if (lex->tk==LEX_R_UNDEFINED) { JSP_ASSERT_MATCH(LEX_R_UNDEFINED); return 0; } else if (lex->tk==LEX_STR) { JsVar *a = 0; if (JSP_SHOULD_EXECUTE) a = jslGetTokenValueAsVar(lex); JSP_ASSERT_MATCH(LEX_STR); return a; #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_TEMPLATE_LITERAL) { return jspeTemplateLiteral(); #endif } else if (lex->tk==LEX_REGEX) { JsVar *a = 0; #ifdef SAVE_ON_FLASH jsExceptionHere(JSET_SYNTAXERROR, "RegEx are not supported in this version of Espruino\n"); #else JsVar *regex = jslGetTokenValueAsVar(lex); size_t regexEnd = 0, regexLen = 0; JsvStringIterator it; jsvStringIteratorNew(&it, regex, 0); while (jsvStringIteratorHasChar(&it)) { regexLen++; if (jsvStringIteratorGetChar(&it)=='/') regexEnd = regexLen; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); JsVar *flags = 0; if (regexEnd < regexLen) flags = jsvNewFromStringVar(regex, regexEnd, JSVAPPENDSTRINGVAR_MAXLENGTH); JsVar *regexSource = jsvNewFromStringVar(regex, 1, regexEnd-2); a = jswrap_regexp_constructor(regexSource, flags); jsvUnLock3(regex, flags, regexSource); #endif JSP_ASSERT_MATCH(LEX_REGEX); return a; } else if (lex->tk=='{') { if (!jspCheckStackPosition()) return 0; return jspeFactorObject(); } else if (lex->tk=='[') { if (!jspCheckStackPosition()) return 0; return jspeFactorArray(); } else if (lex->tk==LEX_R_FUNCTION) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_FUNCTION); return jspeFunctionDefinition(true); #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_R_CLASS) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_CLASS); return jspeClassDefinition(true); } else if (lex->tk==LEX_R_SUPER) { JSP_ASSERT_MATCH(LEX_R_SUPER); /* This is kind of nasty, since super appears to do three different things. * In the constructor it references the extended class's constructor * in a method it references the constructor's prototype. * in a static method it references the extended class's constructor (but this is different) */ if (jsvIsObject(execInfo.thisVar)) { // 'this' is an object - must be calling a normal method JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_INHERITS_VAR, 0); // if we're in a method, get __proto__ first JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; // still in method, get __proto__.__proto__ jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } if (lex->tk=='(') return proto2; // eg. used in a constructor // But if we're doing something else - eg '.' or '[' then it needs to reference the prototype JsVar *proto3 = jsvIsFunction(proto2) ? jsvObjectGetChild(proto2, JSPARSE_PROTOTYPE_VAR, 0) : 0; jsvUnLock(proto2); return proto3; } else if (jsvIsFunction(execInfo.thisVar)) { // 'this' is a function - must be calling a static method JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_PROTOTYPE_VAR, 0); JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } return proto2; } jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; #endif } else if (lex->tk==LEX_R_THIS) { JSP_ASSERT_MATCH(LEX_R_THIS); return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.root ); } else if (lex->tk==LEX_R_DELETE) { if (!jspCheckStackPosition()) return 0; return jspeFactorDelete(); } else if (lex->tk==LEX_R_TYPEOF) { if (!jspCheckStackPosition()) return 0; return jspeFactorTypeOf(); } else if (lex->tk==LEX_R_VOID) { JSP_ASSERT_MATCH(LEX_R_VOID); jsvUnLock(jspeUnaryExpression()); return 0; } JSP_MATCH(LEX_EOF); jsExceptionHere(JSET_SYNTAXERROR, "Unexpected end of Input\n"); return 0; } NO_INLINE JsVar *__jspePostfixExpression(JsVar *a) { while (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *oldValue = jsvAsNumberAndUnLock(jsvSkipName(a)); // keep the old value (but convert to number) JsVar *res = jsvMathsOpSkipNames(oldValue, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); // in-place add/subtract jspReplaceWith(a, res); jsvUnLock(res); // but then use the old value jsvUnLock(a); a = oldValue; } } return a; } NO_INLINE JsVar *jspePostfixExpression() { JsVar *a; // TODO: should be in jspeUnaryExpression if (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); a = jspePostfixExpression(); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); // in-place add/subtract jspReplaceWith(a, res); jsvUnLock(res); } } else a = jspeFactorFunctionCall(); return __jspePostfixExpression(a); } NO_INLINE JsVar *jspeUnaryExpression() { if (lex->tk=='!' || lex->tk=='~' || lex->tk=='-' || lex->tk=='+') { short tk = lex->tk; JSP_ASSERT_MATCH(tk); if (!JSP_SHOULD_EXECUTE) { return jspeUnaryExpression(); } if (tk=='!') { // logical not return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='~') { // bitwise not return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='-') { // unary minus return jsvNegateAndUnLock(jspeUnaryExpression()); // names already skipped } else if (tk=='+') { // unary plus (convert to number) JsVar *v = jsvSkipNameAndUnLock(jspeUnaryExpression()); JsVar *r = jsvAsNumber(v); // names already skipped jsvUnLock(v); return r; } assert(0); return 0; } else return jspePostfixExpression(); } // Get the precedence of a BinaryExpression - or return 0 if not one unsigned int jspeGetBinaryExpressionPrecedence(int op) { switch (op) { case LEX_OROR: return 1; break; case LEX_ANDAND: return 2; break; case '|' : return 3; break; case '^' : return 4; break; case '&' : return 5; break; case LEX_EQUAL: case LEX_NEQUAL: case LEX_TYPEEQUAL: case LEX_NTYPEEQUAL: return 6; case LEX_LEQUAL: case LEX_GEQUAL: case '<': case '>': case LEX_R_INSTANCEOF: return 7; case LEX_R_IN: return (execInfo.execute&EXEC_FOR_INIT)?0:7; case LEX_LSHIFT: case LEX_RSHIFT: case LEX_RSHIFTUNSIGNED: return 8; case '+': case '-': return 9; case '*': case '/': case '%': return 10; default: return 0; } } NO_INLINE JsVar *__jspeBinaryExpression(JsVar *a, unsigned int lastPrecedence) { /* This one's a bit strange. Basically all the ops have their own precedence, it's not * like & and | share the same precedence. We don't want to recurse for each one, * so instead we do this. * * We deal with an expression in recursion ONLY if it's of higher precedence * than the current one, otherwise we stick in the while loop. */ unsigned int precedence = jspeGetBinaryExpressionPrecedence(lex->tk); while (precedence && precedence>lastPrecedence) { int op = lex->tk; JSP_ASSERT_MATCH(op); // if we have short-circuit ops, then if we know the outcome // we don't bother to execute the other op. Even if not // we need to tell mathsOp it's an & or | if (op==LEX_ANDAND || op==LEX_OROR) { bool aValue = jsvGetBoolAndUnLock(jsvSkipName(a)); if ((!aValue && op==LEX_ANDAND) || (aValue && op==LEX_OROR)) { // use first argument (A) JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(__jspeBinaryExpression(jspeUnaryExpression(),precedence)); JSP_RESTORE_EXECUTE(); } else { // use second argument (B) jsvUnLock(a); a = __jspeBinaryExpression(jspeUnaryExpression(),precedence); } } else { // else it's a more 'normal' logical expression - just use Maths JsVar *b = __jspeBinaryExpression(jspeUnaryExpression(),precedence); if (JSP_SHOULD_EXECUTE) { if (op==LEX_R_IN) { JsVar *av = jsvSkipName(a); // needle JsVar *bv = jsvSkipName(b); // haystack if (jsvIsArray(bv) || jsvIsObject(bv)) { // search keys, NOT values av = jsvAsArrayIndexAndUnLock(av); JsVar *varFound = jspGetVarNamedField( bv, av, true); jsvUnLock(a); a = jsvNewFromBool(varFound!=0); jsvUnLock(varFound); } else {// else it will be undefined jsExceptionHere(JSET_ERROR, "Cannot use 'in' operator to search a %t", bv); jsvUnLock(a); a = 0; } jsvUnLock2(av, bv); } else if (op==LEX_R_INSTANCEOF) { bool inst = false; JsVar *av = jsvSkipName(a); JsVar *bv = jsvSkipName(b); if (!jsvIsFunction(bv)) { jsExceptionHere(JSET_ERROR, "Expecting a function on RHS in instanceof check, got %t", bv); } else { if (jsvIsObject(av) || jsvIsFunction(av)) { JsVar *bproto = jspGetNamedField(bv, JSPARSE_PROTOTYPE_VAR, false); JsVar *proto = jsvObjectGetChild(av, JSPARSE_INHERITS_VAR, 0); while (proto) { if (proto == bproto) inst=true; // search prototype chain JsVar *childProto = jsvObjectGetChild(proto, JSPARSE_INHERITS_VAR, 0); jsvUnLock(proto); proto = childProto; } if (jspIsConstructor(bv, "Object")) inst = true; jsvUnLock(bproto); } if (!inst) { const char *name = jswGetBasicObjectName(av); if (name) { inst = jspIsConstructor(bv, name); } // Hack for built-ins that should also be instances of Object if (!inst && (jsvIsArray(av) || jsvIsArrayBuffer(av)) && jspIsConstructor(bv, "Object")) inst = true; } } jsvUnLock3(av, bv, a); a = jsvNewFromBool(inst); } else { // --------------------------------------------- NORMAL JsVar *res = jsvMathsOpSkipNames(a, b, op); jsvUnLock(a); a = res; } } jsvUnLock(b); } precedence = jspeGetBinaryExpressionPrecedence(lex->tk); } return a; } JsVar *jspeBinaryExpression() { return __jspeBinaryExpression(jspeUnaryExpression(),0); } NO_INLINE JsVar *__jspeConditionalExpression(JsVar *lhs) { if (lex->tk=='?') { JSP_ASSERT_MATCH('?'); if (!JSP_SHOULD_EXECUTE) { // just let lhs pass through jsvUnLock(jspeAssignmentExpression()); JSP_MATCH(':'); jsvUnLock(jspeAssignmentExpression()); } else { bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs)); jsvUnLock(lhs); if (first) { lhs = jspeAssignmentExpression(); JSP_MATCH(':'); JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); } else { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); JSP_MATCH(':'); lhs = jspeAssignmentExpression(); } } } return lhs; } JsVar *jspeConditionalExpression() { return __jspeConditionalExpression(jspeBinaryExpression()); } NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { /* If we're assigning to this and we don't have a parent, * add it to the symbol table root */ if (!jsvGetRefs(lhs) && jsvIsName(lhs)) { if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs)) jsvAddName(execInfo.root, lhs); } jspReplaceWith(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jspReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; } JsVar *jspeAssignmentExpression() { return __jspeAssignmentExpression(jspeConditionalExpression()); } // ',' is allowed to add multiple expressions, this is not allowed in jspeAssignmentExpression NO_INLINE JsVar *jspeExpression() { while (!JSP_SHOULDNT_PARSE) { JsVar *a = jspeAssignmentExpression(); if (lex->tk!=',') return a; // if we get a comma, we just forget this data and parse the next bit... jsvUnLock(a); JSP_ASSERT_MATCH(','); } return 0; } /** Parse a block `{ ... }` but assume brackets are already parsed */ NO_INLINE void jspeBlockNoBrackets() { if (JSP_SHOULD_EXECUTE) { while (lex->tk && lex->tk!='}') { jsvUnLock(jspeStatement()); if (JSP_HAS_ERROR) { if (lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) { execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED); JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); if (stackTrace) { jsvAppendPrintf(stackTrace, "at "); jspAppendStackTrace(stackTrace); jsvUnLock(stackTrace); } } } if (JSP_SHOULDNT_PARSE) return; } } else { // fast skip of blocks int brackets = 0; while (lex->tk && (brackets || lex->tk != '}')) { if (lex->tk == '{') brackets++; if (lex->tk == '}') brackets--; JSP_ASSERT_MATCH(lex->tk); } } return; } /** Parse a block `{ ... }` */ NO_INLINE void jspeBlock() { JSP_MATCH_WITH_RETURN('{',); jspeBlockNoBrackets(); if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN('}',); return; } NO_INLINE JsVar *jspeBlockOrStatement() { if (lex->tk=='{') { jspeBlock(); return 0; } else { JsVar *v = jspeStatement(); if (lex->tk==';') JSP_ASSERT_MATCH(';'); return v; } } /** Parse using current lexer until we hit the end of * input or there was some problem. */ NO_INLINE JsVar *jspParse() { JsVar *v = 0; while (!JSP_SHOULDNT_PARSE && lex->tk != LEX_EOF) { jsvUnLock(v); v = jspeBlockOrStatement(); } return v; } NO_INLINE JsVar *jspeStatementVar() { JsVar *lastDefined = 0; /* variable creation. TODO - we need a better way of parsing the left * hand side. Maybe just have a flag called can_create_var that we * set and then we parse as if we're doing a normal equals.*/ assert(lex->tk==LEX_R_VAR || lex->tk==LEX_R_LET || lex->tk==LEX_R_CONST); jslGetNextToken(); ///TODO: Correctly implement CONST and LET - we just treat them like 'var' at the moment bool hasComma = true; // for first time in loop while (hasComma && lex->tk == LEX_ID && !jspIsInterrupted()) { JsVar *a = 0; if (JSP_SHOULD_EXECUTE) { a = jspeiFindOnTop(jslGetTokenValueAsString(lex), true); if (!a) { // out of memory jspSetError(false); return lastDefined; } } JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(a), lastDefined); // sort out initialiser if (lex->tk == '=') { JsVar *var; JSP_MATCH_WITH_CLEANUP_AND_RETURN('=', jsvUnLock(a), lastDefined); var = jsvSkipNameAndUnLock(jspeAssignmentExpression()); if (JSP_SHOULD_EXECUTE) jspReplaceWith(a, var); jsvUnLock(var); } jsvUnLock(lastDefined); lastDefined = a; hasComma = lex->tk == ','; if (hasComma) JSP_MATCH_WITH_RETURN(',', lastDefined); } return lastDefined; } NO_INLINE JsVar *jspeStatementIf() { bool cond; JsVar *var, *result = 0; JSP_ASSERT_MATCH(LEX_R_IF); JSP_MATCH('('); var = jspeExpression(); if (JSP_SHOULDNT_PARSE) return var; JSP_MATCH(')'); cond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(var)); jsvUnLock(var); JSP_SAVE_EXECUTE(); if (!cond) jspSetNoExecute(); JsVar *a = jspeBlockOrStatement(); if (!cond) { jsvUnLock(a); JSP_RESTORE_EXECUTE(); } else { result = a; } if (lex->tk==LEX_R_ELSE) { JSP_ASSERT_MATCH(LEX_R_ELSE); JSP_SAVE_EXECUTE(); if (cond) jspSetNoExecute(); JsVar *a = jspeBlockOrStatement(); if (cond) { jsvUnLock(a); JSP_RESTORE_EXECUTE(); } else { result = a; } } return result; } NO_INLINE JsVar *jspeStatementSwitch() { JSP_ASSERT_MATCH(LEX_R_SWITCH); JSP_MATCH('('); JsVar *switchOn = jspeExpression(); JSP_SAVE_EXECUTE(); bool execute = JSP_SHOULD_EXECUTE; JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock(switchOn), 0); // shortcut if not executing... if (!execute) { jsvUnLock(switchOn); jspeBlock(); return 0; } JSP_MATCH_WITH_CLEANUP_AND_RETURN('{', jsvUnLock(switchOn), 0); bool executeDefault = true; if (execute) execInfo.execute=EXEC_NO|EXEC_IN_SWITCH; while (lex->tk==LEX_R_CASE) { JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_CASE, jsvUnLock(switchOn), 0); JsExecFlags oldFlags = execInfo.execute; if (execute) execInfo.execute=EXEC_YES|EXEC_IN_SWITCH; JsVar *test = jspeAssignmentExpression(); execInfo.execute = oldFlags|EXEC_IN_SWITCH;; JSP_MATCH_WITH_CLEANUP_AND_RETURN(':', jsvUnLock2(switchOn, test), 0); bool cond = false; if (execute) cond = jsvGetBoolAndUnLock(jsvMathsOpSkipNames(switchOn, test, LEX_TYPEEQUAL)); if (cond) executeDefault = false; jsvUnLock(test); if (cond && (execInfo.execute&EXEC_RUN_MASK)==EXEC_NO) execInfo.execute=EXEC_YES|EXEC_IN_SWITCH; while (!JSP_SHOULDNT_PARSE && lex->tk!=LEX_EOF && lex->tk!=LEX_R_CASE && lex->tk!=LEX_R_DEFAULT && lex->tk!='}') jsvUnLock(jspeBlockOrStatement()); oldExecute |= execInfo.execute & (EXEC_ERROR_MASK|EXEC_RETURN); // copy across any errors/exceptions/returns } jsvUnLock(switchOn); if (execute && (execInfo.execute&EXEC_RUN_MASK)==EXEC_BREAK) { execInfo.execute=EXEC_YES|EXEC_IN_SWITCH; } else { executeDefault = true; } JSP_RESTORE_EXECUTE(); if (lex->tk==LEX_R_DEFAULT) { JSP_ASSERT_MATCH(LEX_R_DEFAULT); JSP_MATCH(':'); JSP_SAVE_EXECUTE(); if (!executeDefault) jspSetNoExecute(); else execInfo.execute |= EXEC_IN_SWITCH; while (!JSP_SHOULDNT_PARSE && lex->tk!=LEX_EOF && lex->tk!='}') jsvUnLock(jspeBlockOrStatement()); oldExecute |= execInfo.execute & (EXEC_ERROR_MASK|EXEC_RETURN); // copy across any errors/exceptions/returns execInfo.execute = execInfo.execute & (JsExecFlags)~EXEC_BREAK; JSP_RESTORE_EXECUTE(); } JSP_MATCH('}'); return 0; } NO_INLINE JsVar *jspeStatementDoOrWhile(bool isWhile) { #ifdef JSPARSE_MAX_LOOP_ITERATIONS int loopCount = JSPARSE_MAX_LOOP_ITERATIONS; #endif JsVar *cond; bool loopCond = true; // true for do...while loops bool hasHadBreak = false; JslCharPos whileCondStart; // We do repetition by pulling out the string representing our statement // there's definitely some opportunity for optimisation here JSP_ASSERT_MATCH(isWhile ? LEX_R_WHILE : LEX_R_DO); bool wasInLoop = (execInfo.execute&EXEC_IN_LOOP)!=0; if (isWhile) { // while loop JSP_MATCH('('); whileCondStart = jslCharPosClone(&lex->tokenStart); cond = jspeAssignmentExpression(); loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond)); jsvUnLock(cond); JSP_MATCH_WITH_CLEANUP_AND_RETURN(')',jslCharPosFree(&whileCondStart);,0); } JslCharPos whileBodyStart = jslCharPosClone(&lex->tokenStart); JSP_SAVE_EXECUTE(); // actually try and execute first bit of while loop (we'll do the rest in the actual loop later) if (!loopCond) jspSetNoExecute(); execInfo.execute |= EXEC_IN_LOOP; jsvUnLock(jspeBlockOrStatement()); if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP; if (execInfo.execute & EXEC_CONTINUE) execInfo.execute = EXEC_YES; else if (execInfo.execute & EXEC_BREAK) { execInfo.execute = EXEC_YES; hasHadBreak = true; // fail loop condition, so we exit } if (!loopCond) JSP_RESTORE_EXECUTE(); if (!isWhile) { // do..while loop JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_WHILE,jslCharPosFree(&whileBodyStart);,0); JSP_MATCH_WITH_CLEANUP_AND_RETURN('(',jslCharPosFree(&whileBodyStart);if (isWhile)jslCharPosFree(&whileCondStart);,0); whileCondStart = jslCharPosClone(&lex->tokenStart); cond = jspeAssignmentExpression(); loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond)); jsvUnLock(cond); JSP_MATCH_WITH_CLEANUP_AND_RETURN(')',jslCharPosFree(&whileBodyStart);jslCharPosFree(&whileCondStart);,0); } JslCharPos whileBodyEnd; whileBodyEnd = jslCharPosClone(&lex->tokenStart); while (!hasHadBreak && loopCond #ifdef JSPARSE_MAX_LOOP_ITERATIONS && loopCount-->0 #endif ) { jslSeekToP(&whileCondStart); cond = jspeAssignmentExpression(); loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond)); jsvUnLock(cond); if (loopCond) { jslSeekToP(&whileBodyStart); execInfo.execute |= EXEC_IN_LOOP; jspDebuggerLoopIfCtrlC(); jsvUnLock(jspeBlockOrStatement()); if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP; if (execInfo.execute & EXEC_CONTINUE) execInfo.execute = EXEC_YES; else if (execInfo.execute & EXEC_BREAK) { execInfo.execute = EXEC_YES; hasHadBreak = true; } } } jslSeekToP(&whileBodyEnd); jslCharPosFree(&whileCondStart); jslCharPosFree(&whileBodyStart); jslCharPosFree(&whileBodyEnd); #ifdef JSPARSE_MAX_LOOP_ITERATIONS if (loopCount<=0) { jsExceptionHere(JSET_ERROR, "WHILE Loop exceeded the maximum number of iterations (" STRINGIFY(JSPARSE_MAX_LOOP_ITERATIONS) ")"); } #endif return 0; } NO_INLINE JsVar *jspeStatementFor() { JSP_ASSERT_MATCH(LEX_R_FOR); JSP_MATCH('('); bool wasInLoop = (execInfo.execute&EXEC_IN_LOOP)!=0; execInfo.execute |= EXEC_FOR_INIT; // initialisation JsVar *forStatement = 0; // we could have 'for (;;)' - so don't munch up our semicolon if that's all we have if (lex->tk != ';') forStatement = jspeStatement(); if (jspIsInterrupted()) { jsvUnLock(forStatement); return 0; } execInfo.execute &= (JsExecFlags)~EXEC_FOR_INIT; if (lex->tk == LEX_R_IN) { // for (i in array) // where i = jsvUnLock(forStatement); if (JSP_SHOULD_EXECUTE && !jsvIsName(forStatement)) { jsvUnLock(forStatement); jsExceptionHere(JSET_ERROR, "FOR a IN b - 'a' must be a variable name, not %t", forStatement); return 0; } bool addedIteratorToScope = false; if (JSP_SHOULD_EXECUTE && !jsvGetRefs(forStatement)) { // if the variable did not exist, add it to the scope addedIteratorToScope = true; jsvAddName(execInfo.root, forStatement); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_IN, jsvUnLock(forStatement), 0); JsVar *array = jsvSkipNameAndUnLock(jspeExpression()); JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock2(forStatement, array), 0); JslCharPos forBodyStart = jslCharPosClone(&lex->tokenStart); JSP_SAVE_EXECUTE(); jspSetNoExecute(); execInfo.execute |= EXEC_IN_LOOP; jsvUnLock(jspeBlockOrStatement()); JslCharPos forBodyEnd = jslCharPosClone(&lex->tokenStart); if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP; JSP_RESTORE_EXECUTE(); if (JSP_SHOULD_EXECUTE) { if (jsvIsIterable(array)) { JsvIsInternalChecker checkerFunction = jsvGetInternalFunctionCheckerFor(array); JsVar *foundPrototype = 0; JsvIterator it; jsvIteratorNew(&it, array, JSIF_DEFINED_ARRAY_ElEMENTS); bool hasHadBreak = false; while (JSP_SHOULD_EXECUTE && jsvIteratorHasElement(&it) && !hasHadBreak) { JsVar *loopIndexVar = jsvIteratorGetKey(&it); bool ignore = false; if (checkerFunction && checkerFunction(loopIndexVar)) { ignore = true; if (jsvIsString(loopIndexVar) && jsvIsStringEqual(loopIndexVar, JSPARSE_INHERITS_VAR)) foundPrototype = jsvSkipName(loopIndexVar); } if (!ignore) { JsVar *indexValue = jsvIsName(loopIndexVar) ? jsvCopyNameOnly(loopIndexVar, false/*no copy children*/, false/*not a name*/) : loopIndexVar; if (indexValue) { // could be out of memory assert(!jsvIsName(indexValue) && jsvGetRefs(indexValue)==0); jsvSetValueOfName(forStatement, indexValue); if (indexValue!=loopIndexVar) jsvUnLock(indexValue); jsvIteratorNext(&it); jslSeekToP(&forBodyStart); execInfo.execute |= EXEC_IN_LOOP; jspDebuggerLoopIfCtrlC(); jsvUnLock(jspeBlockOrStatement()); if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP; if (execInfo.execute & EXEC_CONTINUE) execInfo.execute = EXEC_YES; else if (execInfo.execute & EXEC_BREAK) { execInfo.execute = EXEC_YES; hasHadBreak = true; } } } else jsvIteratorNext(&it); jsvUnLock(loopIndexVar); if (!jsvIteratorHasElement(&it) && foundPrototype) { jsvIteratorFree(&it); jsvIteratorNew(&it, foundPrototype, JSIF_DEFINED_ARRAY_ElEMENTS); jsvUnLock(foundPrototype); foundPrototype = 0; } } assert(!foundPrototype); jsvIteratorFree(&it); } else if (!jsvIsUndefined(array)) { jsExceptionHere(JSET_ERROR, "FOR loop can only iterate over Arrays, Strings or Objects, not %t", array); } } jslSeekToP(&forBodyEnd); jslCharPosFree(&forBodyStart); jslCharPosFree(&forBodyEnd); if (addedIteratorToScope) { jsvRemoveChild(execInfo.root, forStatement); } jsvUnLock2(forStatement, array); } else { // ----------------------------------------------- NORMAL FOR LOOP #ifdef JSPARSE_MAX_LOOP_ITERATIONS int loopCount = JSPARSE_MAX_LOOP_ITERATIONS; #endif bool loopCond = true; bool hasHadBreak = false; jsvUnLock(forStatement); JSP_MATCH(';'); JslCharPos forCondStart = jslCharPosClone(&lex->tokenStart); if (lex->tk != ';') { JsVar *cond = jspeAssignmentExpression(); // condition loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond)); jsvUnLock(cond); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(';',jslCharPosFree(&forCondStart);,0); JslCharPos forIterStart = jslCharPosClone(&lex->tokenStart); if (lex->tk != ')') { // we could have 'for (;;)' JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeExpression()); // iterator JSP_RESTORE_EXECUTE(); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(')',jslCharPosFree(&forCondStart);jslCharPosFree(&forIterStart);,0); JslCharPos forBodyStart = jslCharPosClone(&lex->tokenStart); // actual for body JSP_SAVE_EXECUTE(); if (!loopCond) jspSetNoExecute(); execInfo.execute |= EXEC_IN_LOOP; jsvUnLock(jspeBlockOrStatement()); JslCharPos forBodyEnd = jslCharPosClone(&lex->tokenStart); if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP; if (loopCond || !JSP_SHOULD_EXECUTE) { if (execInfo.execute & EXEC_CONTINUE) execInfo.execute = EXEC_YES; else if (execInfo.execute & EXEC_BREAK) { execInfo.execute = EXEC_YES; hasHadBreak = true; } } if (!loopCond) JSP_RESTORE_EXECUTE(); if (loopCond) { jslSeekToP(&forIterStart); if (lex->tk != ')') jsvUnLock(jspeExpression()); } while (!hasHadBreak && JSP_SHOULD_EXECUTE && loopCond #ifdef JSPARSE_MAX_LOOP_ITERATIONS && loopCount-->0 #endif ) { jslSeekToP(&forCondStart); ; if (lex->tk == ';') { loopCond = true; } else { JsVar *cond = jspeAssignmentExpression(); loopCond = jsvGetBoolAndUnLock(jsvSkipName(cond)); jsvUnLock(cond); } if (JSP_SHOULD_EXECUTE && loopCond) { jslSeekToP(&forBodyStart); execInfo.execute |= EXEC_IN_LOOP; jspDebuggerLoopIfCtrlC(); jsvUnLock(jspeBlockOrStatement()); if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP; if (execInfo.execute & EXEC_CONTINUE) execInfo.execute = EXEC_YES; else if (execInfo.execute & EXEC_BREAK) { execInfo.execute = EXEC_YES; hasHadBreak = true; } } if (JSP_SHOULD_EXECUTE && loopCond && !hasHadBreak) { jslSeekToP(&forIterStart); if (lex->tk != ')') jsvUnLock(jspeExpression()); } } jslSeekToP(&forBodyEnd); jslCharPosFree(&forCondStart); jslCharPosFree(&forIterStart); jslCharPosFree(&forBodyStart); jslCharPosFree(&forBodyEnd); #ifdef JSPARSE_MAX_LOOP_ITERATIONS if (loopCount<=0) { jsExceptionHere(JSET_ERROR, "FOR Loop exceeded the maximum number of iterations ("STRINGIFY(JSPARSE_MAX_LOOP_ITERATIONS)")"); } #endif } return 0; } NO_INLINE JsVar *jspeStatementTry() { // execute the try block JSP_ASSERT_MATCH(LEX_R_TRY); bool shouldExecuteBefore = JSP_SHOULD_EXECUTE; jspeBlock(); bool hadException = shouldExecuteBefore && ((execInfo.execute & EXEC_EXCEPTION)!=0); bool hadCatch = false; if (lex->tk == LEX_R_CATCH) { JSP_ASSERT_MATCH(LEX_R_CATCH); hadCatch = true; JSP_MATCH('('); JsVar *scope = 0; JsVar *exceptionVar = 0; if (hadException) { scope = jsvNewObject(); if (scope) exceptionVar = jsvFindChildFromString(scope, jslGetTokenValueAsString(lex), true); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock2(scope,exceptionVar),0); JSP_MATCH_WITH_CLEANUP_AND_RETURN(')',jsvUnLock2(scope,exceptionVar),0); if (exceptionVar) { // set the exception var up properly JsVar *exception = jspGetException(); if (exception) { jsvSetValueOfName(exceptionVar, exception); jsvUnLock(exception); } // Now clear the exception flag (it's handled - we hope!) execInfo.execute = execInfo.execute & (JsExecFlags)~(EXEC_EXCEPTION|EXEC_ERROR_LINE_REPORTED); jsvUnLock(exceptionVar); } if (shouldExecuteBefore && !hadException) { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jspeBlock(); JSP_RESTORE_EXECUTE(); } else if (scope) { if (jspeiAddScope(scope)) { jspeBlock(); jspeiRemoveScope(); } } jsvUnLock(scope); } if (lex->tk == LEX_R_FINALLY || (!hadCatch && ((execInfo.execute&(EXEC_ERROR|EXEC_INTERRUPTED))==0))) { JSP_MATCH(LEX_R_FINALLY); // clear the exception flag - but only momentarily! if (hadException) execInfo.execute = execInfo.execute & (JsExecFlags)~EXEC_EXCEPTION; jspeBlock(); // put the flag back! if (hadException && !hadCatch) execInfo.execute = execInfo.execute | EXEC_EXCEPTION; } return 0; } NO_INLINE JsVar *jspeStatementReturn() { JsVar *result = 0; JSP_ASSERT_MATCH(LEX_R_RETURN); if (lex->tk != ';' && lex->tk != '}') { // we only want the value, so skip the name if there was one result = jsvSkipNameAndUnLock(jspeExpression()); } if (JSP_SHOULD_EXECUTE) { JsVar *resultVar = jspeiFindInScopes(JSPARSE_RETURN_VAR); if (resultVar) { jspReplaceWith(resultVar, result); jsvUnLock(resultVar); execInfo.execute |= EXEC_RETURN; // Stop anything else in this function executing } else { jsExceptionHere(JSET_SYNTAXERROR, "RETURN statement, but not in a function.\n"); } } jsvUnLock(result); return 0; } NO_INLINE JsVar *jspeStatementThrow() { JsVar *result = 0; JSP_ASSERT_MATCH(LEX_R_THROW); result = jsvSkipNameAndUnLock(jspeExpression()); if (JSP_SHOULD_EXECUTE) { jspSetException(result); // Stop anything else in this function executing } jsvUnLock(result); return 0; } NO_INLINE JsVar *jspeStatementFunctionDecl(bool isClass) { JsVar *funcName = 0; JsVar *funcVar; #ifndef SAVE_ON_FLASH JSP_ASSERT_MATCH(isClass ? LEX_R_CLASS : LEX_R_FUNCTION); #else JSP_ASSERT_MATCH(LEX_R_FUNCTION); #endif bool actuallyCreateFunction = JSP_SHOULD_EXECUTE; if (actuallyCreateFunction) { funcName = jsvMakeIntoVariableName(jslGetTokenValueAsVar(lex), 0); if (!funcName) { // out of memory return 0; } } JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(funcName), 0); #ifndef SAVE_ON_FLASH funcVar = isClass ? jspeClassDefinition(false) : jspeFunctionDefinition(false); #else funcVar = jspeFunctionDefinition(false); #endif if (actuallyCreateFunction) { // find a function with the same name (or make one) // OPT: can Find* use just a JsVar that is a 'name'? JsVar *existingName = jspeiFindNameOnTop(funcName, true); JsVar *existingFunc = jsvSkipName(existingName); if (jsvIsFunction(existingFunc)) { // 'proper' replace, that keeps the original function var and swaps the children funcVar = jsvSkipNameAndUnLock(funcVar); jswrap_function_replaceWith(existingFunc, funcVar); } else { jspReplaceWith(existingName, funcVar); } jsvUnLock(funcName); funcName = existingName; jsvUnLock(existingFunc); // existingName is used - don't UnLock } jsvUnLock(funcVar); return funcName; } NO_INLINE JsVar *jspeStatement() { #ifdef USE_DEBUGGER if (execInfo.execute&EXEC_DEBUGGER_NEXT_LINE && lex->tk!=';' && JSP_SHOULD_EXECUTE) { lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it)-1; jsiDebuggerLoop(); } #endif if (lex->tk==LEX_ID || lex->tk==LEX_INT || lex->tk==LEX_FLOAT || lex->tk==LEX_STR || lex->tk==LEX_TEMPLATE_LITERAL || lex->tk==LEX_REGEX || lex->tk==LEX_R_NEW || lex->tk==LEX_R_NULL || lex->tk==LEX_R_UNDEFINED || lex->tk==LEX_R_TRUE || lex->tk==LEX_R_FALSE || lex->tk==LEX_R_THIS || lex->tk==LEX_R_DELETE || lex->tk==LEX_R_TYPEOF || lex->tk==LEX_R_VOID || lex->tk==LEX_R_SUPER || lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS || lex->tk=='!' || lex->tk=='-' || lex->tk=='+' || lex->tk=='~' || lex->tk=='[' || lex->tk=='(') { /* Execute a simple statement that only contains basic arithmetic... */ return jspeExpression(); } else if (lex->tk=='{') { /* A block of code */ jspeBlock(); return 0; } else if (lex->tk==';') { /* Empty statement - to allow things like ;;; */ JSP_ASSERT_MATCH(';'); return 0; } else if (lex->tk==LEX_R_VAR || lex->tk==LEX_R_LET || lex->tk==LEX_R_CONST) { return jspeStatementVar(); } else if (lex->tk==LEX_R_IF) { return jspeStatementIf(); } else if (lex->tk==LEX_R_DO) { return jspeStatementDoOrWhile(false); } else if (lex->tk==LEX_R_WHILE) { return jspeStatementDoOrWhile(true); } else if (lex->tk==LEX_R_FOR) { return jspeStatementFor(); } else if (lex->tk==LEX_R_TRY) { return jspeStatementTry(); } else if (lex->tk==LEX_R_RETURN) { return jspeStatementReturn(); } else if (lex->tk==LEX_R_THROW) { return jspeStatementThrow(); } else if (lex->tk==LEX_R_FUNCTION) { return jspeStatementFunctionDecl(false/* function */); #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_R_CLASS) { return jspeStatementFunctionDecl(true/* class */); #endif } else if (lex->tk==LEX_R_CONTINUE) { JSP_ASSERT_MATCH(LEX_R_CONTINUE); if (JSP_SHOULD_EXECUTE) { if (!(execInfo.execute & EXEC_IN_LOOP)) jsExceptionHere(JSET_SYNTAXERROR, "CONTINUE statement outside of FOR or WHILE loop"); else execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_CONTINUE; } } else if (lex->tk==LEX_R_BREAK) { JSP_ASSERT_MATCH(LEX_R_BREAK); if (JSP_SHOULD_EXECUTE) { if (!(execInfo.execute & (EXEC_IN_LOOP|EXEC_IN_SWITCH))) jsExceptionHere(JSET_SYNTAXERROR, "BREAK statement outside of SWITCH, FOR or WHILE loop"); else execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_BREAK; } } else if (lex->tk==LEX_R_SWITCH) { return jspeStatementSwitch(); } else if (lex->tk==LEX_R_DEBUGGER) { JSP_ASSERT_MATCH(LEX_R_DEBUGGER); #ifdef USE_DEBUGGER if (JSP_SHOULD_EXECUTE) jsiDebuggerLoop(); #endif } else JSP_MATCH(LEX_EOF); return 0; } // ----------------------------------------------------------------------------- /// Create a new built-in object that jswrapper can use to check for built-in functions JsVar *jspNewBuiltin(const char *instanceOf) { JsVar *objFunc = jswFindBuiltInFunction(0, instanceOf); if (!objFunc) return 0; // out of memory return objFunc; } /// Create a new Class of the given instance and return its prototype NO_INLINE JsVar *jspNewPrototype(const char *instanceOf) { JsVar *objFuncName = jsvFindChildFromString(execInfo.root, instanceOf, true); if (!objFuncName) // out of memory return 0; JsVar *objFunc = jsvSkipName(objFuncName); if (!objFunc) { objFunc = jspNewBuiltin(instanceOf); if (!objFunc) { // out of memory jsvUnLock(objFuncName); return 0; } // set up name jsvSetValueOfName(objFuncName, objFunc); } JsVar *prototypeName = jsvFindChildFromString(objFunc, JSPARSE_PROTOTYPE_VAR, true); jspEnsureIsPrototype(objFunc, prototypeName); // make sure it's an object jsvUnLock2(objFunc, objFuncName); return prototypeName; } /** Create a new object of the given instance and add it to root with name 'name'. * If name!=0, added to root with name, and the name is returned * If name==0, not added to root and Object itself returned */ NO_INLINE JsVar *jspNewObject(const char *name, const char *instanceOf) { JsVar *prototypeName = jspNewPrototype(instanceOf); JsVar *obj = jsvNewObject(); if (!obj) { // out of memory jsvUnLock(prototypeName); return 0; } if (name) { // If it's a device, set the device number up as the Object data // See jsiGetDeviceFromClass IOEventFlags device = jshFromDeviceString(name); if (device!=EV_NONE) { obj->varData.str[0] = 'D'; obj->varData.str[1] = 'E'; obj->varData.str[2] = 'V'; obj->varData.str[3] = (char)device; } } // add __proto__ JsVar *prototypeVar = jsvSkipName(prototypeName); jsvUnLock3(jsvAddNamedChild(obj, prototypeVar, JSPARSE_INHERITS_VAR), prototypeVar, prototypeName);prototypeName=0; if (name) { JsVar *objName = jsvFindChildFromString(execInfo.root, name, true); if (objName) jsvSetValueOfName(objName, obj); jsvUnLock(obj); if (!objName) { // out of memory return 0; } return objName; } else return obj; } /** Returns true if the constructor function given is the same as that * of the object with the given name. */ bool jspIsConstructor(JsVar *constructor, const char *constructorName) { JsVar *objFunc = jsvObjectGetChild(execInfo.root, constructorName, 0); if (!objFunc) return false; bool isConstructor = objFunc == constructor; jsvUnLock(objFunc); return isConstructor; } /** Get the constructor of the given object, or return 0 if ot found, or not a function */ JsVar *jspGetConstructor(JsVar *object) { if (!jsvIsObject(object)) return 0; JsVar *proto = jsvObjectGetChild(object, JSPARSE_INHERITS_VAR, 0); if (jsvIsObject(proto)) { JsVar *constr = jsvObjectGetChild(proto, JSPARSE_CONSTRUCTOR_VAR, 0); if (jsvIsFunction(constr)) { jsvUnLock(proto); return constr; } jsvUnLock(constr); } jsvUnLock(proto); return 0; } // ----------------------------------------------------------------------------- void jspSoftInit() { execInfo.root = jsvFindOrCreateRoot(); // Root now has a lock and a ref execInfo.hiddenRoot = jsvObjectGetChild(execInfo.root, JS_HIDDEN_CHAR_STR, JSV_OBJECT); execInfo.execute = EXEC_YES; } void jspSoftKill() { jsvUnLock(execInfo.hiddenRoot); execInfo.hiddenRoot = 0; jsvUnLock(execInfo.root); execInfo.root = 0; // Root is now left with just a ref } void jspInit() { jspSoftInit(); } void jspKill() { jspSoftKill(); // Unreffing this should completely kill everything attached to root JsVar *r = jsvFindOrCreateRoot(); jsvUnRef(r); jsvUnLock(r); } /** Evaluate the given variable as an expression (in current scope) */ JsVar *jspEvaluateExpressionVar(JsVar *str) { JsLex lex; assert(jsvIsString(str)); JsLex *oldLex = jslSetLex(&lex); jslInit(str); lex.lineNumberOffset = oldLex->lineNumberOffset; // actually do the parsing JsVar *v = jspeExpression(); jslKill(); jslSetLex(oldLex); return jsvSkipNameAndUnLock(v); } /** Execute code form a variable and return the result. If lineNumberOffset * is nonzero it's added to the line numbers that get reported for errors/debug */ JsVar *jspEvaluateVar(JsVar *str, JsVar *scope, uint16_t lineNumberOffset) { JsLex lex; assert(jsvIsString(str)); JsLex *oldLex = jslSetLex(&lex); jslInit(str); lex.lineNumberOffset = lineNumberOffset; JsExecInfo oldExecInfo = execInfo; execInfo.execute = EXEC_YES; bool scopeAdded = false; if (scope) { // if we're adding a scope, make sure it's the *only* scope execInfo.scopeCount = 0; scopeAdded = jspeiAddScope(scope); } // actually do the parsing JsVar *v = jspParse(); // clean up if (scopeAdded) jspeiRemoveScope(); jslKill(); jslSetLex(oldLex); // restore state and execInfo JsExecFlags mask = EXEC_FOR_INIT|EXEC_IN_LOOP|EXEC_IN_SWITCH; oldExecInfo.execute = (oldExecInfo.execute & mask) | (execInfo.execute & ~mask); execInfo = oldExecInfo; // It may have returned a reference, but we just want the value... return jsvSkipNameAndUnLock(v); } JsVar *jspEvaluate(const char *str, bool stringIsStatic) { /* using a memory area is more efficient, but the interpreter * may use substrings from it for function code. This means that * if the string goes away, everything gets corrupted - hence * the option here. */ JsVar *evCode; if (stringIsStatic) evCode = jsvNewNativeString((char*)str, strlen(str)); else evCode = jsvNewFromString(str); if (!evCode) return 0; JsVar *v = 0; if (!jsvIsMemoryFull()) v = jspEvaluateVar(evCode, 0, 0); jsvUnLock(evCode); return v; } JsVar *jspExecuteFunction(JsVar *func, JsVar *thisArg, int argCount, JsVar **argPtr) { JsExecInfo oldExecInfo = execInfo; execInfo.scopeCount = 0; execInfo.execute = EXEC_YES; execInfo.thisVar = 0; JsVar *result = jspeFunctionCall(func, 0, thisArg, false, argCount, argPtr); // clean up assert(execInfo.scopeCount==0); // restore state oldExecInfo.execute = execInfo.execute; // JSP_RESTORE_EXECUTE has made this ok. execInfo = oldExecInfo; return result; } /// Evaluate a JavaScript module and return its exports JsVar *jspEvaluateModule(JsVar *moduleContents) { assert(jsvIsString(moduleContents) || jsvIsFunction(moduleContents)); if (jsvIsFunction(moduleContents)) { moduleContents = jsvObjectGetChild(moduleContents,JSPARSE_FUNCTION_CODE_NAME,0); if (!jsvIsString(moduleContents)) { jsvUnLock(moduleContents); return 0; } } else jsvLockAgain(moduleContents); JsVar *scope = jsvNewObject(); JsVar *scopeExports = jsvNewObject(); if (!scope || !scopeExports) { // out of mem jsvUnLock3(scope, scopeExports, moduleContents); return 0; } JsVar *exportsName = jsvAddNamedChild(scope, scopeExports, "exports"); jsvUnLock2(scopeExports, jsvAddNamedChild(scope, scope, "module")); JsExecFlags oldExecute = execInfo.execute; JsVar *oldThisVar = execInfo.thisVar; execInfo.thisVar = scopeExports; // set 'this' variable to exports jsvUnLock(jspEvaluateVar(moduleContents, scope, 0)); execInfo.thisVar = oldThisVar; execInfo.execute = oldExecute; // make sure we fully restore state after parsing a module jsvUnLock2(moduleContents, scope); return jsvSkipNameAndUnLock(exportsName); } /** Get the owner of the current prototype. We assume that it's * the first item in the array, because that's what we will * have added when we created it. It's safe to call this on * non-prototypes and non-objects. */ JsVar *jspGetPrototypeOwner(JsVar *proto) { if (jsvIsObject(proto) || jsvIsArray(proto)) { return jsvSkipNameAndUnLock(jsvObjectGetChild(proto, JSPARSE_CONSTRUCTOR_VAR, 0)); } return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_159_1
crossvul-cpp_data_bad_343_5
/* * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Initially written by David Mattes <david.mattes@boeing.com> */ /* Support for multiple key containers by Lukas Wunner <lukas@wunner.de> */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #define MANU_ID "Gemplus" #define APPLET_NAME "GemSAFE V1" #define DRIVER_SERIAL_NUMBER "v0.9" #define GEMSAFE_APP_PATH "3F001600" #define GEMSAFE_PATH "3F0016000004" /* Apparently, the Applet max read "quanta" is 248 bytes * Gemalto ClassicClient reads files in chunks of 238 bytes */ #define GEMSAFE_READ_QUANTUM 248 #define GEMSAFE_MAX_OBJLEN 28672 int sc_pkcs15emu_gemsafeV1_init_ex(sc_pkcs15_card_t *, struct sc_aid *,sc_pkcs15emu_opt_t *); static int sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card, int type, int authority, const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label, int obj_flags); static int sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, const sc_path_t *path, int ref, int type, unsigned int min_length, unsigned int max_length, int flags, int tries_left, const char pad_char, int obj_flags); static int sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, int type, unsigned int modulus_length, int usage, const sc_path_t *path, int ref, const sc_pkcs15_id_t *auth_id, int obj_flags); typedef struct cdata_st { char *label; int authority; const char *path; size_t index; size_t count; const char *id; int obj_flags; } cdata; const unsigned int gemsafe_cert_max = 12; cdata gemsafe_cert[] = { {"DS certificate #1", 0, GEMSAFE_PATH, 0, 0, "45", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #2", 0, GEMSAFE_PATH, 0, 0, "46", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #3", 0, GEMSAFE_PATH, 0, 0, "47", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #4", 0, GEMSAFE_PATH, 0, 0, "48", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #5", 0, GEMSAFE_PATH, 0, 0, "49", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #6", 0, GEMSAFE_PATH, 0, 0, "50", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #7", 0, GEMSAFE_PATH, 0, 0, "51", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #8", 0, GEMSAFE_PATH, 0, 0, "52", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #9", 0, GEMSAFE_PATH, 0, 0, "53", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #10", 0, GEMSAFE_PATH, 0, 0, "54", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #11", 0, GEMSAFE_PATH, 0, 0, "55", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #12", 0, GEMSAFE_PATH, 0, 0, "56", SC_PKCS15_CO_FLAG_MODIFIABLE}, }; typedef struct pdata_st { const u8 atr[SC_MAX_ATR_SIZE]; const size_t atr_len; const char *id; const char *label; const char *path; const int ref; const int type; const unsigned int maxlen; const unsigned int minlen; const int flags; const int tries_left; const char pad_char; const int obj_flags; } pindata; const unsigned int gemsafe_pin_max = 2; const pindata gemsafe_pin[] = { /* ATR-specific PIN policies, first match found is used: */ { {0x3B, 0x7D, 0x96, 0x00, 0x00, 0x80, 0x31, 0x80, 0x65, 0xB0, 0x83, 0x11, 0x48, 0xC8, 0x83, 0x00, 0x90, 0x00}, 18, "01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_ASCII_NUMERIC, 8, 4, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL, 3, 0x00, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE }, /* default PIN policy comes last: */ { { 0 }, 0, "01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_BCD, 16, 6, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL, 3, 0xFF, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE } }; typedef struct prdata_st { const char *id; char *label; unsigned int modulus_len; int usage; const char *path; int ref; const char *auth_id; int obj_flags; } prdata; #define USAGE_NONREP SC_PKCS15_PRKEY_USAGE_NONREPUDIATION #define USAGE_KE SC_PKCS15_PRKEY_USAGE_ENCRYPT | \ SC_PKCS15_PRKEY_USAGE_DECRYPT | \ SC_PKCS15_PRKEY_USAGE_WRAP | \ SC_PKCS15_PRKEY_USAGE_UNWRAP #define USAGE_AUT SC_PKCS15_PRKEY_USAGE_ENCRYPT | \ SC_PKCS15_PRKEY_USAGE_DECRYPT | \ SC_PKCS15_PRKEY_USAGE_WRAP | \ SC_PKCS15_PRKEY_USAGE_UNWRAP | \ SC_PKCS15_PRKEY_USAGE_SIGN prdata gemsafe_prkeys[] = { { "45", "DS key #1", 1024, USAGE_AUT, GEMSAFE_PATH, 0x03, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "46", "DS key #2", 1024, USAGE_AUT, GEMSAFE_PATH, 0x04, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "47", "DS key #3", 1024, USAGE_AUT, GEMSAFE_PATH, 0x05, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "48", "DS key #4", 1024, USAGE_AUT, GEMSAFE_PATH, 0x06, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "49", "DS key #5", 1024, USAGE_AUT, GEMSAFE_PATH, 0x07, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "50", "DS key #6", 1024, USAGE_AUT, GEMSAFE_PATH, 0x08, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "51", "DS key #7", 1024, USAGE_AUT, GEMSAFE_PATH, 0x09, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "52", "DS key #8", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0a, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "53", "DS key #9", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0b, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "54", "DS key #10", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0c, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "55", "DS key #11", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0d, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "56", "DS key #12", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0e, "01", SC_PKCS15_CO_FLAG_PRIVATE}, }; static int gemsafe_get_cert_len(sc_card_t *card) { int r; u8 ibuf[GEMSAFE_MAX_OBJLEN]; u8 *iptr; struct sc_path path; struct sc_file *file; size_t objlen, certlen; unsigned int ind, i=0; sc_format_path(GEMSAFE_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* Initial read */ r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0); if (r < 0) return SC_ERROR_INTERNAL; /* Actual stored object size is encoded in first 2 bytes * (allocated EF space is much greater!) */ objlen = (((size_t) ibuf[0]) << 8) | ibuf[1]; sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) { sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); return SC_ERROR_INTERNAL; } /* It looks like the first thing in the block is a table of * which keys are allocated. The table is small and is in the * first 248 bytes. Example for a card with 10 key containers: * 01 f0 00 03 03 b0 00 03 <= 1st key unallocated * 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated * 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated * 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated * 01 f0 00 07 03 b0 00 07 <= 5th key unallocated * ... * 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated * For allocated keys, the fourth byte seems to indicate the * default key and the fifth byte indicates the key_ref of * the private key. */ ind = 2; /* skip length */ while (ibuf[ind] == 0x01) { if (ibuf[ind+1] == 0xFE) { gemsafe_prkeys[i].ref = ibuf[ind+4]; sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d", i+1, gemsafe_prkeys[i].ref); ind += 9; } else { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; sc_log(card->ctx, "Key container %d is unallocated", i+1); ind += 8; } i++; } /* Delete additional key containers from the data structures if * this card can't accommodate them. */ for (; i < gemsafe_cert_max; i++) { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } /* Read entire file, then dissect in memory. * Gemalto ClassicClient seems to do it the same way. */ iptr = ibuf + GEMSAFE_READ_QUANTUM; while ((size_t)(iptr - ibuf) < objlen) { r = sc_read_binary(card, iptr - ibuf, iptr, MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0); if (r < 0) { sc_log(card->ctx, "Could not read cert object"); return SC_ERROR_INTERNAL; } iptr += GEMSAFE_READ_QUANTUM; } /* Search buffer for certificates, they start with 0x3082. */ i = 0; while (ind < objlen - 1) { if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) { /* Find next allocated key container */ while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL) i++; if (i == gemsafe_cert_max) { sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind); return SC_SUCCESS; } /* DER cert len is encoded this way */ if (ind+3 >= sizeof ibuf) return SC_ERROR_INVALID_DATA; certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4; sc_log(card->ctx, "Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u", i+1, ind, certlen); gemsafe_cert[i].index = ind; gemsafe_cert[i].count = certlen; ind += certlen; i++; } else ind++; } /* Delete additional key containers from the data structures if * they're missing on the card. */ for (; i < gemsafe_cert_max; i++) { if (gemsafe_cert[i].label) { sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1); gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } } return SC_SUCCESS; } static int gemsafe_detect_card( sc_pkcs15_card_t *p15card) { if (strcmp(p15card->card->name, "GemSAFE V1")) return SC_ERROR_WRONG_CARD; return SC_SUCCESS; } static int sc_pkcs15emu_gemsafeV1_init( sc_pkcs15_card_t *p15card) { int r; unsigned int i; struct sc_path path; struct sc_file *file = NULL; struct sc_card *card = p15card->card; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_log(p15card->card->ctx, "Setting pkcs15 parameters"); if (p15card->tokeninfo->label) free(p15card->tokeninfo->label); p15card->tokeninfo->label = malloc(strlen(APPLET_NAME) + 1); if (!p15card->tokeninfo->label) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->label, APPLET_NAME); if (p15card->tokeninfo->serial_number) free(p15card->tokeninfo->serial_number); p15card->tokeninfo->serial_number = malloc(strlen(DRIVER_SERIAL_NUMBER) + 1); if (!p15card->tokeninfo->serial_number) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->serial_number, DRIVER_SERIAL_NUMBER); /* the GemSAFE applet version number */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0xdf, 0x03); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); /* Manual says Le=0x05, but should be 0x08 to return full version number */ apdu.le = 0x08; apdu.lc = 0; apdu.datalen = 0; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) return SC_ERROR_INTERNAL; if (r != SC_SUCCESS) return SC_ERROR_INTERNAL; /* the manufacturer ID, in this case GemPlus */ if (p15card->tokeninfo->manufacturer_id) free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = malloc(strlen(MANU_ID) + 1); if (!p15card->tokeninfo->manufacturer_id) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->manufacturer_id, MANU_ID); /* determine allocated key containers and length of certificates */ r = gemsafe_get_cert_len(card); if (r != SC_SUCCESS) return SC_ERROR_INTERNAL; /* set certs */ sc_log(p15card->card->ctx, "Setting certificates"); for (i = 0; i < gemsafe_cert_max; i++) { struct sc_pkcs15_id p15Id; struct sc_path path; if (gemsafe_cert[i].label == NULL) continue; sc_format_path(gemsafe_cert[i].path, &path); sc_pkcs15_format_id(gemsafe_cert[i].id, &p15Id); path.index = gemsafe_cert[i].index; path.count = gemsafe_cert[i].count; sc_pkcs15emu_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509, gemsafe_cert[i].authority, &path, &p15Id, gemsafe_cert[i].label, gemsafe_cert[i].obj_flags); } /* set gemsafe_pin */ sc_log(p15card->card->ctx, "Setting PIN"); for (i=0; i < gemsafe_pin_max; i++) { struct sc_pkcs15_id p15Id; struct sc_path path; sc_pkcs15_format_id(gemsafe_pin[i].id, &p15Id); sc_format_path(gemsafe_pin[i].path, &path); if (gemsafe_pin[i].atr_len == 0 || (gemsafe_pin[i].atr_len == p15card->card->atr.len && memcmp(p15card->card->atr.value, gemsafe_pin[i].atr, p15card->card->atr.len) == 0)) { sc_pkcs15emu_add_pin(p15card, &p15Id, gemsafe_pin[i].label, &path, gemsafe_pin[i].ref, gemsafe_pin[i].type, gemsafe_pin[i].minlen, gemsafe_pin[i].maxlen, gemsafe_pin[i].flags, gemsafe_pin[i].tries_left, gemsafe_pin[i].pad_char, gemsafe_pin[i].obj_flags); break; } }; /* set private keys */ sc_log(p15card->card->ctx, "Setting private keys"); for (i = 0; i < gemsafe_cert_max; i++) { struct sc_pkcs15_id p15Id, authId, *pauthId; struct sc_path path; int key_ref = 0x03; if (gemsafe_prkeys[i].label == NULL) continue; sc_pkcs15_format_id(gemsafe_prkeys[i].id, &p15Id); if (gemsafe_prkeys[i].auth_id) { sc_pkcs15_format_id(gemsafe_prkeys[i].auth_id, &authId); pauthId = &authId; } else pauthId = NULL; sc_format_path(gemsafe_prkeys[i].path, &path); /* * The key ref may be different for different sites; * by adding flags=n where the low order 4 bits can be * the key ref we can force it. */ if ( p15card->card->flags & 0x0F) { key_ref = p15card->card->flags & 0x0F; sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Overriding key_ref %d with %d\n", gemsafe_prkeys[i].ref, key_ref); } else key_ref = gemsafe_prkeys[i].ref; sc_pkcs15emu_add_prkey(p15card, &p15Id, gemsafe_prkeys[i].label, SC_PKCS15_TYPE_PRKEY_RSA, gemsafe_prkeys[i].modulus_len, gemsafe_prkeys[i].usage, &path, key_ref, pauthId, gemsafe_prkeys[i].obj_flags); } /* select the application DF */ sc_log(p15card->card->ctx, "Selecting application DF"); sc_format_path(GEMSAFE_APP_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* set the application DF */ if (p15card->file_app) free(p15card->file_app); p15card->file_app = file; return SC_SUCCESS; } int sc_pkcs15emu_gemsafeV1_init_ex( sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK) return sc_pkcs15emu_gemsafeV1_init(p15card); else { int r = gemsafe_detect_card(p15card); if (r) return SC_ERROR_WRONG_CARD; return sc_pkcs15emu_gemsafeV1_init(p15card); } } static sc_pkcs15_df_t * sc_pkcs15emu_get_df(sc_pkcs15_card_t *p15card, unsigned int type) { sc_pkcs15_df_t *df; sc_file_t *file; int created = 0; while (1) { for (df = p15card->df_list; df; df = df->next) { if (df->type == type) { if (created) df->enumerated = 1; return df; } } assert(created == 0); file = sc_file_new(); if (!file) return NULL; sc_format_path("11001101", &file->path); sc_pkcs15_add_df(p15card, type, &file->path); sc_file_free(file); created++; } } static int sc_pkcs15emu_add_object(sc_pkcs15_card_t *p15card, int type, const char *label, void *data, const sc_pkcs15_id_t *auth_id, int obj_flags) { sc_pkcs15_object_t *obj; int df_type; obj = calloc(1, sizeof(*obj)); obj->type = type; obj->data = data; if (label) strncpy(obj->label, label, sizeof(obj->label)-1); obj->flags = obj_flags; if (auth_id) obj->auth_id = *auth_id; switch (type & SC_PKCS15_TYPE_CLASS_MASK) { case SC_PKCS15_TYPE_AUTH: df_type = SC_PKCS15_AODF; break; case SC_PKCS15_TYPE_PRKEY: df_type = SC_PKCS15_PRKDF; break; case SC_PKCS15_TYPE_PUBKEY: df_type = SC_PKCS15_PUKDF; break; case SC_PKCS15_TYPE_CERT: df_type = SC_PKCS15_CDF; break; default: sc_log(p15card->card->ctx, "Unknown PKCS15 object type %d", type); free(obj); return SC_ERROR_INVALID_ARGUMENTS; } obj->df = sc_pkcs15emu_get_df(p15card, df_type); sc_pkcs15_add_object(p15card, obj); return 0; } static int sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, const sc_path_t *path, int ref, int type, unsigned int min_length, unsigned int max_length, int flags, int tries_left, const char pad_char, int obj_flags) { sc_pkcs15_auth_info_t *info; info = calloc(1, sizeof(*info)); if (!info) LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); info->auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; info->auth_method = SC_AC_CHV; info->auth_id = *id; info->attrs.pin.min_length = min_length; info->attrs.pin.max_length = max_length; info->attrs.pin.stored_length = max_length; info->attrs.pin.type = type; info->attrs.pin.reference = ref; info->attrs.pin.flags = flags; info->attrs.pin.pad_char = pad_char; info->tries_left = tries_left; info->logged_in = SC_PIN_STATE_UNKNOWN; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, SC_PKCS15_TYPE_AUTH_PIN, label, info, NULL, obj_flags); } static int sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card, int type, int authority, const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label, int obj_flags) { sc_pkcs15_cert_info_t *info; info = calloc(1, sizeof(*info)); if (!info) { LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); } info->id = *id; info->authority = authority; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, type, label, info, NULL, obj_flags); } static int sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, int type, unsigned int modulus_length, int usage, const sc_path_t *path, int ref, const sc_pkcs15_id_t *auth_id, int obj_flags) { sc_pkcs15_prkey_info_t *info; info = calloc(1, sizeof(*info)); if (!info) { LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); } info->id = *id; info->modulus_length = modulus_length; info->usage = usage; info->native = 1; info->access_flags = SC_PKCS15_PRKEY_ACCESS_SENSITIVE | SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE | SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE | SC_PKCS15_PRKEY_ACCESS_LOCAL; info->key_reference = ref; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, type, label, info, auth_id, obj_flags); } /* SC_IMPLEMENT_DRIVER_VERSION("0.9.4") */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_343_5
crossvul-cpp_data_bad_5733_0
/* * Copyright (c) 2002 Michael Niedermayer <michaelni@gmx.at> * Copyright (c) 2011 Stefano Sabatini * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with FFmpeg; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /** * @file * Apply a boxblur filter to the input video. * Ported from MPlayer libmpcodecs/vf_boxblur.c. */ #include "libavutil/avstring.h" #include "libavutil/common.h" #include "libavutil/eval.h" #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "avfilter.h" #include "formats.h" #include "internal.h" #include "video.h" static const char *const var_names[] = { "w", "h", "cw", "ch", "hsub", "vsub", NULL }; enum var_name { VAR_W, VAR_H, VAR_CW, VAR_CH, VAR_HSUB, VAR_VSUB, VARS_NB }; typedef struct { int radius; int power; char *radius_expr; } FilterParam; typedef struct { const AVClass *class; FilterParam luma_param; FilterParam chroma_param; FilterParam alpha_param; int hsub, vsub; int radius[4]; int power[4]; uint8_t *temp[2]; ///< temporary buffer used in blur_power() } BoxBlurContext; #define Y 0 #define U 1 #define V 2 #define A 3 static av_cold int init(AVFilterContext *ctx) { BoxBlurContext *s = ctx->priv; if (!s->luma_param.radius_expr) { av_log(ctx, AV_LOG_ERROR, "Luma radius expression is not set.\n"); return AVERROR(EINVAL); } /* fill missing params */ if (!s->chroma_param.radius_expr) { s->chroma_param.radius_expr = av_strdup(s->luma_param.radius_expr); if (!s->chroma_param.radius_expr) return AVERROR(ENOMEM); } if (s->chroma_param.power < 0) s->chroma_param.power = s->luma_param.power; if (!s->alpha_param.radius_expr) { s->alpha_param.radius_expr = av_strdup(s->luma_param.radius_expr); if (!s->alpha_param.radius_expr) return AVERROR(ENOMEM); } if (s->alpha_param.power < 0) s->alpha_param.power = s->luma_param.power; return 0; } static av_cold void uninit(AVFilterContext *ctx) { BoxBlurContext *s = ctx->priv; av_freep(&s->temp[0]); av_freep(&s->temp[1]); } static int query_formats(AVFilterContext *ctx) { static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUV440P, AV_PIX_FMT_GRAY8, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_NONE }; ff_set_common_formats(ctx, ff_make_format_list(pix_fmts)); return 0; } static int config_input(AVFilterLink *inlink) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); AVFilterContext *ctx = inlink->dst; BoxBlurContext *s = ctx->priv; int w = inlink->w, h = inlink->h; int cw, ch; double var_values[VARS_NB], res; char *expr; int ret; if (!(s->temp[0] = av_malloc(FFMAX(w, h))) || !(s->temp[1] = av_malloc(FFMAX(w, h)))) return AVERROR(ENOMEM); s->hsub = desc->log2_chroma_w; s->vsub = desc->log2_chroma_h; var_values[VAR_W] = inlink->w; var_values[VAR_H] = inlink->h; var_values[VAR_CW] = cw = w>>s->hsub; var_values[VAR_CH] = ch = h>>s->vsub; var_values[VAR_HSUB] = 1<<s->hsub; var_values[VAR_VSUB] = 1<<s->vsub; #define EVAL_RADIUS_EXPR(comp) \ expr = s->comp##_param.radius_expr; \ ret = av_expr_parse_and_eval(&res, expr, var_names, var_values, \ NULL, NULL, NULL, NULL, NULL, 0, ctx); \ s->comp##_param.radius = res; \ if (ret < 0) { \ av_log(NULL, AV_LOG_ERROR, \ "Error when evaluating " #comp " radius expression '%s'\n", expr); \ return ret; \ } EVAL_RADIUS_EXPR(luma); EVAL_RADIUS_EXPR(chroma); EVAL_RADIUS_EXPR(alpha); av_log(ctx, AV_LOG_VERBOSE, "luma_radius:%d luma_power:%d " "chroma_radius:%d chroma_power:%d " "alpha_radius:%d alpha_power:%d " "w:%d chroma_w:%d h:%d chroma_h:%d\n", s->luma_param .radius, s->luma_param .power, s->chroma_param.radius, s->chroma_param.power, s->alpha_param .radius, s->alpha_param .power, w, cw, h, ch); #define CHECK_RADIUS_VAL(w_, h_, comp) \ if (s->comp##_param.radius < 0 || \ 2*s->comp##_param.radius > FFMIN(w_, h_)) { \ av_log(ctx, AV_LOG_ERROR, \ "Invalid " #comp " radius value %d, must be >= 0 and <= %d\n", \ s->comp##_param.radius, FFMIN(w_, h_)/2); \ return AVERROR(EINVAL); \ } CHECK_RADIUS_VAL(w, h, luma); CHECK_RADIUS_VAL(cw, ch, chroma); CHECK_RADIUS_VAL(w, h, alpha); s->radius[Y] = s->luma_param.radius; s->radius[U] = s->radius[V] = s->chroma_param.radius; s->radius[A] = s->alpha_param.radius; s->power[Y] = s->luma_param.power; s->power[U] = s->power[V] = s->chroma_param.power; s->power[A] = s->alpha_param.power; return 0; } static inline void blur(uint8_t *dst, int dst_step, const uint8_t *src, int src_step, int len, int radius) { /* Naive boxblur would sum source pixels from x-radius .. x+radius * for destination pixel x. That would be O(radius*width). * If you now look at what source pixels represent 2 consecutive * output pixels, then you see they are almost identical and only * differ by 2 pixels, like: * src0 111111111 * dst0 1 * src1 111111111 * dst1 1 * src0-src1 1 -1 * so when you know one output pixel you can find the next by just adding * and subtracting 1 input pixel. * The following code adopts this faster variant. */ const int length = radius*2 + 1; const int inv = ((1<<16) + length/2)/length; int x, sum = 0; for (x = 0; x < radius; x++) sum += src[x*src_step]<<1; sum += src[radius*src_step]; for (x = 0; x <= radius; x++) { sum += src[(radius+x)*src_step] - src[(radius-x)*src_step]; dst[x*dst_step] = (sum*inv + (1<<15))>>16; } for (; x < len-radius; x++) { sum += src[(radius+x)*src_step] - src[(x-radius-1)*src_step]; dst[x*dst_step] = (sum*inv + (1<<15))>>16; } for (; x < len; x++) { sum += src[(2*len-radius-x-1)*src_step] - src[(x-radius-1)*src_step]; dst[x*dst_step] = (sum*inv + (1<<15))>>16; } } static inline void blur_power(uint8_t *dst, int dst_step, const uint8_t *src, int src_step, int len, int radius, int power, uint8_t *temp[2]) { uint8_t *a = temp[0], *b = temp[1]; if (radius && power) { blur(a, 1, src, src_step, len, radius); for (; power > 2; power--) { uint8_t *c; blur(b, 1, a, 1, len, radius); c = a; a = b; b = c; } if (power > 1) { blur(dst, dst_step, a, 1, len, radius); } else { int i; for (i = 0; i < len; i++) dst[i*dst_step] = a[i]; } } else { int i; for (i = 0; i < len; i++) dst[i*dst_step] = src[i*src_step]; } } static void hblur(uint8_t *dst, int dst_linesize, const uint8_t *src, int src_linesize, int w, int h, int radius, int power, uint8_t *temp[2]) { int y; if (radius == 0 && dst == src) return; for (y = 0; y < h; y++) blur_power(dst + y*dst_linesize, 1, src + y*src_linesize, 1, w, radius, power, temp); } static void vblur(uint8_t *dst, int dst_linesize, const uint8_t *src, int src_linesize, int w, int h, int radius, int power, uint8_t *temp[2]) { int x; if (radius == 0 && dst == src) return; for (x = 0; x < w; x++) blur_power(dst + x, dst_linesize, src + x, src_linesize, h, radius, power, temp); } static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; BoxBlurContext *s = ctx->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int plane; int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub); int w[4] = { inlink->w, cw, cw, inlink->w }; int h[4] = { in->height, ch, ch, in->height }; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); for (plane = 0; in->data[plane] && plane < 4; plane++) hblur(out->data[plane], out->linesize[plane], in ->data[plane], in ->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); for (plane = 0; in->data[plane] && plane < 4; plane++) vblur(out->data[plane], out->linesize[plane], out->data[plane], out->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); av_frame_free(&in); return ff_filter_frame(outlink, out); } #define OFFSET(x) offsetof(BoxBlurContext, x) #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM static const AVOption boxblur_options[] = { { "luma_radius", "Radius of the luma blurring box", OFFSET(luma_param.radius_expr), AV_OPT_TYPE_STRING, {.str="2"}, .flags = FLAGS }, { "lr", "Radius of the luma blurring box", OFFSET(luma_param.radius_expr), AV_OPT_TYPE_STRING, {.str="2"}, .flags = FLAGS }, { "luma_power", "How many times should the boxblur be applied to luma", OFFSET(luma_param.power), AV_OPT_TYPE_INT, {.i64=2}, 0, INT_MAX, .flags = FLAGS }, { "lp", "How many times should the boxblur be applied to luma", OFFSET(luma_param.power), AV_OPT_TYPE_INT, {.i64=2}, 0, INT_MAX, .flags = FLAGS }, { "chroma_radius", "Radius of the chroma blurring box", OFFSET(chroma_param.radius_expr), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS }, { "cr", "Radius of the chroma blurring box", OFFSET(chroma_param.radius_expr), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS }, { "chroma_power", "How many times should the boxblur be applied to chroma", OFFSET(chroma_param.power), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS }, { "cp", "How many times should the boxblur be applied to chroma", OFFSET(chroma_param.power), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS }, { "alpha_radius", "Radius of the alpha blurring box", OFFSET(alpha_param.radius_expr), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS }, { "ar", "Radius of the alpha blurring box", OFFSET(alpha_param.radius_expr), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS }, { "alpha_power", "How many times should the boxblur be applied to alpha", OFFSET(alpha_param.power), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS }, { "ap", "How many times should the boxblur be applied to alpha", OFFSET(alpha_param.power), AV_OPT_TYPE_INT, {.i64=-1}, -1, INT_MAX, .flags = FLAGS }, { NULL } }; AVFILTER_DEFINE_CLASS(boxblur); static const AVFilterPad avfilter_vf_boxblur_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .config_props = config_input, .filter_frame = filter_frame, }, { NULL } }; static const AVFilterPad avfilter_vf_boxblur_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, }, { NULL } }; AVFilter avfilter_vf_boxblur = { .name = "boxblur", .description = NULL_IF_CONFIG_SMALL("Blur the input."), .priv_size = sizeof(BoxBlurContext), .priv_class = &boxblur_class, .init = init, .uninit = uninit, .query_formats = query_formats, .inputs = avfilter_vf_boxblur_inputs, .outputs = avfilter_vf_boxblur_outputs, .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5733_0
crossvul-cpp_data_bad_343_6
/* * pkcs15-sc-hsm.c : Initialize PKCS#15 emulation * * Copyright (C) 2012 Andreas Schwier, CardContact, Minden, Germany * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #include "asn1.h" #include "common/compat_strlcpy.h" #include "common/compat_strnlen.h" #include "card-sc-hsm.h" extern struct sc_aid sc_hsm_aid; void sc_hsm_set_serialnr(sc_card_t *card, char *serial); static struct ec_curve curves[] = { { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x01", 8}, // secp192r1 aka prime192r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 24}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 24}, { (unsigned char *) "\x64\x21\x05\x19\xE5\x9C\x80\xE7\x0F\xA7\xE9\xAB\x72\x24\x30\x49\xFE\xB8\xDE\xEC\xC1\x46\xB9\xB1", 24}, { (unsigned char *) "\x04\x18\x8D\xA8\x0E\xB0\x30\x90\xF6\x7C\xBF\x20\xEB\x43\xA1\x88\x00\xF4\xFF\x0A\xFD\x82\xFF\x10\x12\x07\x19\x2B\x95\xFF\xC8\xDA\x78\x63\x10\x11\xED\x6B\x24\xCD\xD5\x73\xF9\x77\xA1\x1E\x79\x48\x11", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x99\xDE\xF8\x36\x14\x6B\xC9\xB1\xB4\xD2\x28\x31", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8}, // secp256r1 aka prime256r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 32}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 32}, { (unsigned char *) "\x5A\xC6\x35\xD8\xAA\x3A\x93\xE7\xB3\xEB\xBD\x55\x76\x98\x86\xBC\x65\x1D\x06\xB0\xCC\x53\xB0\xF6\x3B\xCE\x3C\x3E\x27\xD2\x60\x4B", 32}, { (unsigned char *) "\x04\x6B\x17\xD1\xF2\xE1\x2C\x42\x47\xF8\xBC\xE6\xE5\x63\xA4\x40\xF2\x77\x03\x7D\x81\x2D\xEB\x33\xA0\xF4\xA1\x39\x45\xD8\x98\xC2\x96\x4F\xE3\x42\xE2\xFE\x1A\x7F\x9B\x8E\xE7\xEB\x4A\x7C\x0F\x9E\x16\x2B\xCE\x33\x57\x6B\x31\x5E\xCE\xCB\xB6\x40\x68\x37\xBF\x51\xF5", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBC\xE6\xFA\xAD\xA7\x17\x9E\x84\xF3\xB9\xCA\xC2\xFC\x63\x25\x51", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x03", 9}, // brainpoolP192r1 { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x30\x93\xD1\x8D\xB7\x8F\xCE\x47\x6D\xE1\xA8\x62\x97", 24}, { (unsigned char *) "\x6A\x91\x17\x40\x76\xB1\xE0\xE1\x9C\x39\xC0\x31\xFE\x86\x85\xC1\xCA\xE0\x40\xE5\xC6\x9A\x28\xEF", 24}, { (unsigned char *) "\x46\x9A\x28\xEF\x7C\x28\xCC\xA3\xDC\x72\x1D\x04\x4F\x44\x96\xBC\xCA\x7E\xF4\x14\x6F\xBF\x25\xC9", 24}, { (unsigned char *) "\x04\xC0\xA0\x64\x7E\xAA\xB6\xA4\x87\x53\xB0\x33\xC5\x6C\xB0\xF0\x90\x0A\x2F\x5C\x48\x53\x37\x5F\xD6\x14\xB6\x90\x86\x6A\xBD\x5B\xB8\x8B\x5F\x48\x28\xC1\x49\x00\x02\xE6\x77\x3F\xA2\xFA\x29\x9B\x8F", 49}, { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x2F\x9E\x9E\x91\x6B\x5B\xE8\xF1\x02\x9A\xC4\xAC\xC1", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x05", 9}, // brainpoolP224r1 { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF", 28}, { (unsigned char *) "\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA\xD2\x9F\x43", 28}, { (unsigned char *) "\x25\x80\xF6\x3C\xCF\xE4\x41\x38\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66\xDB\xB3\x72\x38\x6C\x40\x0B", 28}, { (unsigned char *) "\x04\x0D\x90\x29\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02\xCD", 57}, { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD0\xFB\x98\xD1\x16\xBC\x4B\x6D\xDE\xBC\xA3\xA5\xA7\x93\x9F", 28}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x07", 9}, // brainpoolP256r1 { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x72\x6E\x3B\xF6\x23\xD5\x26\x20\x28\x20\x13\x48\x1D\x1F\x6E\x53\x77", 32}, { (unsigned char *) "\x7D\x5A\x09\x75\xFC\x2C\x30\x57\xEE\xF6\x75\x30\x41\x7A\xFF\xE7\xFB\x80\x55\xC1\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9", 32}, { (unsigned char *) "\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9\xBB\xD7\x7C\xBF\x95\x84\x16\x29\x5C\xF7\xE1\xCE\x6B\xCC\xDC\x18\xFF\x8C\x07\xB6", 32}, { (unsigned char *) "\x04\x8B\xD2\xAE\xB9\xCB\x7E\x57\xCB\x2C\x4B\x48\x2F\xFC\x81\xB7\xAF\xB9\xDE\x27\xE1\xE3\xBD\x23\xC2\x3A\x44\x53\xBD\x9A\xCE\x32\x62\x54\x7E\xF8\x35\xC3\xDA\xC4\xFD\x97\xF8\x46\x1A\x14\x61\x1D\xC9\xC2\x77\x45\x13\x2D\xED\x8E\x54\x5C\x1D\x54\xC7\x2F\x04\x69\x97", 65}, { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x71\x8C\x39\x7A\xA3\xB5\x61\xA6\xF7\x90\x1E\x0E\x82\x97\x48\x56\xA7", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x09", 9}, // brainpoolP320r1 { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA6\xF6\xF4\x0D\xEF\x4F\x92\xB9\xEC\x78\x93\xEC\x28\xFC\xD4\x12\xB1\xF1\xB3\x2E\x27", 40}, { (unsigned char *) "\x3E\xE3\x0B\x56\x8F\xBA\xB0\xF8\x83\xCC\xEB\xD4\x6D\x3F\x3B\xB8\xA2\xA7\x35\x13\xF5\xEB\x79\xDA\x66\x19\x0E\xB0\x85\xFF\xA9\xF4\x92\xF3\x75\xA9\x7D\x86\x0E\xB4", 40}, { (unsigned char *) "\x52\x08\x83\x94\x9D\xFD\xBC\x42\xD3\xAD\x19\x86\x40\x68\x8A\x6F\xE1\x3F\x41\x34\x95\x54\xB4\x9A\xCC\x31\xDC\xCD\x88\x45\x39\x81\x6F\x5E\xB4\xAC\x8F\xB1\xF1\xA6", 40}, { (unsigned char *) "\x04\x43\xBD\x7E\x9A\xFB\x53\xD8\xB8\x52\x89\xBC\xC4\x8E\xE5\xBF\xE6\xF2\x01\x37\xD1\x0A\x08\x7E\xB6\xE7\x87\x1E\x2A\x10\xA5\x99\xC7\x10\xAF\x8D\x0D\x39\xE2\x06\x11\x14\xFD\xD0\x55\x45\xEC\x1C\xC8\xAB\x40\x93\x24\x7F\x77\x27\x5E\x07\x43\xFF\xED\x11\x71\x82\xEA\xA9\xC7\x78\x77\xAA\xAC\x6A\xC7\xD3\x52\x45\xD1\x69\x2E\x8E\xE1", 81}, { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA5\xB6\x8F\x12\xA3\x2D\x48\x2E\xC7\xEE\x86\x58\xE9\x86\x91\x55\x5B\x44\xC5\x93\x11", 40}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x1F", 5}, // secp192k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xEE\x37", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03", 24}, { (unsigned char *) "\x04\xDB\x4F\xF1\x0E\xC0\x57\xE9\xAE\x26\xB0\x7D\x02\x80\xB7\xF4\x34\x1D\xA5\xD1\xB1\xEA\xE0\x6C\x7D\x9B\x2F\x2F\x6D\x9C\x56\x28\xA7\x84\x41\x63\xD0\x15\xBE\x86\x34\x40\x82\xAA\x88\xD9\x5E\x2F\x9D", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\x26\xF2\xFC\x17\x0F\x69\x46\x6A\x74\xDE\xFD\x8D", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x0A", 5}, // secp256k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFC\x2F", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07", 32}, { (unsigned char *) "\x04\x79\xBE\x66\x7E\xF9\xDC\xBB\xAC\x55\xA0\x62\x95\xCE\x87\x0B\x07\x02\x9B\xFC\xDB\x2D\xCE\x28\xD9\x59\xF2\x81\x5B\x16\xF8\x17\x98\x48\x3A\xDA\x77\x26\xA3\xC4\x65\x5D\xA4\xFB\xFC\x0E\x11\x08\xA8\xFD\x17\xB4\x48\xA6\x85\x54\x19\x9C\x47\xD0\x8F\xFB\x10\xD4\xB8", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B\xBF\xD2\x5E\x8C\xD0\x36\x41\x41", 32}, { (unsigned char *) "\x01", 1} }, { { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0} } }; #define C_ASN1_CVC_PUBKEY_SIZE 10 static const struct sc_asn1_entry c_asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE] = { { "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL }, { "primeOrModulus", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientAorExponent", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 2, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientB", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 3, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "basePointG", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 4, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "order", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 5, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "cofactor", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 7, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "modulusSize", SC_ASN1_INTEGER, SC_ASN1_UNI | SC_ASN1_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_BODY_SIZE 5 static const struct sc_asn1_entry c_asn1_cvc_body[C_ASN1_CVC_BODY_SIZE] = { { "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL }, { "certificationAuthorityReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL }, { "certificateHolderReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVCERT_SIZE 3 static const struct sc_asn1_entry c_asn1_cvcert[C_ASN1_CVCERT_SIZE] = { { "certificateBody", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F4E, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_SIZE 2 static const struct sc_asn1_entry c_asn1_cvc[C_ASN1_CVC_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_AUTHREQ_SIZE 4 static const struct sc_asn1_entry c_asn1_authreq[C_ASN1_AUTHREQ_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { "outerCAR", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_REQ_SIZE 2 static const struct sc_asn1_entry c_asn1_req[C_ASN1_REQ_SIZE] = { { "authenticatedrequest", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 7, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static int read_file(sc_pkcs15_card_t * p15card, u8 fid[2], u8 *efbin, size_t *len, int optional) { sc_path_t path; int r; sc_path_set(&path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); /* look this up with our AID */ path.aid = sc_hsm_aid; /* we don't have a pre-known size of the file */ path.count = -1; if (!p15card->opts.use_file_cache || !efbin || SC_SUCCESS != sc_pkcs15_read_cached_file(p15card, &path, &efbin, len)) { /* avoid re-selection of SC-HSM */ path.aid.len = 0; r = sc_select_file(p15card->card, &path, NULL); if (r < 0) { sc_log(p15card->card->ctx, "Could not select EF"); } else { r = sc_read_binary(p15card->card, 0, efbin, *len, 0); } if (r < 0) { sc_log(p15card->card->ctx, "Could not read EF"); if (!optional) { return r; } /* optional files are saved as empty files to avoid card * transactions. Parsing the file's data will reveal that they were * missing. */ *len = 0; } else { *len = r; } if (p15card->opts.use_file_cache) { /* save this with our AID */ path.aid = sc_hsm_aid; sc_pkcs15_cache_file(p15card, &path, efbin, *len); } } return SC_SUCCESS; } /* * Decode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_decode_cvc(sc_pkcs15_card_t * p15card, const u8 ** buf, size_t *buflen, sc_cvc_t *cvc) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_req[C_ASN1_REQ_SIZE]; struct sc_asn1_entry asn1_authreq[C_ASN1_AUTHREQ_SIZE]; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; unsigned int cla,tag; size_t taglen; size_t lenchr = sizeof(cvc->chr); size_t lencar = sizeof(cvc->car); size_t lenoutercar = sizeof(cvc->outer_car); const u8 *tbuf; int r; memset(cvc, 0, sizeof(*cvc)); sc_copy_asn1_entry(c_asn1_req, asn1_req); sc_copy_asn1_entry(c_asn1_authreq, asn1_authreq); sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 1, &cvc->primeOrModulus, &cvc->primeOrModuluslen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 2, &cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 3, &cvc->coefficientB, &cvc->coefficientBlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 4, &cvc->basePointG, &cvc->basePointGlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 5, &cvc->order, &cvc->orderlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 6, &cvc->publicPoint, &cvc->publicPointlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 7, &cvc->cofactor, &cvc->cofactorlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 0); sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 0); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 0); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 0); sc_format_asn1_entry(asn1_cvcert + 1, &cvc->signature, &cvc->signatureLen, 0); sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq + 1, &cvc->outer_car, &lenoutercar, 0); sc_format_asn1_entry(asn1_authreq + 2, &cvc->outerSignature, &cvc->outerSignatureLen, 0); sc_format_asn1_entry(asn1_req , &asn1_authreq, NULL, 0); /* sc_asn1_print_tags(*buf, *buflen); */ tbuf = *buf; r = sc_asn1_read_tag(&tbuf, *buflen, &cla, &tag, &taglen); LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); /* Determine if we deal with an authenticated request, plain request or certificate */ if ((cla == (SC_ASN1_TAG_APPLICATION|SC_ASN1_TAG_CONSTRUCTED)) && (tag == 7)) { r = sc_asn1_decode(card->ctx, asn1_req, *buf, *buflen, buf, buflen); } else { r = sc_asn1_decode(card->ctx, asn1_cvc, *buf, *buflen, buf, buflen); } LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Encode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_encode_cvc(sc_pkcs15_card_t * p15card, sc_cvc_t *cvc, u8 ** buf, size_t *buflen) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; size_t lenchr; size_t lencar; int r; sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); asn1_cvc_pubkey[1].flags = SC_ASN1_OPTIONAL; asn1_cvcert[1].flags = SC_ASN1_OPTIONAL; sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 1); if (cvc->primeOrModulus && (cvc->primeOrModuluslen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 1, cvc->primeOrModulus, &cvc->primeOrModuluslen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 2, cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 1); if (cvc->coefficientB && (cvc->coefficientBlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 3, cvc->coefficientB, &cvc->coefficientBlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 4, cvc->basePointG, &cvc->basePointGlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 5, cvc->order, &cvc->orderlen, 1); if (cvc->publicPoint && (cvc->publicPointlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 6, cvc->publicPoint, &cvc->publicPointlen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 7, cvc->cofactor, &cvc->cofactorlen, 1); } if (cvc->modulusSize > 0) { sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 1); } sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 1); lencar = strnlen(cvc->car, sizeof cvc->car); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 1); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 1); lenchr = strnlen(cvc->chr, sizeof cvc->chr); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 1); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 1); if (cvc->signature && (cvc->signatureLen > 0)) { sc_format_asn1_entry(asn1_cvcert + 1, cvc->signature, &cvc->signatureLen, 1); } sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 1); r = sc_asn1_encode(card->ctx, asn1_cvc, buf, buflen); LOG_TEST_RET(card->ctx, r, "Could not encode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_get_curve(struct ec_curve **curve, u8 *oid, size_t oidlen) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].oid.len == oidlen) && !memcmp(curves[i].oid.value, oid, oidlen)) { *curve = &curves[i]; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } int sc_pkcs15emu_sc_hsm_get_curve_oid(sc_cvc_t *cvc, const struct sc_lv_data **oid) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].prime.len == cvc->primeOrModuluslen) && !memcmp(curves[i].prime.value, cvc->primeOrModulus, cvc->primeOrModuluslen)) { *oid = &curves[i].oid; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } static int sc_pkcs15emu_sc_hsm_get_rsa_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { pubkey->algorithm = SC_ALGORITHM_RSA; pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) return SC_ERROR_OUT_OF_MEMORY; pubkey->alg_id->algorithm = SC_ALGORITHM_RSA; pubkey->u.rsa.modulus.len = cvc->primeOrModuluslen; pubkey->u.rsa.modulus.data = malloc(pubkey->u.rsa.modulus.len); pubkey->u.rsa.exponent.len = cvc->coefficientAorExponentlen; pubkey->u.rsa.exponent.data = malloc(pubkey->u.rsa.exponent.len); if (!pubkey->u.rsa.modulus.data || !pubkey->u.rsa.exponent.data) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.rsa.exponent.data, cvc->coefficientAorExponent, pubkey->u.rsa.exponent.len); memcpy(pubkey->u.rsa.modulus.data, cvc->primeOrModulus, pubkey->u.rsa.modulus.len); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_get_ec_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { struct sc_ec_parameters *ecp; const struct sc_lv_data *oid; int r; pubkey->algorithm = SC_ALGORITHM_EC; r = sc_pkcs15emu_sc_hsm_get_curve_oid(cvc, &oid); if (r != SC_SUCCESS) return r; ecp = calloc(1, sizeof(struct sc_ec_parameters)); if (!ecp) return SC_ERROR_OUT_OF_MEMORY; ecp->der.len = oid->len + 2; ecp->der.value = calloc(ecp->der.len, 1); if (!ecp->der.value) { free(ecp); return SC_ERROR_OUT_OF_MEMORY; } *(ecp->der.value + 0) = 0x06; *(ecp->der.value + 1) = (u8)oid->len; memcpy(ecp->der.value + 2, oid->value, oid->len); ecp->type = 1; // Named curve pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) { free(ecp->der.value); free(ecp); return SC_ERROR_OUT_OF_MEMORY; } pubkey->alg_id->algorithm = SC_ALGORITHM_EC; pubkey->alg_id->params = ecp; pubkey->u.ec.ecpointQ.value = malloc(cvc->publicPointlen); if (!pubkey->u.ec.ecpointQ.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.ecpointQ.value, cvc->publicPoint, cvc->publicPointlen); pubkey->u.ec.ecpointQ.len = cvc->publicPointlen; pubkey->u.ec.params.der.value = malloc(ecp->der.len); if (!pubkey->u.ec.params.der.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.params.der.value, ecp->der.value, ecp->der.len); pubkey->u.ec.params.der.len = ecp->der.len; /* FIXME: check return value? */ sc_pkcs15_fix_ec_parameters(ctx, &pubkey->u.ec.params); return SC_SUCCESS; } int sc_pkcs15emu_sc_hsm_get_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { if (cvc->publicPoint && cvc->publicPointlen) { return sc_pkcs15emu_sc_hsm_get_ec_public_key(ctx, cvc, pubkey); } else { return sc_pkcs15emu_sc_hsm_get_rsa_public_key(ctx, cvc, pubkey); } } void sc_pkcs15emu_sc_hsm_free_cvc(sc_cvc_t *cvc) { if (cvc->signature) { free(cvc->signature); cvc->signature = NULL; } if (cvc->primeOrModulus) { free(cvc->primeOrModulus); cvc->primeOrModulus = NULL; } if (cvc->coefficientAorExponent) { free(cvc->coefficientAorExponent); cvc->coefficientAorExponent = NULL; } if (cvc->coefficientB) { free(cvc->coefficientB); cvc->coefficientB = NULL; } if (cvc->basePointG) { free(cvc->basePointG); cvc->basePointG = NULL; } if (cvc->order) { free(cvc->order); cvc->order = NULL; } if (cvc->publicPoint) { free(cvc->publicPoint); cvc->publicPoint = NULL; } if (cvc->cofactor) { free(cvc->cofactor); cvc->cofactor = NULL; } } static int sc_pkcs15emu_sc_hsm_add_pubkey(sc_pkcs15_card_t *p15card, u8 *efbin, size_t len, sc_pkcs15_prkey_info_t *key_info, char *label) { struct sc_context *ctx = p15card->card->ctx; sc_card_t *card = p15card->card; sc_pkcs15_pubkey_info_t pubkey_info; sc_pkcs15_object_t pubkey_obj; struct sc_pkcs15_pubkey pubkey; sc_cvc_t cvc; u8 *cvcpo; int r; cvcpo = efbin; memset(&cvc, 0, sizeof(cvc)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&cvcpo, &len, &cvc); LOG_TEST_RET(ctx, r, "Could decode certificate signing request"); memset(&pubkey, 0, sizeof(pubkey)); r = sc_pkcs15emu_sc_hsm_get_public_key(ctx, &cvc, &pubkey); LOG_TEST_RET(card->ctx, r, "Could not extract public key"); memset(&pubkey_info, 0, sizeof(pubkey_info)); memset(&pubkey_obj, 0, sizeof(pubkey_obj)); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_obj.content.value, &pubkey_obj.content.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_info.direct.raw.value, &pubkey_info.direct.raw.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey_as_spki(ctx, &pubkey, &pubkey_info.direct.spki.value, &pubkey_info.direct.spki.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); pubkey_info.id = key_info->id; strlcpy(pubkey_obj.label, label, sizeof(pubkey_obj.label)); if (pubkey.algorithm == SC_ALGORITHM_RSA) { pubkey_info.modulus_length = pubkey.u.rsa.modulus.len << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_VERIFY|SC_PKCS15_PRKEY_USAGE_WRAP; r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info); } else { /* TODO fix if support of non multiple of 8 curves are added */ pubkey_info.field_length = cvc.primeOrModuluslen << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_VERIFY; r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info); } LOG_TEST_RET(ctx, r, "Could not add public key"); sc_pkcs15emu_sc_hsm_free_cvc(&cvc); sc_pkcs15_erase_pubkey(&pubkey); return SC_SUCCESS; } /* * Add a key and the key description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t cert_info; sc_pkcs15_object_t cert_obj; struct sc_pkcs15_object prkd; sc_pkcs15_prkey_info_t *key_info; u8 fid[2]; /* enough to hold a complete certificate */ u8 efbin[4096]; u8 *ptr; size_t len; int r; fid[0] = PRKD_PREFIX; fid[1] = keyid; /* Try to select a related EF containing the PKCS#15 description of the key */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); ptr = efbin; memset(&prkd, 0, sizeof(prkd)); r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); /* All keys require user PIN authentication */ prkd.auth_id.len = 1; prkd.auth_id.value[0] = 1; /* * Set private key flag as all keys are private anyway */ prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE; key_info = (sc_pkcs15_prkey_info_t *)prkd.data; key_info->key_reference = keyid; key_info->path.aid.len = 0; if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) { r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info); } else { r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info); } LOG_TEST_RET(card->ctx, r, "Could not add private key to framework"); /* Check if we also have a certificate for the private key */ fid[0] = EE_CERTIFICATE_PREFIX; len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 0); LOG_TEST_RET(card->ctx, r, "Could not read EF"); if (efbin[0] == 0x67) { /* Decode CSR and create public key object */ sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label); free(key_info); return SC_SUCCESS; /* Ignore any errors */ } if (efbin[0] != 0x30) { free(key_info); return SC_SUCCESS; } memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id = key_info->id; sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); cert_info.path.count = -1; if (p15card->opts.use_file_cache) { /* look this up with our AID, which should already be cached from the * call to `read_file`. This may have the side effect that OpenSC's * caching layer re-selects our applet *if the cached file cannot be * found/used* and we may loose the authentication status. We assume * that caching works perfectly without this side effect. */ cert_info.path.aid = sc_hsm_aid; } strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); free(key_info); LOG_TEST_RET(card->ctx, r, "Could not add certificate"); return SC_SUCCESS; } /* * Add a data object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_dcod(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_data_info_t *data_info; sc_pkcs15_object_t data_obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = DCOD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&data_obj, 0, sizeof(data_obj)); r = sc_pkcs15_decode_dodf_entry(p15card, &data_obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Could not decode optional EF.DCOD"); data_info = (sc_pkcs15_data_info_t *)data_obj.data; r = sc_pkcs15emu_add_data_object(p15card, &data_obj, data_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } /* * Add a unrelated certificate object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_cd(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t *cert_info; sc_pkcs15_object_t obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = CD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&obj, 0, sizeof(obj)); r = sc_pkcs15_decode_cdf_entry(p15card, &obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.CDOD"); cert_info = (sc_pkcs15_cert_info_t *)obj.data; r = sc_pkcs15emu_add_x509_cert(p15card, &obj, cert_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_read_tokeninfo (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; int r; u8 efbin[512]; size_t len; LOG_FUNC_CALLED(card->ctx); /* Read token info */ len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x03", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); r = sc_pkcs15_parse_tokeninfo(card->ctx, p15card->tokeninfo, efbin, len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Initialize PKCS#15 emulation with user PIN, private keys, certificate and data objects * */ static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data; sc_file_t *file = NULL; sc_path_t path; u8 filelist[MAX_EXT_APDU_LENGTH]; int filelistlength; int r, i; sc_cvc_t devcert; struct sc_app_info *appinfo; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; struct sc_pin_cmd_data pindata; u8 efbin[1024]; u8 *ptr; size_t len; LOG_FUNC_CALLED(card->ctx); appinfo = calloc(1, sizeof(struct sc_app_info)); if (appinfo == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->aid = sc_hsm_aid; appinfo->ddo.aid = sc_hsm_aid; p15card->app = appinfo; sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0); r = sc_select_file(card, &path, &file); LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application"); p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */ p15card->card->version.hw_minor = 13; if (file && file->prop_attr && file->prop_attr_len >= 2) { p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2]; p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1]; } sc_file_free(file); /* Read device certificate to determine serial number */ if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) { ptr = priv->EF_C_DevAut; len = priv->EF_C_DevAut_len; } else { len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut"); /* save EF_C_DevAut for further use */ ptr = realloc(priv->EF_C_DevAut, len); if (ptr) { memcpy(ptr, efbin, len); priv->EF_C_DevAut = ptr; priv->EF_C_DevAut_len = len; } ptr = efbin; } memset(&devcert, 0 ,sizeof(devcert)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert); LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut"); sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card); if (p15card->tokeninfo->label == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->label = strdup("GoID"); } else { p15card->tokeninfo->label = strdup("SmartCard-HSM"); } if (p15card->tokeninfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) { free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = NULL; } if (p15card->tokeninfo->manufacturer_id == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH"); } else { p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de"); } if (p15card->tokeninfo->manufacturer_id == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->label = strdup(p15card->tokeninfo->label); if (appinfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */ assert(len >= 8); len -= 5; p15card->tokeninfo->serial_number = calloc(len + 1, 1); if (p15card->tokeninfo->serial_number == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(p15card->tokeninfo->serial_number, devcert.chr, len); *(p15card->tokeninfo->serial_number + len) = 0; sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number); sc_pkcs15emu_sc_hsm_free_cvc(&devcert); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 1; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x81; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = 6; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 15; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 3; pin_info.max_tries = 3; pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 2; strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 2; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x88; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD; pin_info.attrs.pin.min_length = 16; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 16; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 15; pin_info.max_tries = 15; strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); if (card->type == SC_CARD_TYPE_SC_HSM_SOC || card->type == SC_CARD_TYPE_SC_HSM_GOID) { /* SC-HSM of this type always has a PIN-Pad */ r = SC_SUCCESS; } else { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x85; r = sc_pin_cmd(card, &pindata, NULL); } if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x86; r = sc_pin_cmd(card, &pindata, NULL); } if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS)) card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH; filelistlength = sc_list_files(card, filelist, sizeof(filelist)); LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier"); for (i = 0; i < filelistlength; i += 2) { switch(filelist[i]) { case KEY_PREFIX: r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]); break; case DCOD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]); break; case CD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]); break; } if (r != SC_SUCCESS) { sc_log(card->ctx, "Error %d adding elements to framework", r); } } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) { return sc_pkcs15emu_sc_hsm_init(p15card); } else { if (p15card->card->type != SC_CARD_TYPE_SC_HSM && p15card->card->type != SC_CARD_TYPE_SC_HSM_SOC && p15card->card->type != SC_CARD_TYPE_SC_HSM_GOID) { return SC_ERROR_WRONG_CARD; } return sc_pkcs15emu_sc_hsm_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_343_6
crossvul-cpp_data_bad_343_2
/* * card-muscle.c: Support for MuscleCard Applet from musclecard.com * * Copyright (C) 2006, Identity Alliance, Thomas Harning <support@identityalliance.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include "internal.h" #include "cardctl.h" #include "muscle.h" #include "muscle-filesystem.h" #include "types.h" #include "opensc.h" static struct sc_card_operations muscle_ops; static const struct sc_card_operations *iso_ops = NULL; static struct sc_card_driver muscle_drv = { "MuscleApplet", "muscle", &muscle_ops, NULL, 0, NULL }; static struct sc_atr_table muscle_atrs[] = { /* Tyfone JCOP 242R2 cards */ { "3b:6d:00:00:ff:54:79:66:6f:6e:65:20:32:34:32:52:32", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU, 0, NULL }, /* Aladdin eToken PRO USB 72K Java */ { "3b:d5:18:00:81:31:3a:7d:80:73:c8:21:10:30", NULL, NULL, SC_CARD_TYPE_MUSCLE_ETOKEN_72K, 0, NULL }, /* JCOP31 v2.4.1 contact interface */ { "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, /* JCOP31 v2.4.1 RF interface */ { "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; #define MUSCLE_DATA(card) ( (muscle_private_t*)card->drv_data ) #define MUSCLE_FS(card) ( ((muscle_private_t*)card->drv_data)->fs ) typedef struct muscle_private { sc_security_env_t env; unsigned short verifiedPins; mscfs_t *fs; int rsa_key_ref; } muscle_private_t; static int muscle_finish(sc_card_t *card) { muscle_private_t *priv = MUSCLE_DATA(card); mscfs_free(priv->fs); free(priv); return 0; } static u8 muscleAppletId[] = { 0xA0, 0x00,0x00,0x00, 0x01, 0x01 }; static int muscle_match_card(sc_card_t *card) { sc_apdu_t apdu; u8 response[64]; int r; /* Since we send an APDU, the card's logout function may be called... * however it's not always properly nulled out... */ card->ops->logout = NULL; if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) == 1) { /* Muscle applet is present, check the protocol version to be sure */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0x3C, 0x00, 0x00); apdu.cla = 0xB0; apdu.le = 64; apdu.resplen = 64; apdu.resp = response; r = sc_transmit_apdu(card, &apdu); if (r == SC_SUCCESS && response[0] == 0x01) { card->type = SC_CARD_TYPE_MUSCLE_V1; } else { card->type = SC_CARD_TYPE_MUSCLE_GENERIC; } return 1; } return 0; } /* Since Musclecard has a different ACL system then PKCS15 * objects need to have their READ/UPDATE/DELETE permissions mapped for files * and directory ACLS need to be set * For keys.. they have different ACLS, but are accessed in different locations, so it shouldn't be an issue here */ static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl) { unsigned short acl_entry = 0; while(acl) { int key = acl->key_ref; int method = acl->method; switch(method) { case SC_AC_NEVER: return 0xFFFF; /* Ignore... other items overwrite these */ case SC_AC_NONE: case SC_AC_UNKNOWN: break; case SC_AC_CHV: acl_entry |= (1 << key); /* Assuming key 0 == SO */ break; case SC_AC_AUT: case SC_AC_TERM: case SC_AC_PRO: default: /* Ignored */ break; } acl = acl->next; } return acl_entry; } static void muscle_parse_acls(const sc_file_t* file, unsigned short* read_perm, unsigned short* write_perm, unsigned short* delete_perm) { assert(read_perm && write_perm && delete_perm); *read_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_READ)); *write_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_UPDATE)); *delete_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_DELETE)); } static int muscle_create_directory(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); msc_id objectId; u8* oid = objectId.id; unsigned id = file->id; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; int objectSize; int r; if(id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; /* No nesting directories */ if(fs->currentPath[0] != 0x3F || fs->currentPath[1] != 0x00) return SC_ERROR_NOT_SUPPORTED; oid[0] = ((id & 0xFF00) >> 8) & 0xFF; oid[1] = id & 0xFF; oid[2] = oid[3] = 0; objectSize = file->size; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_create_file(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); int objectSize = file->size; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; msc_id objectId; int r; if(file->type == SC_FILE_TYPE_DF) return muscle_create_directory(card, file); if(file->type != SC_FILE_TYPE_WORKING_EF) return SC_ERROR_NOT_SUPPORTED; if(file->id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); mscfs_lookup_local(fs, file->id, &objectId); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_read_binary(sc_card_t *card, unsigned int idx, u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; msc_id objectId; u8* oid = objectId.id; mscfs_file_t *file; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } r = msc_read_object(card, objectId, idx, buf, count); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int muscle_update_binary(sc_card_t *card, unsigned int idx, const u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; mscfs_file_t *file; msc_id objectId; u8* oid = objectId.id; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } if(file->size < idx + count) { int newFileSize = idx + count; u8* buffer = malloc(newFileSize); if(buffer == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); r = msc_read_object(card, objectId, 0, buffer, file->size); /* TODO: RETRIEVE ACLS */ if(r < 0) goto update_bin_free_buffer; r = msc_delete_object(card, objectId, 0); if(r < 0) goto update_bin_free_buffer; r = msc_create_object(card, objectId, newFileSize, 0,0,0); if(r < 0) goto update_bin_free_buffer; memcpy(buffer + idx, buf, count); r = msc_update_object(card, objectId, 0, buffer, newFileSize); if(r < 0) goto update_bin_free_buffer; file->size = newFileSize; update_bin_free_buffer: free(buffer); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } else { r = msc_update_object(card, objectId, idx, buf, count); } /* mscfs_clear_cache(fs); */ return r; } /* TODO: Evaluate correctness */ static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data) { mscfs_t *fs = MUSCLE_FS(card); msc_id id = file_data->objectId; u8* oid = id.id; int r; if(!file_data->ef) { int x; mscfs_file_t *childFile; /* Delete children */ mscfs_check_cache(fs); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING Children of: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); for(x = 0; x < fs->cache.size; x++) { msc_id objectId; childFile = &fs->cache.array[x]; objectId = childFile->objectId; if(0 == memcmp(oid + 2, objectId.id, 2)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING: %02X%02X%02X%02X\n", objectId.id[0],objectId.id[1], objectId.id[2],objectId.id[3]); r = muscle_delete_mscfs_file(card, childFile); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } } oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; /* ??? objectId = objectId >> 16; */ } if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) { } r = msc_delete_object(card, id, 1); /* Check if its the root... this file generally is virtual * So don't return an error if it fails */ if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) return 0; if(r < 0) { printf("ID: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } return 0; } static int muscle_delete_file(sc_card_t *card, const sc_path_t *path_in) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int r = 0; r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, NULL); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); r = muscle_delete_mscfs_file(card, file_data); mscfs_clear_cache(fs); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); return 0; } static void muscle_load_single_acl(sc_file_t* file, int operation, unsigned short acl) { int key; /* Everybody by default.... */ sc_file_add_acl_entry(file, operation, SC_AC_NONE, 0); if(acl == 0xFFFF) { sc_file_add_acl_entry(file, operation, SC_AC_NEVER, 0); return; } for(key = 0; key < 16; key++) { if(acl >> key & 1) { sc_file_add_acl_entry(file, operation, SC_AC_CHV, key); } } } static void muscle_load_file_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_READ, file_data->read); muscle_load_single_acl(file, SC_AC_OP_WRITE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_UPDATE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); } static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_SELECT, 0); muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0); muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write); } /* Required type = -1 for don't care, 1 for EF, 0 for DF */ static int select_item(sc_card_t *card, const sc_path_t *path_in, sc_file_t ** file_out, int requiredType) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int pathlen = path_in->len; int r = 0; int objectIndex; u8* oid; mscfs_check_cache(fs); r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, &objectIndex); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); /* Check if its the right type */ if(requiredType >= 0 && requiredType != file_data->ef) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } oid = file_data->objectId.id; /* Is it a file or directory */ if(file_data->ef) { fs->currentPath[0] = oid[0]; fs->currentPath[1] = oid[1]; fs->currentFile[0] = oid[2]; fs->currentFile[1] = oid[3]; } else { fs->currentPath[0] = oid[pathlen - 2]; fs->currentPath[1] = oid[pathlen - 1]; fs->currentFile[0] = 0; fs->currentFile[1] = 0; } fs->currentFileIndex = objectIndex; if(file_out) { sc_file_t *file; file = sc_file_new(); file->path = *path_in; file->size = file_data->size; file->id = (oid[2] << 8) | oid[3]; if(!file_data->ef) { file->type = SC_FILE_TYPE_DF; } else { file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; } /* Setup ACLS */ if(file_data->ef) { muscle_load_file_acls(file, file_data); } else { muscle_load_dir_acls(file, file_data); /* Setup directory acls... */ } file->magic = SC_FILE_MAGIC; *file_out = file; } return 0; } static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in, sc_file_t **file_out) { int r; assert(card != NULL && path_in != NULL); switch (path_in->type) { case SC_PATH_TYPE_FILE_ID: r = select_item(card, path_in, file_out, 1); break; case SC_PATH_TYPE_DF_NAME: r = select_item(card, path_in, file_out, 0); break; case SC_PATH_TYPE_PATH: r = select_item(card, path_in, file_out, -1); break; default: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if(r > 0) r = 0; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } static int _listFile(mscfs_file_t *file, int reset, void *udata) { int next = reset ? 0x00 : 0x01; return msc_list_objects( (sc_card_t*)udata, next, file); } static int muscle_init(sc_card_t *card) { muscle_private_t *priv; card->name = "MuscleApplet"; card->drv_data = malloc(sizeof(muscle_private_t)); if(!card->drv_data) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } memset(card->drv_data, 0, sizeof(muscle_private_t)); priv = MUSCLE_DATA(card); priv->verifiedPins = 0; priv->fs = mscfs_new(); if(!priv->fs) { free(card->drv_data); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } priv->fs->udata = card; priv->fs->listFile = _listFile; card->cla = 0xB0; card->flags |= SC_CARD_FLAG_RNG; card->caps |= SC_CARD_CAP_RNG; /* Card type detection */ _sc_match_atr(card, muscle_atrs, &card->type); if(card->type == SC_CARD_TYPE_MUSCLE_ETOKEN_72K) { card->caps |= SC_CARD_CAP_APDU_EXT; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP241) { card->caps |= SC_CARD_CAP_APDU_EXT; } if (!(card->caps & SC_CARD_CAP_APDU_EXT)) { card->max_recv_size = 255; card->max_send_size = 255; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU) { /* Tyfone JCOP v242R2 card that doesn't support extended APDUs */ } /* FIXME: Card type detection */ if (1) { unsigned long flags; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_HASH_NONE; flags |= SC_ALGORITHM_ONBOARD_KEY_GEN; _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } return SC_SUCCESS; } static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen) { muscle_private_t* priv = MUSCLE_DATA(card); mscfs_t *fs = priv->fs; int x; int count = 0; mscfs_check_cache(priv->fs); for(x = 0; x < fs->cache.size; x++) { u8* oid= fs->cache.array[x].objectId.id; sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "FILE: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); if(0 == memcmp(fs->currentPath, oid, 2)) { buf[0] = oid[2]; buf[1] = oid[3]; if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */ buf += 2; count+=2; } } return count; } static int muscle_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *cmd, int *tries_left) { muscle_private_t* priv = MUSCLE_DATA(card); const int bufferLength = MSC_MAX_PIN_COMMAND_LENGTH; u8 buffer[MSC_MAX_PIN_COMMAND_LENGTH]; switch(cmd->cmd) { case SC_PIN_CMD_VERIFY: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; int r; msc_verify_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; cmd->pin1.offset = 5; r = iso_ops->pin_cmd(card, cmd, tries_left); if(r >= 0) priv->verifiedPins |= (1 << cmd->pin_reference); return r; } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_CHANGE: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_change_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len, cmd->pin2.data, cmd->pin2.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_UNBLOCK: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_unblock_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported command\n"); return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_extract_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 1: /* RSA */ return msc_extract_rsa_public_key(card, info->keyLocation, &info->modLength, &info->modValue, &info->expLength, &info->expValue); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_import_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 0x02: /* RSA_PRIVATE */ case 0x03: /* RSA_PRIVATE_CRT */ return msc_import_key(card, info->keyLocation, info); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_generate_key(sc_card_t *card, sc_cardctl_muscle_gen_key_info_t *info) { return msc_generate_keypair(card, info->privateKeyLocation, info->publicKeyLocation, info->keyType, info->keySize, 0); } static int muscle_card_verified_pins(sc_card_t *card, sc_cardctl_muscle_verified_pins_info_t *info) { muscle_private_t* priv = MUSCLE_DATA(card); info->verifiedPins = priv->verifiedPins; return 0; } static int muscle_card_ctl(sc_card_t *card, unsigned long request, void *data) { switch(request) { case SC_CARDCTL_MUSCLE_GENERATE_KEY: return muscle_card_generate_key(card, (sc_cardctl_muscle_gen_key_info_t*) data); case SC_CARDCTL_MUSCLE_EXTRACT_KEY: return muscle_card_extract_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_IMPORT_KEY: return muscle_card_import_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_VERIFIED_PINS: return muscle_card_verified_pins(card, (sc_cardctl_muscle_verified_pins_info_t*) data); default: return SC_ERROR_NOT_SUPPORTED; /* Unsupported.. whatever it is */ } } static int muscle_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); if (env->operation != SC_SEC_OPERATION_SIGN && env->operation != SC_SEC_OPERATION_DECIPHER) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto operation supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->algorithm != SC_ALGORITHM_RSA) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto algorithm supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } /* ADJUST FOR PKCS1 padding support for decryption only */ if ((env->algorithm_flags & SC_ALGORITHM_RSA_PADS) || (env->algorithm_flags & SC_ALGORITHM_RSA_HASHES)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card supports only raw RSA.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { if (env->key_ref_len != 1 || (env->key_ref[0] > 0x0F)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid key reference supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } priv->rsa_key_ref = env->key_ref[0]; } if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm reference not supported.\n"); return SC_ERROR_NOT_SUPPORTED; } /* if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) if (memcmp(env->file_ref.value, "\x00\x12", 2) != 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference is not 0012.\n"); return SC_ERROR_NOT_SUPPORTED; } */ priv->env = *env; return 0; } static int muscle_restore_security_env(sc_card_t *card, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); memset(&priv->env, 0, sizeof(priv->env)); return 0; } static int muscle_decipher(sc_card_t * card, const u8 * crgram, size_t crgram_len, u8 * out, size_t out_len) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; /* sanity check */ if (priv->env.operation != SC_SEC_OPERATION_DECIPHER) return SC_ERROR_INVALID_ARGUMENTS; key_id = priv->rsa_key_ref * 2; /* Private key */ if (out_len < crgram_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* decrypt */ crgram, out, crgram_len, out_len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_compute_signature(sc_card_t *card, const u8 *data, size_t data_len, u8 * out, size_t outlen) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; key_id = priv->rsa_key_ref * 2; /* Private key */ if (outlen < data_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* -- decrypt raw... will do what we need since signing isn't yet supported */ data, out, data_len, outlen); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { if (len == 0) return SC_SUCCESS; else { SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, msc_get_challenge(card, len, 0, NULL, rnd), "GET CHALLENGE cmd failed"); return (int) len; } } static int muscle_check_sw(sc_card_t * card, unsigned int sw1, unsigned int sw2) { if(sw1 == 0x9C) { switch(sw2) { case 0x01: /* SW_NO_MEMORY_LEFT */ return SC_ERROR_NOT_ENOUGH_MEMORY; case 0x02: /* SW_AUTH_FAILED */ return SC_ERROR_PIN_CODE_INCORRECT; case 0x03: /* SW_OPERATION_NOT_ALLOWED */ return SC_ERROR_NOT_ALLOWED; case 0x05: /* SW_UNSUPPORTED_FEATURE */ return SC_ERROR_NO_CARD_SUPPORT; case 0x06: /* SW_UNAUTHORIZED */ return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED; case 0x07: /* SW_OBJECT_NOT_FOUND */ return SC_ERROR_FILE_NOT_FOUND; case 0x08: /* SW_OBJECT_EXISTS */ return SC_ERROR_FILE_ALREADY_EXISTS; case 0x09: /* SW_INCORRECT_ALG */ return SC_ERROR_INCORRECT_PARAMETERS; case 0x0B: /* SW_SIGNATURE_INVALID */ return SC_ERROR_CARD_CMD_FAILED; case 0x0C: /* SW_IDENTITY_BLOCKED */ return SC_ERROR_AUTH_METHOD_BLOCKED; case 0x0F: /* SW_INVALID_PARAMETER */ case 0x10: /* SW_INCORRECT_P1 */ case 0x11: /* SW_INCORRECT_P2 */ return SC_ERROR_INCORRECT_PARAMETERS; } } return iso_ops->check_sw(card, sw1, sw2); } static int muscle_card_reader_lock_obtained(sc_card_t *card, int was_reset) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (was_reset > 0) { if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) != 1) { r = SC_ERROR_INVALID_CARD; } } LOG_FUNC_RETURN(card->ctx, r); } static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; muscle_ops = *iso_drv->ops; muscle_ops.check_sw = muscle_check_sw; muscle_ops.pin_cmd = muscle_pin_cmd; muscle_ops.match_card = muscle_match_card; muscle_ops.init = muscle_init; muscle_ops.finish = muscle_finish; muscle_ops.get_challenge = muscle_get_challenge; muscle_ops.set_security_env = muscle_set_security_env; muscle_ops.restore_security_env = muscle_restore_security_env; muscle_ops.compute_signature = muscle_compute_signature; muscle_ops.decipher = muscle_decipher; muscle_ops.card_ctl = muscle_card_ctl; muscle_ops.read_binary = muscle_read_binary; muscle_ops.update_binary = muscle_update_binary; muscle_ops.create_file = muscle_create_file; muscle_ops.select_file = muscle_select_file; muscle_ops.delete_file = muscle_delete_file; muscle_ops.list_files = muscle_list_files; muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained; return &muscle_drv; } struct sc_card_driver * sc_get_muscle_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_343_2
crossvul-cpp_data_good_3522_0
/* * Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved. * Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. */ #include <linux/spinlock.h> #include <linux/completion.h> #include <linux/buffer_head.h> #include <linux/blkdev.h> #include <linux/gfs2_ondisk.h> #include <linux/crc32.h> #include "gfs2.h" #include "incore.h" #include "bmap.h" #include "glock.h" #include "inode.h" #include "meta_io.h" #include "quota.h" #include "rgrp.h" #include "super.h" #include "trans.h" #include "dir.h" #include "util.h" #include "trace_gfs2.h" /* This doesn't need to be that large as max 64 bit pointers in a 4k * block is 512, so __u16 is fine for that. It saves stack space to * keep it small. */ struct metapath { struct buffer_head *mp_bh[GFS2_MAX_META_HEIGHT]; __u16 mp_list[GFS2_MAX_META_HEIGHT]; }; struct strip_mine { int sm_first; unsigned int sm_height; }; /** * gfs2_unstuffer_page - unstuff a stuffed inode into a block cached by a page * @ip: the inode * @dibh: the dinode buffer * @block: the block number that was allocated * @page: The (optional) page. This is looked up if @page is NULL * * Returns: errno */ static int gfs2_unstuffer_page(struct gfs2_inode *ip, struct buffer_head *dibh, u64 block, struct page *page) { struct inode *inode = &ip->i_inode; struct buffer_head *bh; int release = 0; if (!page || page->index) { page = grab_cache_page(inode->i_mapping, 0); if (!page) return -ENOMEM; release = 1; } if (!PageUptodate(page)) { void *kaddr = kmap(page); u64 dsize = i_size_read(inode); if (dsize > (dibh->b_size - sizeof(struct gfs2_dinode))) dsize = dibh->b_size - sizeof(struct gfs2_dinode); memcpy(kaddr, dibh->b_data + sizeof(struct gfs2_dinode), dsize); memset(kaddr + dsize, 0, PAGE_CACHE_SIZE - dsize); kunmap(page); SetPageUptodate(page); } if (!page_has_buffers(page)) create_empty_buffers(page, 1 << inode->i_blkbits, (1 << BH_Uptodate)); bh = page_buffers(page); if (!buffer_mapped(bh)) map_bh(bh, inode->i_sb, block); set_buffer_uptodate(bh); if (!gfs2_is_jdata(ip)) mark_buffer_dirty(bh); if (!gfs2_is_writeback(ip)) gfs2_trans_add_bh(ip->i_gl, bh, 0); if (release) { unlock_page(page); page_cache_release(page); } return 0; } /** * gfs2_unstuff_dinode - Unstuff a dinode when the data has grown too big * @ip: The GFS2 inode to unstuff * @page: The (optional) page. This is looked up if the @page is NULL * * This routine unstuffs a dinode and returns it to a "normal" state such * that the height can be grown in the traditional way. * * Returns: errno */ int gfs2_unstuff_dinode(struct gfs2_inode *ip, struct page *page) { struct buffer_head *bh, *dibh; struct gfs2_dinode *di; u64 block = 0; int isdir = gfs2_is_dir(ip); int error; down_write(&ip->i_rw_mutex); error = gfs2_meta_inode_buffer(ip, &dibh); if (error) goto out; if (i_size_read(&ip->i_inode)) { /* Get a free block, fill it with the stuffed data, and write it out to disk */ unsigned int n = 1; error = gfs2_alloc_block(ip, &block, &n); if (error) goto out_brelse; if (isdir) { gfs2_trans_add_unrevoke(GFS2_SB(&ip->i_inode), block, 1); error = gfs2_dir_get_new_buffer(ip, block, &bh); if (error) goto out_brelse; gfs2_buffer_copy_tail(bh, sizeof(struct gfs2_meta_header), dibh, sizeof(struct gfs2_dinode)); brelse(bh); } else { error = gfs2_unstuffer_page(ip, dibh, block, page); if (error) goto out_brelse; } } /* Set up the pointer to the new block */ gfs2_trans_add_bh(ip->i_gl, dibh, 1); di = (struct gfs2_dinode *)dibh->b_data; gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode)); if (i_size_read(&ip->i_inode)) { *(__be64 *)(di + 1) = cpu_to_be64(block); gfs2_add_inode_blocks(&ip->i_inode, 1); di->di_blocks = cpu_to_be64(gfs2_get_inode_blocks(&ip->i_inode)); } ip->i_height = 1; di->di_height = cpu_to_be16(1); out_brelse: brelse(dibh); out: up_write(&ip->i_rw_mutex); return error; } /** * find_metapath - Find path through the metadata tree * @sdp: The superblock * @mp: The metapath to return the result in * @block: The disk block to look up * @height: The pre-calculated height of the metadata tree * * This routine returns a struct metapath structure that defines a path * through the metadata of inode "ip" to get to block "block". * * Example: * Given: "ip" is a height 3 file, "offset" is 101342453, and this is a * filesystem with a blocksize of 4096. * * find_metapath() would return a struct metapath structure set to: * mp_offset = 101342453, mp_height = 3, mp_list[0] = 0, mp_list[1] = 48, * and mp_list[2] = 165. * * That means that in order to get to the block containing the byte at * offset 101342453, we would load the indirect block pointed to by pointer * 0 in the dinode. We would then load the indirect block pointed to by * pointer 48 in that indirect block. We would then load the data block * pointed to by pointer 165 in that indirect block. * * ---------------------------------------- * | Dinode | | * | | 4| * | |0 1 2 3 4 5 9| * | | 6| * ---------------------------------------- * | * | * V * ---------------------------------------- * | Indirect Block | * | 5| * | 4 4 4 4 4 5 5 1| * |0 5 6 7 8 9 0 1 2| * ---------------------------------------- * | * | * V * ---------------------------------------- * | Indirect Block | * | 1 1 1 1 1 5| * | 6 6 6 6 6 1| * |0 3 4 5 6 7 2| * ---------------------------------------- * | * | * V * ---------------------------------------- * | Data block containing offset | * | 101342453 | * | | * | | * ---------------------------------------- * */ static void find_metapath(const struct gfs2_sbd *sdp, u64 block, struct metapath *mp, unsigned int height) { unsigned int i; for (i = height; i--;) mp->mp_list[i] = do_div(block, sdp->sd_inptrs); } static inline unsigned int metapath_branch_start(const struct metapath *mp) { if (mp->mp_list[0] == 0) return 2; return 1; } /** * metapointer - Return pointer to start of metadata in a buffer * @height: The metadata height (0 = dinode) * @mp: The metapath * * Return a pointer to the block number of the next height of the metadata * tree given a buffer containing the pointer to the current height of the * metadata tree. */ static inline __be64 *metapointer(unsigned int height, const struct metapath *mp) { struct buffer_head *bh = mp->mp_bh[height]; unsigned int head_size = (height > 0) ? sizeof(struct gfs2_meta_header) : sizeof(struct gfs2_dinode); return ((__be64 *)(bh->b_data + head_size)) + mp->mp_list[height]; } /** * lookup_metapath - Walk the metadata tree to a specific point * @ip: The inode * @mp: The metapath * * Assumes that the inode's buffer has already been looked up and * hooked onto mp->mp_bh[0] and that the metapath has been initialised * by find_metapath(). * * If this function encounters part of the tree which has not been * allocated, it returns the current height of the tree at the point * at which it found the unallocated block. Blocks which are found are * added to the mp->mp_bh[] list. * * Returns: error or height of metadata tree */ static int lookup_metapath(struct gfs2_inode *ip, struct metapath *mp) { unsigned int end_of_metadata = ip->i_height - 1; unsigned int x; __be64 *ptr; u64 dblock; int ret; for (x = 0; x < end_of_metadata; x++) { ptr = metapointer(x, mp); dblock = be64_to_cpu(*ptr); if (!dblock) return x + 1; ret = gfs2_meta_indirect_buffer(ip, x+1, dblock, 0, &mp->mp_bh[x+1]); if (ret) return ret; } return ip->i_height; } static inline void release_metapath(struct metapath *mp) { int i; for (i = 0; i < GFS2_MAX_META_HEIGHT; i++) { if (mp->mp_bh[i] == NULL) break; brelse(mp->mp_bh[i]); } } /** * gfs2_extent_length - Returns length of an extent of blocks * @start: Start of the buffer * @len: Length of the buffer in bytes * @ptr: Current position in the buffer * @limit: Max extent length to return (0 = unlimited) * @eob: Set to 1 if we hit "end of block" * * If the first block is zero (unallocated) it will return the number of * unallocated blocks in the extent, otherwise it will return the number * of contiguous blocks in the extent. * * Returns: The length of the extent (minimum of one block) */ static inline unsigned int gfs2_extent_length(void *start, unsigned int len, __be64 *ptr, unsigned limit, int *eob) { const __be64 *end = (start + len); const __be64 *first = ptr; u64 d = be64_to_cpu(*ptr); *eob = 0; do { ptr++; if (ptr >= end) break; if (limit && --limit == 0) break; if (d) d++; } while(be64_to_cpu(*ptr) == d); if (ptr >= end) *eob = 1; return (ptr - first); } static inline void bmap_lock(struct gfs2_inode *ip, int create) { if (create) down_write(&ip->i_rw_mutex); else down_read(&ip->i_rw_mutex); } static inline void bmap_unlock(struct gfs2_inode *ip, int create) { if (create) up_write(&ip->i_rw_mutex); else up_read(&ip->i_rw_mutex); } static inline __be64 *gfs2_indirect_init(struct metapath *mp, struct gfs2_glock *gl, unsigned int i, unsigned offset, u64 bn) { __be64 *ptr = (__be64 *)(mp->mp_bh[i - 1]->b_data + ((i > 1) ? sizeof(struct gfs2_meta_header) : sizeof(struct gfs2_dinode))); BUG_ON(i < 1); BUG_ON(mp->mp_bh[i] != NULL); mp->mp_bh[i] = gfs2_meta_new(gl, bn); gfs2_trans_add_bh(gl, mp->mp_bh[i], 1); gfs2_metatype_set(mp->mp_bh[i], GFS2_METATYPE_IN, GFS2_FORMAT_IN); gfs2_buffer_clear_tail(mp->mp_bh[i], sizeof(struct gfs2_meta_header)); ptr += offset; *ptr = cpu_to_be64(bn); return ptr; } enum alloc_state { ALLOC_DATA = 0, ALLOC_GROW_DEPTH = 1, ALLOC_GROW_HEIGHT = 2, /* ALLOC_UNSTUFF = 3, TBD and rather complicated */ }; /** * gfs2_bmap_alloc - Build a metadata tree of the requested height * @inode: The GFS2 inode * @lblock: The logical starting block of the extent * @bh_map: This is used to return the mapping details * @mp: The metapath * @sheight: The starting height (i.e. whats already mapped) * @height: The height to build to * @maxlen: The max number of data blocks to alloc * * In this routine we may have to alloc: * i) Indirect blocks to grow the metadata tree height * ii) Indirect blocks to fill in lower part of the metadata tree * iii) Data blocks * * The function is in two parts. The first part works out the total * number of blocks which we need. The second part does the actual * allocation asking for an extent at a time (if enough contiguous free * blocks are available, there will only be one request per bmap call) * and uses the state machine to initialise the blocks in order. * * Returns: errno on error */ static int gfs2_bmap_alloc(struct inode *inode, const sector_t lblock, struct buffer_head *bh_map, struct metapath *mp, const unsigned int sheight, const unsigned int height, const unsigned int maxlen) { struct gfs2_inode *ip = GFS2_I(inode); struct gfs2_sbd *sdp = GFS2_SB(inode); struct super_block *sb = sdp->sd_vfs; struct buffer_head *dibh = mp->mp_bh[0]; u64 bn, dblock = 0; unsigned n, i, blks, alloced = 0, iblks = 0, branch_start = 0; unsigned dblks = 0; unsigned ptrs_per_blk; const unsigned end_of_metadata = height - 1; int ret; int eob = 0; enum alloc_state state; __be64 *ptr; __be64 zero_bn = 0; BUG_ON(sheight < 1); BUG_ON(dibh == NULL); gfs2_trans_add_bh(ip->i_gl, dibh, 1); if (height == sheight) { struct buffer_head *bh; /* Bottom indirect block exists, find unalloced extent size */ ptr = metapointer(end_of_metadata, mp); bh = mp->mp_bh[end_of_metadata]; dblks = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen, &eob); BUG_ON(dblks < 1); state = ALLOC_DATA; } else { /* Need to allocate indirect blocks */ ptrs_per_blk = height > 1 ? sdp->sd_inptrs : sdp->sd_diptrs; dblks = min(maxlen, ptrs_per_blk - mp->mp_list[end_of_metadata]); if (height == ip->i_height) { /* Writing into existing tree, extend tree down */ iblks = height - sheight; state = ALLOC_GROW_DEPTH; } else { /* Building up tree height */ state = ALLOC_GROW_HEIGHT; iblks = height - ip->i_height; branch_start = metapath_branch_start(mp); iblks += (height - branch_start); } } /* start of the second part of the function (state machine) */ blks = dblks + iblks; i = sheight; do { int error; n = blks - alloced; error = gfs2_alloc_block(ip, &bn, &n); if (error) return error; alloced += n; if (state != ALLOC_DATA || gfs2_is_jdata(ip)) gfs2_trans_add_unrevoke(sdp, bn, n); switch (state) { /* Growing height of tree */ case ALLOC_GROW_HEIGHT: if (i == 1) { ptr = (__be64 *)(dibh->b_data + sizeof(struct gfs2_dinode)); zero_bn = *ptr; } for (; i - 1 < height - ip->i_height && n > 0; i++, n--) gfs2_indirect_init(mp, ip->i_gl, i, 0, bn++); if (i - 1 == height - ip->i_height) { i--; gfs2_buffer_copy_tail(mp->mp_bh[i], sizeof(struct gfs2_meta_header), dibh, sizeof(struct gfs2_dinode)); gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode) + sizeof(__be64)); ptr = (__be64 *)(mp->mp_bh[i]->b_data + sizeof(struct gfs2_meta_header)); *ptr = zero_bn; state = ALLOC_GROW_DEPTH; for(i = branch_start; i < height; i++) { if (mp->mp_bh[i] == NULL) break; brelse(mp->mp_bh[i]); mp->mp_bh[i] = NULL; } i = branch_start; } if (n == 0) break; /* Branching from existing tree */ case ALLOC_GROW_DEPTH: if (i > 1 && i < height) gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[i-1], 1); for (; i < height && n > 0; i++, n--) gfs2_indirect_init(mp, ip->i_gl, i, mp->mp_list[i-1], bn++); if (i == height) state = ALLOC_DATA; if (n == 0) break; /* Tree complete, adding data blocks */ case ALLOC_DATA: BUG_ON(n > dblks); BUG_ON(mp->mp_bh[end_of_metadata] == NULL); gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[end_of_metadata], 1); dblks = n; ptr = metapointer(end_of_metadata, mp); dblock = bn; while (n-- > 0) *ptr++ = cpu_to_be64(bn++); if (buffer_zeronew(bh_map)) { ret = sb_issue_zeroout(sb, dblock, dblks, GFP_NOFS); if (ret) { fs_err(sdp, "Failed to zero data buffers\n"); clear_buffer_zeronew(bh_map); } } break; } } while ((state != ALLOC_DATA) || !dblock); ip->i_height = height; gfs2_add_inode_blocks(&ip->i_inode, alloced); gfs2_dinode_out(ip, mp->mp_bh[0]->b_data); map_bh(bh_map, inode->i_sb, dblock); bh_map->b_size = dblks << inode->i_blkbits; set_buffer_new(bh_map); return 0; } /** * gfs2_block_map - Map a block from an inode to a disk block * @inode: The inode * @lblock: The logical block number * @bh_map: The bh to be mapped * @create: True if its ok to alloc blocks to satify the request * * Sets buffer_mapped() if successful, sets buffer_boundary() if a * read of metadata will be required before the next block can be * mapped. Sets buffer_new() if new blocks were allocated. * * Returns: errno */ int gfs2_block_map(struct inode *inode, sector_t lblock, struct buffer_head *bh_map, int create) { struct gfs2_inode *ip = GFS2_I(inode); struct gfs2_sbd *sdp = GFS2_SB(inode); unsigned int bsize = sdp->sd_sb.sb_bsize; const unsigned int maxlen = bh_map->b_size >> inode->i_blkbits; const u64 *arr = sdp->sd_heightsize; __be64 *ptr; u64 size; struct metapath mp; int ret; int eob; unsigned int len; struct buffer_head *bh; u8 height; BUG_ON(maxlen == 0); memset(mp.mp_bh, 0, sizeof(mp.mp_bh)); bmap_lock(ip, create); clear_buffer_mapped(bh_map); clear_buffer_new(bh_map); clear_buffer_boundary(bh_map); trace_gfs2_bmap(ip, bh_map, lblock, create, 1); if (gfs2_is_dir(ip)) { bsize = sdp->sd_jbsize; arr = sdp->sd_jheightsize; } ret = gfs2_meta_inode_buffer(ip, &mp.mp_bh[0]); if (ret) goto out; height = ip->i_height; size = (lblock + 1) * bsize; while (size > arr[height]) height++; find_metapath(sdp, lblock, &mp, height); ret = 1; if (height > ip->i_height || gfs2_is_stuffed(ip)) goto do_alloc; ret = lookup_metapath(ip, &mp); if (ret < 0) goto out; if (ret != ip->i_height) goto do_alloc; ptr = metapointer(ip->i_height - 1, &mp); if (*ptr == 0) goto do_alloc; map_bh(bh_map, inode->i_sb, be64_to_cpu(*ptr)); bh = mp.mp_bh[ip->i_height - 1]; len = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen, &eob); bh_map->b_size = (len << inode->i_blkbits); if (eob) set_buffer_boundary(bh_map); ret = 0; out: release_metapath(&mp); trace_gfs2_bmap(ip, bh_map, lblock, create, ret); bmap_unlock(ip, create); return ret; do_alloc: /* All allocations are done here, firstly check create flag */ if (!create) { BUG_ON(gfs2_is_stuffed(ip)); ret = 0; goto out; } /* At this point ret is the tree depth of already allocated blocks */ ret = gfs2_bmap_alloc(inode, lblock, bh_map, &mp, ret, height, maxlen); goto out; } /* * Deprecated: do not use in new code */ int gfs2_extent_map(struct inode *inode, u64 lblock, int *new, u64 *dblock, unsigned *extlen) { struct buffer_head bh = { .b_state = 0, .b_blocknr = 0 }; int ret; int create = *new; BUG_ON(!extlen); BUG_ON(!dblock); BUG_ON(!new); bh.b_size = 1 << (inode->i_blkbits + (create ? 0 : 5)); ret = gfs2_block_map(inode, lblock, &bh, create); *extlen = bh.b_size >> inode->i_blkbits; *dblock = bh.b_blocknr; if (buffer_new(&bh)) *new = 1; else *new = 0; return ret; } /** * do_strip - Look for a layer a particular layer of the file and strip it off * @ip: the inode * @dibh: the dinode buffer * @bh: A buffer of pointers * @top: The first pointer in the buffer * @bottom: One more than the last pointer * @height: the height this buffer is at * @data: a pointer to a struct strip_mine * * Returns: errno */ static int do_strip(struct gfs2_inode *ip, struct buffer_head *dibh, struct buffer_head *bh, __be64 *top, __be64 *bottom, unsigned int height, struct strip_mine *sm) { struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode); struct gfs2_rgrp_list rlist; u64 bn, bstart; u32 blen, btotal; __be64 *p; unsigned int rg_blocks = 0; int metadata; unsigned int revokes = 0; int x; int error = 0; if (!*top) sm->sm_first = 0; if (height != sm->sm_height) return 0; if (sm->sm_first) { top++; sm->sm_first = 0; } metadata = (height != ip->i_height - 1); if (metadata) revokes = (height) ? sdp->sd_inptrs : sdp->sd_diptrs; else if (ip->i_depth) revokes = sdp->sd_inptrs; if (error) return error; memset(&rlist, 0, sizeof(struct gfs2_rgrp_list)); bstart = 0; blen = 0; for (p = top; p < bottom; p++) { if (!*p) continue; bn = be64_to_cpu(*p); if (bstart + blen == bn) blen++; else { if (bstart) gfs2_rlist_add(ip, &rlist, bstart); bstart = bn; blen = 1; } } if (bstart) gfs2_rlist_add(ip, &rlist, bstart); else goto out; /* Nothing to do */ gfs2_rlist_alloc(&rlist, LM_ST_EXCLUSIVE); for (x = 0; x < rlist.rl_rgrps; x++) { struct gfs2_rgrpd *rgd; rgd = rlist.rl_ghs[x].gh_gl->gl_object; rg_blocks += rgd->rd_length; } error = gfs2_glock_nq_m(rlist.rl_rgrps, rlist.rl_ghs); if (error) goto out_rlist; error = gfs2_trans_begin(sdp, rg_blocks + RES_DINODE + RES_INDIRECT + RES_STATFS + RES_QUOTA, revokes); if (error) goto out_rg_gunlock; down_write(&ip->i_rw_mutex); gfs2_trans_add_bh(ip->i_gl, dibh, 1); gfs2_trans_add_bh(ip->i_gl, bh, 1); bstart = 0; blen = 0; btotal = 0; for (p = top; p < bottom; p++) { if (!*p) continue; bn = be64_to_cpu(*p); if (bstart + blen == bn) blen++; else { if (bstart) { __gfs2_free_blocks(ip, bstart, blen, metadata); btotal += blen; } bstart = bn; blen = 1; } *p = 0; gfs2_add_inode_blocks(&ip->i_inode, -1); } if (bstart) { __gfs2_free_blocks(ip, bstart, blen, metadata); btotal += blen; } gfs2_statfs_change(sdp, 0, +btotal, 0); gfs2_quota_change(ip, -(s64)btotal, ip->i_inode.i_uid, ip->i_inode.i_gid); ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME; gfs2_dinode_out(ip, dibh->b_data); up_write(&ip->i_rw_mutex); gfs2_trans_end(sdp); out_rg_gunlock: gfs2_glock_dq_m(rlist.rl_rgrps, rlist.rl_ghs); out_rlist: gfs2_rlist_free(&rlist); out: return error; } /** * recursive_scan - recursively scan through the end of a file * @ip: the inode * @dibh: the dinode buffer * @mp: the path through the metadata to the point to start * @height: the height the recursion is at * @block: the indirect block to look at * @first: 1 if this is the first block * @sm: data opaque to this function to pass to @bc * * When this is first called @height and @block should be zero and * @first should be 1. * * Returns: errno */ static int recursive_scan(struct gfs2_inode *ip, struct buffer_head *dibh, struct metapath *mp, unsigned int height, u64 block, int first, struct strip_mine *sm) { struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode); struct buffer_head *bh = NULL; __be64 *top, *bottom, *t2; u64 bn; int error; int mh_size = sizeof(struct gfs2_meta_header); if (!height) { error = gfs2_meta_inode_buffer(ip, &bh); if (error) return error; dibh = bh; top = (__be64 *)(bh->b_data + sizeof(struct gfs2_dinode)) + mp->mp_list[0]; bottom = (__be64 *)(bh->b_data + sizeof(struct gfs2_dinode)) + sdp->sd_diptrs; } else { error = gfs2_meta_indirect_buffer(ip, height, block, 0, &bh); if (error) return error; top = (__be64 *)(bh->b_data + mh_size) + (first ? mp->mp_list[height] : 0); bottom = (__be64 *)(bh->b_data + mh_size) + sdp->sd_inptrs; } error = do_strip(ip, dibh, bh, top, bottom, height, sm); if (error) goto out; if (height < ip->i_height - 1) { struct buffer_head *rabh; for (t2 = top; t2 < bottom; t2++, first = 0) { if (!*t2) continue; bn = be64_to_cpu(*t2); rabh = gfs2_getbuf(ip->i_gl, bn, CREATE); if (trylock_buffer(rabh)) { if (buffer_uptodate(rabh)) { unlock_buffer(rabh); brelse(rabh); continue; } rabh->b_end_io = end_buffer_read_sync; submit_bh(READA | REQ_META, rabh); continue; } brelse(rabh); } for (; top < bottom; top++, first = 0) { if (!*top) continue; bn = be64_to_cpu(*top); error = recursive_scan(ip, dibh, mp, height + 1, bn, first, sm); if (error) break; } } out: brelse(bh); return error; } /** * gfs2_block_truncate_page - Deal with zeroing out data for truncate * * This is partly borrowed from ext3. */ static int gfs2_block_truncate_page(struct address_space *mapping, loff_t from) { struct inode *inode = mapping->host; struct gfs2_inode *ip = GFS2_I(inode); unsigned long index = from >> PAGE_CACHE_SHIFT; unsigned offset = from & (PAGE_CACHE_SIZE-1); unsigned blocksize, iblock, length, pos; struct buffer_head *bh; struct page *page; int err; page = grab_cache_page(mapping, index); if (!page) return 0; blocksize = inode->i_sb->s_blocksize; length = blocksize - (offset & (blocksize - 1)); iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits); if (!page_has_buffers(page)) create_empty_buffers(page, blocksize, 0); /* Find the buffer that contains "offset" */ bh = page_buffers(page); pos = blocksize; while (offset >= pos) { bh = bh->b_this_page; iblock++; pos += blocksize; } err = 0; if (!buffer_mapped(bh)) { gfs2_block_map(inode, iblock, bh, 0); /* unmapped? It's a hole - nothing to do */ if (!buffer_mapped(bh)) goto unlock; } /* Ok, it's mapped. Make sure it's up-to-date */ if (PageUptodate(page)) set_buffer_uptodate(bh); if (!buffer_uptodate(bh)) { err = -EIO; ll_rw_block(READ, 1, &bh); wait_on_buffer(bh); /* Uhhuh. Read error. Complain and punt. */ if (!buffer_uptodate(bh)) goto unlock; err = 0; } if (!gfs2_is_writeback(ip)) gfs2_trans_add_bh(ip->i_gl, bh, 0); zero_user(page, offset, length); mark_buffer_dirty(bh); unlock: unlock_page(page); page_cache_release(page); return err; } static int trunc_start(struct inode *inode, u64 oldsize, u64 newsize) { struct gfs2_inode *ip = GFS2_I(inode); struct gfs2_sbd *sdp = GFS2_SB(inode); struct address_space *mapping = inode->i_mapping; struct buffer_head *dibh; int journaled = gfs2_is_jdata(ip); int error; error = gfs2_trans_begin(sdp, RES_DINODE + (journaled ? RES_JDATA : 0), 0); if (error) return error; error = gfs2_meta_inode_buffer(ip, &dibh); if (error) goto out; gfs2_trans_add_bh(ip->i_gl, dibh, 1); if (gfs2_is_stuffed(ip)) { gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode) + newsize); } else { if (newsize & (u64)(sdp->sd_sb.sb_bsize - 1)) { error = gfs2_block_truncate_page(mapping, newsize); if (error) goto out_brelse; } ip->i_diskflags |= GFS2_DIF_TRUNC_IN_PROG; } i_size_write(inode, newsize); ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME; gfs2_dinode_out(ip, dibh->b_data); truncate_pagecache(inode, oldsize, newsize); out_brelse: brelse(dibh); out: gfs2_trans_end(sdp); return error; } static int trunc_dealloc(struct gfs2_inode *ip, u64 size) { struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode); unsigned int height = ip->i_height; u64 lblock; struct metapath mp; int error; if (!size) lblock = 0; else lblock = (size - 1) >> sdp->sd_sb.sb_bsize_shift; find_metapath(sdp, lblock, &mp, ip->i_height); if (!gfs2_alloc_get(ip)) return -ENOMEM; error = gfs2_quota_hold(ip, NO_QUOTA_CHANGE, NO_QUOTA_CHANGE); if (error) goto out; while (height--) { struct strip_mine sm; sm.sm_first = !!size; sm.sm_height = height; error = recursive_scan(ip, NULL, &mp, 0, 0, 1, &sm); if (error) break; } gfs2_quota_unhold(ip); out: gfs2_alloc_put(ip); return error; } static int trunc_end(struct gfs2_inode *ip) { struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode); struct buffer_head *dibh; int error; error = gfs2_trans_begin(sdp, RES_DINODE, 0); if (error) return error; down_write(&ip->i_rw_mutex); error = gfs2_meta_inode_buffer(ip, &dibh); if (error) goto out; if (!i_size_read(&ip->i_inode)) { ip->i_height = 0; ip->i_goal = ip->i_no_addr; gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode)); } ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME; ip->i_diskflags &= ~GFS2_DIF_TRUNC_IN_PROG; gfs2_trans_add_bh(ip->i_gl, dibh, 1); gfs2_dinode_out(ip, dibh->b_data); brelse(dibh); out: up_write(&ip->i_rw_mutex); gfs2_trans_end(sdp); return error; } /** * do_shrink - make a file smaller * @inode: the inode * @oldsize: the current inode size * @newsize: the size to make the file * * Called with an exclusive lock on @inode. The @size must * be equal to or smaller than the current inode size. * * Returns: errno */ static int do_shrink(struct inode *inode, u64 oldsize, u64 newsize) { struct gfs2_inode *ip = GFS2_I(inode); int error; error = trunc_start(inode, oldsize, newsize); if (error < 0) return error; if (gfs2_is_stuffed(ip)) return 0; error = trunc_dealloc(ip, newsize); if (error == 0) error = trunc_end(ip); return error; } void gfs2_trim_blocks(struct inode *inode) { u64 size = inode->i_size; int ret; ret = do_shrink(inode, size, size); WARN_ON(ret != 0); } /** * do_grow - Touch and update inode size * @inode: The inode * @size: The new size * * This function updates the timestamps on the inode and * may also increase the size of the inode. This function * must not be called with @size any smaller than the current * inode size. * * Although it is not strictly required to unstuff files here, * earlier versions of GFS2 have a bug in the stuffed file reading * code which will result in a buffer overrun if the size is larger * than the max stuffed file size. In order to prevent this from * occurring, such files are unstuffed, but in other cases we can * just update the inode size directly. * * Returns: 0 on success, or -ve on error */ static int do_grow(struct inode *inode, u64 size) { struct gfs2_inode *ip = GFS2_I(inode); struct gfs2_sbd *sdp = GFS2_SB(inode); struct buffer_head *dibh; struct gfs2_alloc *al = NULL; int error; if (gfs2_is_stuffed(ip) && (size > (sdp->sd_sb.sb_bsize - sizeof(struct gfs2_dinode)))) { al = gfs2_alloc_get(ip); if (al == NULL) return -ENOMEM; error = gfs2_quota_lock_check(ip); if (error) goto do_grow_alloc_put; al->al_requested = 1; error = gfs2_inplace_reserve(ip); if (error) goto do_grow_qunlock; } error = gfs2_trans_begin(sdp, RES_DINODE + RES_STATFS + RES_RG_BIT, 0); if (error) goto do_grow_release; if (al) { error = gfs2_unstuff_dinode(ip, NULL); if (error) goto do_end_trans; } error = gfs2_meta_inode_buffer(ip, &dibh); if (error) goto do_end_trans; i_size_write(inode, size); ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME; gfs2_trans_add_bh(ip->i_gl, dibh, 1); gfs2_dinode_out(ip, dibh->b_data); brelse(dibh); do_end_trans: gfs2_trans_end(sdp); do_grow_release: if (al) { gfs2_inplace_release(ip); do_grow_qunlock: gfs2_quota_unlock(ip); do_grow_alloc_put: gfs2_alloc_put(ip); } return error; } /** * gfs2_setattr_size - make a file a given size * @inode: the inode * @newsize: the size to make the file * * The file size can grow, shrink, or stay the same size. This * is called holding i_mutex and an exclusive glock on the inode * in question. * * Returns: errno */ int gfs2_setattr_size(struct inode *inode, u64 newsize) { int ret; u64 oldsize; BUG_ON(!S_ISREG(inode->i_mode)); ret = inode_newsize_ok(inode, newsize); if (ret) return ret; inode_dio_wait(inode); oldsize = inode->i_size; if (newsize >= oldsize) return do_grow(inode, newsize); return do_shrink(inode, oldsize, newsize); } int gfs2_truncatei_resume(struct gfs2_inode *ip) { int error; error = trunc_dealloc(ip, i_size_read(&ip->i_inode)); if (!error) error = trunc_end(ip); return error; } int gfs2_file_dealloc(struct gfs2_inode *ip) { return trunc_dealloc(ip, 0); } /** * gfs2_write_alloc_required - figure out if a write will require an allocation * @ip: the file being written to * @offset: the offset to write to * @len: the number of bytes being written * * Returns: 1 if an alloc is required, 0 otherwise */ int gfs2_write_alloc_required(struct gfs2_inode *ip, u64 offset, unsigned int len) { struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode); struct buffer_head bh; unsigned int shift; u64 lblock, lblock_stop, size; u64 end_of_file; if (!len) return 0; if (gfs2_is_stuffed(ip)) { if (offset + len > sdp->sd_sb.sb_bsize - sizeof(struct gfs2_dinode)) return 1; return 0; } shift = sdp->sd_sb.sb_bsize_shift; BUG_ON(gfs2_is_dir(ip)); end_of_file = (i_size_read(&ip->i_inode) + sdp->sd_sb.sb_bsize - 1) >> shift; lblock = offset >> shift; lblock_stop = (offset + len + sdp->sd_sb.sb_bsize - 1) >> shift; if (lblock_stop > end_of_file) return 1; size = (lblock_stop - lblock) << shift; do { bh.b_state = 0; bh.b_size = size; gfs2_block_map(&ip->i_inode, lblock, &bh, 0); if (!buffer_mapped(&bh)) return 1; size -= bh.b_size; lblock += (bh.b_size >> ip->i_inode.i_blkbits); } while(size > 0); return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_3522_0
crossvul-cpp_data_good_1299_0
/* * card-cac1.c: Support for legacy CAC-1 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL #include <openssl/sha.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #include "card-cac-common.h" /* * CAC hardware and APDU constants */ #define CAC_INS_GET_CERTIFICATE 0x36 /* CAC1 command to read a certificate */ /* * OLD cac read certificate, only use with CAC-1 card. */ static int cac_cac1_get_certificate(sc_card_t *card, u8 **out_buf, size_t *out_len) { u8 buf[CAC_MAX_SIZE]; u8 *out_ptr; size_t size = 0; size_t left = 0; size_t len; sc_apdu_t apdu; int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* get the size */ size = left = *out_buf ? *out_len : sizeof(buf); out_ptr = *out_buf ? *out_buf : buf; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, CAC_INS_GET_CERTIFICATE, 0, 0 ); len = MIN(left, 100); for (; left > 0;) { /* Increments for readability in the end of the function */ apdu.resp = out_ptr; apdu.le = len; apdu.resplen = left; r = sc_transmit_apdu(card, &apdu); if (r < 0) { break; } if (apdu.resplen == 0) { r = SC_ERROR_INTERNAL; break; } /* in the old CAC-1, 0x63 means 'more data' in addition to 'pin failed' */ if (apdu.sw1 != 0x63 || apdu.sw2 < 1) { /* we've either finished reading, or hit an error, break */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); left -= len; break; } /* Adjust the lengths */ left -= len; out_ptr += len; len = MIN(left, apdu.sw2); } if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } r = size - left; if (*out_buf == NULL) { *out_buf = malloc(r); if (*out_buf == NULL) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_OUT_OF_MEMORY); } memcpy(*out_buf, buf, r); } *out_len = r; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *val = NULL; u8 *cert_ptr; size_t val_len = 0; size_t len, cert_len; u8 cert_type; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_log(card->ctx, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); LOG_FUNC_RETURN(card->ctx, len); } sc_log(card->ctx, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; r = cac_cac1_get_certificate(card, &val, &val_len); if (r < 0) goto done; if (val_len < 1) { r = SC_ERROR_INVALID_DATA; goto done; } cert_type = val[0]; cert_ptr = val + 1; cert_len = val_len - 1; /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); if (len && priv->cache_buf) memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (val) free(val); LOG_FUNC_RETURN(card->ctx, r); } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path=%s, path->value=%s path->type=%d (%x)", sc_print_path(in_path), sc_dump_hex(in_path->value, in_path->len), in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, iso7816_select_file expects paths to keys to have specific * formats. There is no override. We have to add some bytes to the * path to make it happy. * We only need to do this for private keys. */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { path += 2; pathlen -= 2; } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; apdu.p2 = 0x00; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { u8 data[2]; sc_apdu_t apdu; /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2, CAC_INS_GET_CERTIFICATE, 0x00, 0x00); apdu.le = 0x02; apdu.resplen = 2; apdu.resp = data; r = sc_transmit_apdu(card, &apdu); /* SW1 = 0x63 means more data in CAC1 */ if (r == SC_SUCCESS && apdu.sw1 != 0x63) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } static int cac_populate_cac1(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = get_cac_label(i); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s)", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = sizeof(buf); r = cac_cac1_get_certificate(card, &val, &val_len); if (r >= 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC-1"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac1(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_I; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac1_drv = { "Common Access Card (CAC 1)", "cac1", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { /* Inherit most of the things from the CAC driver */ struct sc_card_driver *cac_drv = sc_get_cac_driver(); cac_ops = *cac_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.read_binary = cac_read_binary; return &cac1_drv; } struct sc_card_driver * sc_get_cac1_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1299_0
crossvul-cpp_data_bad_1537_2
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2009 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ #include "k5-int.h" #include "gssapiP_krb5.h" /* * IAKERB implementation */ extern int gssint_get_der_length(unsigned char **, OM_uint32, unsigned int*); enum iakerb_state { IAKERB_AS_REQ, /* acquiring ticket with initial creds */ IAKERB_TGS_REQ, /* acquiring ticket with TGT */ IAKERB_AP_REQ /* hand-off to normal GSS AP-REQ exchange */ }; struct _iakerb_ctx_id_rec { krb5_magic magic; /* KG_IAKERB_CONTEXT */ krb5_context k5c; gss_cred_id_t defcred; /* Initiator only */ enum iakerb_state state; /* Initiator only */ krb5_init_creds_context icc; /* Initiator only */ krb5_tkt_creds_context tcc; /* Initiator only */ gss_ctx_id_t gssc; krb5_data conv; /* conversation for checksumming */ unsigned int count; /* number of round trips */ int initiate; int established; krb5_get_init_creds_opt *gic_opts; }; #define IAKERB_MAX_HOPS ( 16 /* MAX_IN_TKT_LOOPS */ + KRB5_REFERRAL_MAXHOPS ) typedef struct _iakerb_ctx_id_rec iakerb_ctx_id_rec; typedef iakerb_ctx_id_rec *iakerb_ctx_id_t; /* * Release an IAKERB context */ static void iakerb_release_context(iakerb_ctx_id_t ctx) { OM_uint32 tmp; if (ctx == NULL) return; krb5_gss_release_cred(&tmp, &ctx->defcred); krb5_init_creds_free(ctx->k5c, ctx->icc); krb5_tkt_creds_free(ctx->k5c, ctx->tcc); krb5_gss_delete_sec_context(&tmp, &ctx->gssc, NULL); krb5_free_data_contents(ctx->k5c, &ctx->conv); krb5_get_init_creds_opt_free(ctx->k5c, ctx->gic_opts); krb5_free_context(ctx->k5c); free(ctx); } /* * Create a IAKERB-FINISHED structure containing a checksum of * the entire IAKERB exchange. */ krb5_error_code iakerb_make_finished(krb5_context context, krb5_key key, const krb5_data *conv, krb5_data **finished) { krb5_error_code code; krb5_iakerb_finished iaf; *finished = NULL; memset(&iaf, 0, sizeof(iaf)); if (key == NULL) return KRB5KDC_ERR_NULL_KEY; code = krb5_k_make_checksum(context, 0, key, KRB5_KEYUSAGE_IAKERB_FINISHED, conv, &iaf.checksum); if (code != 0) return code; code = encode_krb5_iakerb_finished(&iaf, finished); krb5_free_checksum_contents(context, &iaf.checksum); return code; } /* * Verify a IAKERB-FINISHED structure submitted by the initiator */ krb5_error_code iakerb_verify_finished(krb5_context context, krb5_key key, const krb5_data *conv, const krb5_data *finished) { krb5_error_code code; krb5_iakerb_finished *iaf; krb5_boolean valid = FALSE; if (key == NULL) return KRB5KDC_ERR_NULL_KEY; code = decode_krb5_iakerb_finished(finished, &iaf); if (code != 0) return code; code = krb5_k_verify_checksum(context, key, KRB5_KEYUSAGE_IAKERB_FINISHED, conv, &iaf->checksum, &valid); if (code == 0 && valid == FALSE) code = KRB5KRB_AP_ERR_BAD_INTEGRITY; krb5_free_iakerb_finished(context, iaf); return code; } /* * Save a token for future checksumming. */ static krb5_error_code iakerb_save_token(iakerb_ctx_id_t ctx, const gss_buffer_t token) { char *p; p = realloc(ctx->conv.data, ctx->conv.length + token->length); if (p == NULL) return ENOMEM; memcpy(p + ctx->conv.length, token->value, token->length); ctx->conv.data = p; ctx->conv.length += token->length; return 0; } /* * Parse a token into IAKERB-HEADER and KRB-KDC-REQ/REP */ static krb5_error_code iakerb_parse_token(iakerb_ctx_id_t ctx, int initialContextToken, const gss_buffer_t token, krb5_data *realm, krb5_data **cookie, krb5_data *request) { krb5_error_code code; krb5_iakerb_header *iah = NULL; unsigned int bodysize, lenlen; int length; unsigned char *ptr; int flags = 0; krb5_data data; if (token == GSS_C_NO_BUFFER || token->length == 0) { code = KRB5_BAD_MSIZE; goto cleanup; } if (initialContextToken) flags |= G_VFY_TOKEN_HDR_WRAPPER_REQUIRED; ptr = token->value; code = g_verify_token_header(gss_mech_iakerb, &bodysize, &ptr, IAKERB_TOK_PROXY, token->length, flags); if (code != 0) goto cleanup; data.data = (char *)ptr; if (bodysize-- == 0 || *ptr++ != 0x30 /* SEQUENCE */) { code = ASN1_BAD_ID; goto cleanup; } length = gssint_get_der_length(&ptr, bodysize, &lenlen); if (length < 0 || bodysize - lenlen < (unsigned int)length) { code = KRB5_BAD_MSIZE; goto cleanup; } data.length = 1 /* SEQUENCE */ + lenlen + length; ptr += length; bodysize -= (lenlen + length); code = decode_krb5_iakerb_header(&data, &iah); if (code != 0) goto cleanup; if (realm != NULL) { *realm = iah->target_realm; iah->target_realm.data = NULL; } if (cookie != NULL) { *cookie = iah->cookie; iah->cookie = NULL; } request->data = (char *)ptr; request->length = bodysize; assert(request->data + request->length == (char *)token->value + token->length); cleanup: krb5_free_iakerb_header(ctx->k5c, iah); return code; } /* * Create a token from IAKERB-HEADER and KRB-KDC-REQ/REP */ static krb5_error_code iakerb_make_token(iakerb_ctx_id_t ctx, krb5_data *realm, krb5_data *cookie, krb5_data *request, int initialContextToken, gss_buffer_t token) { krb5_error_code code; krb5_iakerb_header iah; krb5_data *data = NULL; char *p; unsigned int tokenSize; unsigned char *q; token->value = NULL; token->length = 0; /* * Assemble the IAKERB-HEADER from the realm and cookie */ memset(&iah, 0, sizeof(iah)); iah.target_realm = *realm; iah.cookie = cookie; code = encode_krb5_iakerb_header(&iah, &data); if (code != 0) goto cleanup; /* * Concatenate Kerberos request. */ p = realloc(data->data, data->length + request->length); if (p == NULL) { code = ENOMEM; goto cleanup; } data->data = p; if (request->length > 0) memcpy(data->data + data->length, request->data, request->length); data->length += request->length; if (initialContextToken) tokenSize = g_token_size(gss_mech_iakerb, data->length); else tokenSize = 2 + data->length; token->value = q = gssalloc_malloc(tokenSize); if (q == NULL) { code = ENOMEM; goto cleanup; } token->length = tokenSize; if (initialContextToken) { g_make_token_header(gss_mech_iakerb, data->length, &q, IAKERB_TOK_PROXY); } else { store_16_be(IAKERB_TOK_PROXY, q); q += 2; } memcpy(q, data->data, data->length); q += data->length; assert(q == (unsigned char *)token->value + token->length); cleanup: krb5_free_data(ctx->k5c, data); return code; } /* * Parse the IAKERB token in input_token and send the contained KDC * request to the KDC for the realm. * * Wrap the KDC reply in output_token. */ static krb5_error_code iakerb_acceptor_step(iakerb_ctx_id_t ctx, int initialContextToken, const gss_buffer_t input_token, gss_buffer_t output_token) { krb5_error_code code; krb5_data request = empty_data(), reply = empty_data(); krb5_data realm = empty_data(); OM_uint32 tmp; int tcp_only, use_master; krb5_ui_4 kdc_code; output_token->length = 0; output_token->value = NULL; if (ctx->count >= IAKERB_MAX_HOPS) { code = KRB5_KDC_UNREACH; goto cleanup; } code = iakerb_parse_token(ctx, initialContextToken, input_token, &realm, NULL, &request); if (code != 0) goto cleanup; if (realm.length == 0 || request.length == 0) { code = KRB5_BAD_MSIZE; goto cleanup; } code = iakerb_save_token(ctx, input_token); if (code != 0) goto cleanup; for (tcp_only = 0; tcp_only <= 1; tcp_only++) { use_master = 0; code = krb5_sendto_kdc(ctx->k5c, &request, &realm, &reply, &use_master, tcp_only); if (code == 0 && krb5_is_krb_error(&reply)) { krb5_error *error; code = decode_krb5_error(&reply, &error); if (code != 0) goto cleanup; kdc_code = error->error; krb5_free_error(ctx->k5c, error); if (kdc_code == KRB_ERR_RESPONSE_TOO_BIG) { krb5_free_data_contents(ctx->k5c, &reply); reply = empty_data(); continue; } } break; } if (code == KRB5_KDC_UNREACH || code == KRB5_REALM_UNKNOWN) { krb5_error error; memset(&error, 0, sizeof(error)); if (code == KRB5_KDC_UNREACH) error.error = KRB_AP_ERR_IAKERB_KDC_NO_RESPONSE; else if (code == KRB5_REALM_UNKNOWN) error.error = KRB_AP_ERR_IAKERB_KDC_NOT_FOUND; code = krb5_mk_error(ctx->k5c, &error, &reply); if (code != 0) goto cleanup; } else if (code != 0) goto cleanup; code = iakerb_make_token(ctx, &realm, NULL, &reply, 0, output_token); if (code != 0) goto cleanup; code = iakerb_save_token(ctx, output_token); if (code != 0) goto cleanup; ctx->count++; cleanup: if (code != 0) gss_release_buffer(&tmp, output_token); /* request is a pointer into input_token, no need to free */ krb5_free_data_contents(ctx->k5c, &realm); krb5_free_data_contents(ctx->k5c, &reply); return code; } /* * Initialise the krb5_init_creds context for the IAKERB context */ static krb5_error_code iakerb_init_creds_ctx(iakerb_ctx_id_t ctx, krb5_gss_cred_id_t cred, OM_uint32 time_req) { krb5_error_code code; if (cred->iakerb_mech == 0) { code = EINVAL; goto cleanup; } assert(cred->name != NULL); assert(cred->name->princ != NULL); code = krb5_get_init_creds_opt_alloc(ctx->k5c, &ctx->gic_opts); if (code != 0) goto cleanup; if (time_req != 0 && time_req != GSS_C_INDEFINITE) krb5_get_init_creds_opt_set_tkt_life(ctx->gic_opts, time_req); code = krb5_get_init_creds_opt_set_out_ccache(ctx->k5c, ctx->gic_opts, cred->ccache); if (code != 0) goto cleanup; code = krb5_init_creds_init(ctx->k5c, cred->name->princ, NULL, /* prompter */ NULL, /* data */ 0, /* start_time */ ctx->gic_opts, &ctx->icc); if (code != 0) goto cleanup; if (cred->password != NULL) { code = krb5_init_creds_set_password(ctx->k5c, ctx->icc, cred->password); } else { code = krb5_init_creds_set_keytab(ctx->k5c, ctx->icc, cred->client_keytab); } if (code != 0) goto cleanup; cleanup: return code; } /* * Initialise the krb5_tkt_creds context for the IAKERB context */ static krb5_error_code iakerb_tkt_creds_ctx(iakerb_ctx_id_t ctx, krb5_gss_cred_id_t cred, krb5_gss_name_t name, OM_uint32 time_req) { krb5_error_code code; krb5_creds creds; krb5_timestamp now; assert(cred->name != NULL); assert(cred->name->princ != NULL); memset(&creds, 0, sizeof(creds)); creds.client = cred->name->princ; creds.server = name->princ; if (time_req != 0 && time_req != GSS_C_INDEFINITE) { code = krb5_timeofday(ctx->k5c, &now); if (code != 0) goto cleanup; creds.times.endtime = now + time_req; } if (cred->name->ad_context != NULL) { code = krb5_authdata_export_authdata(ctx->k5c, cred->name->ad_context, AD_USAGE_TGS_REQ, &creds.authdata); if (code != 0) goto cleanup; } code = krb5_tkt_creds_init(ctx->k5c, cred->ccache, &creds, 0, &ctx->tcc); if (code != 0) goto cleanup; cleanup: krb5_free_authdata(ctx->k5c, creds.authdata); return code; } /* * Parse the IAKERB token in input_token and process the KDC * response. * * Emit the next KDC request, if any, in output_token. */ static krb5_error_code iakerb_initiator_step(iakerb_ctx_id_t ctx, krb5_gss_cred_id_t cred, krb5_gss_name_t name, OM_uint32 time_req, const gss_buffer_t input_token, gss_buffer_t output_token) { krb5_error_code code = 0; krb5_data in = empty_data(), out = empty_data(), realm = empty_data(); krb5_data *cookie = NULL; OM_uint32 tmp; unsigned int flags = 0; krb5_ticket_times times; output_token->length = 0; output_token->value = NULL; if (input_token != GSS_C_NO_BUFFER) { code = iakerb_parse_token(ctx, 0, input_token, NULL, &cookie, &in); if (code != 0) goto cleanup; code = iakerb_save_token(ctx, input_token); if (code != 0) goto cleanup; } switch (ctx->state) { case IAKERB_AS_REQ: if (ctx->icc == NULL) { code = iakerb_init_creds_ctx(ctx, cred, time_req); if (code != 0) goto cleanup; } code = krb5_init_creds_step(ctx->k5c, ctx->icc, &in, &out, &realm, &flags); if (code != 0) { if (cred->have_tgt) { /* We were trying to refresh; keep going with current creds. */ ctx->state = IAKERB_TGS_REQ; krb5_clear_error_message(ctx->k5c); } else { goto cleanup; } } else if (!(flags & KRB5_INIT_CREDS_STEP_FLAG_CONTINUE)) { krb5_init_creds_get_times(ctx->k5c, ctx->icc, &times); kg_cred_set_initial_refresh(ctx->k5c, cred, &times); cred->expire = times.endtime; krb5_init_creds_free(ctx->k5c, ctx->icc); ctx->icc = NULL; ctx->state = IAKERB_TGS_REQ; } else break; in = empty_data(); /* Done with AS request; fall through to TGS request. */ case IAKERB_TGS_REQ: if (ctx->tcc == NULL) { code = iakerb_tkt_creds_ctx(ctx, cred, name, time_req); if (code != 0) goto cleanup; } code = krb5_tkt_creds_step(ctx->k5c, ctx->tcc, &in, &out, &realm, &flags); if (code != 0) goto cleanup; if (!(flags & KRB5_TKT_CREDS_STEP_FLAG_CONTINUE)) { krb5_tkt_creds_get_times(ctx->k5c, ctx->tcc, &times); cred->expire = times.endtime; krb5_tkt_creds_free(ctx->k5c, ctx->tcc); ctx->tcc = NULL; ctx->state = IAKERB_AP_REQ; } else break; /* Done with TGS request; fall through to AP request. */ case IAKERB_AP_REQ: break; } if (out.length != 0) { assert(ctx->state != IAKERB_AP_REQ); code = iakerb_make_token(ctx, &realm, cookie, &out, (input_token == GSS_C_NO_BUFFER), output_token); if (code != 0) goto cleanup; /* Save the token for generating a future checksum */ code = iakerb_save_token(ctx, output_token); if (code != 0) goto cleanup; ctx->count++; } cleanup: if (code != 0) gss_release_buffer(&tmp, output_token); krb5_free_data(ctx->k5c, cookie); krb5_free_data_contents(ctx->k5c, &out); krb5_free_data_contents(ctx->k5c, &realm); return code; } /* * Determine the starting IAKERB state for a context. If we already * have a ticket, we may not need to do IAKERB at all. */ static krb5_error_code iakerb_get_initial_state(iakerb_ctx_id_t ctx, krb5_gss_cred_id_t cred, krb5_gss_name_t target, OM_uint32 time_req, enum iakerb_state *state) { krb5_creds in_creds, *out_creds = NULL; krb5_error_code code; memset(&in_creds, 0, sizeof(in_creds)); in_creds.client = cred->name->princ; in_creds.server = target->princ; if (cred->name->ad_context != NULL) { code = krb5_authdata_export_authdata(ctx->k5c, cred->name->ad_context, AD_USAGE_TGS_REQ, &in_creds.authdata); if (code != 0) goto cleanup; } if (time_req != 0 && time_req != GSS_C_INDEFINITE) { krb5_timestamp now; code = krb5_timeofday(ctx->k5c, &now); if (code != 0) goto cleanup; in_creds.times.endtime = now + time_req; } /* Make an AS request if we have no creds or it's time to refresh them. */ if (cred->expire == 0 || kg_cred_time_to_refresh(ctx->k5c, cred)) { *state = IAKERB_AS_REQ; code = 0; goto cleanup; } code = krb5_get_credentials(ctx->k5c, KRB5_GC_CACHED, cred->ccache, &in_creds, &out_creds); if (code == KRB5_CC_NOTFOUND || code == KRB5_CC_NOT_KTYPE) { *state = cred->have_tgt ? IAKERB_TGS_REQ : IAKERB_AS_REQ; code = 0; } else if (code == 0) { *state = IAKERB_AP_REQ; krb5_free_creds(ctx->k5c, out_creds); } cleanup: krb5_free_authdata(ctx->k5c, in_creds.authdata); return code; } /* * Allocate and initialise an IAKERB context */ static krb5_error_code iakerb_alloc_context(iakerb_ctx_id_t *pctx, int initiate) { iakerb_ctx_id_t ctx; krb5_error_code code; *pctx = NULL; ctx = k5alloc(sizeof(*ctx), &code); if (ctx == NULL) goto cleanup; ctx->defcred = GSS_C_NO_CREDENTIAL; ctx->magic = KG_IAKERB_CONTEXT; ctx->state = IAKERB_AS_REQ; ctx->count = 0; ctx->initiate = initiate; ctx->established = 0; code = krb5_gss_init_context(&ctx->k5c); if (code != 0) goto cleanup; *pctx = ctx; cleanup: if (code != 0) iakerb_release_context(ctx); return code; } OM_uint32 KRB5_CALLCONV iakerb_gss_delete_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t output_token) { iakerb_ctx_id_t iakerb_ctx = (iakerb_ctx_id_t)*context_handle; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } *minor_status = 0; *context_handle = GSS_C_NO_CONTEXT; iakerb_release_context(iakerb_ctx); return GSS_S_COMPLETE; } static krb5_boolean iakerb_is_iakerb_token(const gss_buffer_t token) { krb5_error_code code; unsigned int bodysize = token->length; unsigned char *ptr = token->value; code = g_verify_token_header(gss_mech_iakerb, &bodysize, &ptr, IAKERB_TOK_PROXY, token->length, 0); return (code == 0); } static void iakerb_make_exts(iakerb_ctx_id_t ctx, krb5_gss_ctx_ext_rec *exts) { memset(exts, 0, sizeof(*exts)); if (ctx->conv.length != 0) exts->iakerb.conv = &ctx->conv; } OM_uint32 KRB5_CALLCONV iakerb_gss_accept_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_cred_id_t verifier_cred_handle, gss_buffer_t input_token, gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *delegated_cred_handle) { OM_uint32 major_status = GSS_S_FAILURE; OM_uint32 code; iakerb_ctx_id_t ctx; int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT); if (initialContextToken) { code = iakerb_alloc_context(&ctx, 0); if (code != 0) goto cleanup; } else ctx = (iakerb_ctx_id_t)*context_handle; if (iakerb_is_iakerb_token(input_token)) { if (ctx->gssc != GSS_C_NO_CONTEXT) { /* We shouldn't get an IAKERB token now. */ code = G_WRONG_TOKID; major_status = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } code = iakerb_acceptor_step(ctx, initialContextToken, input_token, output_token); if (code == (OM_uint32)KRB5_BAD_MSIZE) major_status = GSS_S_DEFECTIVE_TOKEN; if (code != 0) goto cleanup; if (initialContextToken) { *context_handle = (gss_ctx_id_t)ctx; ctx = NULL; } if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = (gss_OID)gss_mech_iakerb; if (ret_flags != NULL) *ret_flags = 0; if (time_rec != NULL) *time_rec = 0; if (delegated_cred_handle != NULL) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; major_status = GSS_S_CONTINUE_NEEDED; } else { krb5_gss_ctx_ext_rec exts; iakerb_make_exts(ctx, &exts); major_status = krb5_gss_accept_sec_context_ext(&code, &ctx->gssc, verifier_cred_handle, input_token, input_chan_bindings, src_name, NULL, output_token, ret_flags, time_rec, delegated_cred_handle, &exts); if (major_status == GSS_S_COMPLETE) ctx->established = 1; if (mech_type != NULL) *mech_type = (gss_OID)gss_mech_krb5; } cleanup: if (initialContextToken && GSS_ERROR(major_status)) { iakerb_release_context(ctx); *context_handle = GSS_C_NO_CONTEXT; } *minor_status = code; return major_status; } OM_uint32 KRB5_CALLCONV iakerb_gss_init_sec_context(OM_uint32 *minor_status, gss_cred_id_t claimant_cred_handle, gss_ctx_id_t *context_handle, gss_name_t target_name, gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_OID *actual_mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec) { OM_uint32 major_status = GSS_S_FAILURE; krb5_error_code code; iakerb_ctx_id_t ctx; krb5_gss_cred_id_t kcred; krb5_gss_name_t kname; krb5_boolean cred_locked = FALSE; int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT); if (initialContextToken) { code = iakerb_alloc_context(&ctx, 1); if (code != 0) { *minor_status = code; goto cleanup; } if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) { major_status = iakerb_gss_acquire_cred(minor_status, NULL, GSS_C_INDEFINITE, GSS_C_NULL_OID_SET, GSS_C_INITIATE, &ctx->defcred, NULL, NULL); if (GSS_ERROR(major_status)) goto cleanup; claimant_cred_handle = ctx->defcred; } } else { ctx = (iakerb_ctx_id_t)*context_handle; if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) claimant_cred_handle = ctx->defcred; } kname = (krb5_gss_name_t)target_name; major_status = kg_cred_resolve(minor_status, ctx->k5c, claimant_cred_handle, target_name); if (GSS_ERROR(major_status)) goto cleanup; cred_locked = TRUE; kcred = (krb5_gss_cred_id_t)claimant_cred_handle; major_status = GSS_S_FAILURE; if (initialContextToken) { code = iakerb_get_initial_state(ctx, kcred, kname, time_req, &ctx->state); if (code != 0) { *minor_status = code; goto cleanup; } *context_handle = (gss_ctx_id_t)ctx; } if (ctx->state != IAKERB_AP_REQ) { /* We need to do IAKERB. */ code = iakerb_initiator_step(ctx, kcred, kname, time_req, input_token, output_token); if (code == KRB5_BAD_MSIZE) major_status = GSS_S_DEFECTIVE_TOKEN; if (code != 0) { *minor_status = code; goto cleanup; } } if (ctx->state == IAKERB_AP_REQ) { krb5_gss_ctx_ext_rec exts; if (cred_locked) { k5_mutex_unlock(&kcred->lock); cred_locked = FALSE; } iakerb_make_exts(ctx, &exts); if (ctx->gssc == GSS_C_NO_CONTEXT) input_token = GSS_C_NO_BUFFER; /* IAKERB is finished, or we skipped to Kerberos directly. */ major_status = krb5_gss_init_sec_context_ext(minor_status, (gss_cred_id_t) kcred, &ctx->gssc, target_name, (gss_OID)gss_mech_iakerb, req_flags, time_req, input_chan_bindings, input_token, NULL, output_token, ret_flags, time_rec, &exts); if (major_status == GSS_S_COMPLETE) ctx->established = 1; if (actual_mech_type != NULL) *actual_mech_type = (gss_OID)gss_mech_krb5; } else { if (actual_mech_type != NULL) *actual_mech_type = (gss_OID)gss_mech_iakerb; if (ret_flags != NULL) *ret_flags = 0; if (time_rec != NULL) *time_rec = 0; major_status = GSS_S_CONTINUE_NEEDED; } cleanup: if (cred_locked) k5_mutex_unlock(&kcred->lock); if (initialContextToken && GSS_ERROR(major_status)) { iakerb_release_context(ctx); *context_handle = GSS_C_NO_CONTEXT; } return major_status; } OM_uint32 KRB5_CALLCONV iakerb_gss_unwrap(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int *conf_state, gss_qop_t *qop_state) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_unwrap(minor_status, ctx->gssc, input_message_buffer, output_message_buffer, conf_state, qop_state); } OM_uint32 KRB5_CALLCONV iakerb_gss_wrap(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_message_buffer, int *conf_state, gss_buffer_t output_message_buffer) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_wrap(minor_status, ctx->gssc, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer); } OM_uint32 KRB5_CALLCONV iakerb_gss_process_context_token(OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_buffer_t token_buffer) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_DEFECTIVE_TOKEN; return krb5_gss_process_context_token(minor_status, ctx->gssc, token_buffer); } OM_uint32 KRB5_CALLCONV iakerb_gss_context_time(OM_uint32 *minor_status, gss_ctx_id_t context_handle, OM_uint32 *time_rec) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_context_time(minor_status, ctx->gssc, time_rec); } #ifndef LEAN_CLIENT OM_uint32 KRB5_CALLCONV iakerb_gss_export_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token) { OM_uint32 maj; iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; /* We don't currently support exporting partially established contexts. */ if (!ctx->established) return GSS_S_UNAVAILABLE; maj = krb5_gss_export_sec_context(minor_status, &ctx->gssc, interprocess_token); if (ctx->gssc == GSS_C_NO_CONTEXT) { iakerb_release_context(ctx); *context_handle = GSS_C_NO_CONTEXT; } return maj; } /* * Until we implement partial context exports, there are no IAKERB exported * context tokens, only tokens for the underlying krb5 context. So we do not * need to implement an iakerb_gss_import_sec_context() yet; it would be * unreachable except via a manually constructed token. */ #endif /* LEAN_CLIENT */ OM_uint32 KRB5_CALLCONV iakerb_gss_inquire_context(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_name_t *src_name, gss_name_t *targ_name, OM_uint32 *lifetime_rec, gss_OID *mech_type, OM_uint32 *ctx_flags, int *initiate, int *opened) { OM_uint32 ret; iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (targ_name != NULL) *targ_name = GSS_C_NO_NAME; if (lifetime_rec != NULL) *lifetime_rec = 0; if (mech_type != NULL) *mech_type = (gss_OID)gss_mech_iakerb; if (ctx_flags != NULL) *ctx_flags = 0; if (initiate != NULL) *initiate = ctx->initiate; if (opened != NULL) *opened = ctx->established; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_COMPLETE; ret = krb5_gss_inquire_context(minor_status, ctx->gssc, src_name, targ_name, lifetime_rec, mech_type, ctx_flags, initiate, opened); if (!ctx->established) { /* Report IAKERB as the mech OID until the context is established. */ if (mech_type != NULL) *mech_type = (gss_OID)gss_mech_iakerb; /* We don't support exporting partially-established contexts. */ if (ctx_flags != NULL) *ctx_flags &= ~GSS_C_TRANS_FLAG; } return ret; } OM_uint32 KRB5_CALLCONV iakerb_gss_wrap_size_limit(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_wrap_size_limit(minor_status, ctx->gssc, conf_req_flag, qop_req, req_output_size, max_input_size); } OM_uint32 KRB5_CALLCONV iakerb_gss_get_mic(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t qop_req, gss_buffer_t message_buffer, gss_buffer_t message_token) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_get_mic(minor_status, ctx->gssc, qop_req, message_buffer, message_token); } OM_uint32 KRB5_CALLCONV iakerb_gss_verify_mic(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t msg_buffer, gss_buffer_t token_buffer, gss_qop_t *qop_state) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_verify_mic(minor_status, ctx->gssc, msg_buffer, token_buffer, qop_state); } OM_uint32 KRB5_CALLCONV iakerb_gss_inquire_sec_context_by_oid(OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_UNAVAILABLE; return krb5_gss_inquire_sec_context_by_oid(minor_status, ctx->gssc, desired_object, data_set); } OM_uint32 KRB5_CALLCONV iakerb_gss_set_sec_context_option(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, const gss_OID desired_object, const gss_buffer_t value) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)*context_handle; if (ctx == NULL || ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_UNAVAILABLE; return krb5_gss_set_sec_context_option(minor_status, &ctx->gssc, desired_object, value); } OM_uint32 KRB5_CALLCONV iakerb_gss_wrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_wrap_iov(minor_status, ctx->gssc, conf_req_flag, qop_req, conf_state, iov, iov_count); } OM_uint32 KRB5_CALLCONV iakerb_gss_unwrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_unwrap_iov(minor_status, ctx->gssc, conf_state, qop_state, iov, iov_count); } OM_uint32 KRB5_CALLCONV iakerb_gss_wrap_iov_length(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_wrap_iov_length(minor_status, ctx->gssc, conf_req_flag, qop_req, conf_state, iov, iov_count); } OM_uint32 KRB5_CALLCONV iakerb_gss_pseudo_random(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_pseudo_random(minor_status, ctx->gssc, prf_key, prf_in, desired_output_len, prf_out); } OM_uint32 KRB5_CALLCONV iakerb_gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t qop_req, gss_iov_buffer_desc *iov, int iov_count) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_get_mic_iov(minor_status, ctx->gssc, qop_req, iov, iov_count); } OM_uint32 KRB5_CALLCONV iakerb_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_verify_mic_iov(minor_status, ctx->gssc, qop_state, iov, iov_count); } OM_uint32 KRB5_CALLCONV iakerb_gss_get_mic_iov_length(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t qop_req, gss_iov_buffer_desc *iov, int iov_count) { iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; if (ctx->gssc == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; return krb5_gss_get_mic_iov_length(minor_status, ctx->gssc, qop_req, iov, iov_count); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_1537_2
crossvul-cpp_data_bad_622_1
/*====================================================================* - Copyright (C) 2001 Leptonica. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *====================================================================*/ /* * xtractprotos.c * * This program accepts a list of C files on the command line * and outputs the C prototypes to stdout. It uses cpp to * handle the preprocessor macros, and then parses the cpp output. * In leptonica, it is used to make allheaders.h (and optionally * leptprotos.h, which contains just the function prototypes.) * In leptonica, only the file allheaders.h is included with * source files. * * An optional 'prestring' can be prepended to each declaration. * And the function prototypes can either be sent to stdout, written * to a named file, or placed in-line within allheaders.h. * * The signature is: * * xtractprotos [-prestring=<string>] [-protos=<where>] [list of C files] * * Without -protos, the prototypes are written to stdout. * With -protos, allheaders.h is rewritten: * * if you use -protos=inline, the prototypes are placed within * allheaders.h. * * if you use -protos=leptprotos.h, the prototypes written to * the file leptprotos.h, and alltypes.h has * #include "leptprotos.h" * * For constructing allheaders.h, two text files are provided: * allheaders_top.txt * allheaders_bot.txt * The former contains the leptonica version number, so it must * be updated when a new version is made. * * For simple C prototype extraction, xtractprotos has essentially * the same functionality as Adam Bryant's cextract, but the latter * has not been officially supported for over 15 years, has been * patched numerous times, and doesn't work with sys/sysmacros.h * for 64 bit architecture. * * This is used to extract all prototypes in liblept. * The function that does all the work is parseForProtos(), * which takes as input the output from cpp. * * xtractprotos can run in leptonica to do an 'ab initio' generation * of allheaders.h; that is, it can make allheaders.h without * leptprotos.h and with an allheaders.h file of 0 length. * Of course, the usual situation is to run it with a valid allheaders.h, * which includes all the function prototypes. To avoid including * all the prototypes in the input for each file, cpp runs here * with -DNO_PROTOS, so the prototypes are not included -- this is * much faster. * * The xtractprotos version number, defined below, is incremented * whenever a new version is made. * * Note: this uses cpp to preprocess the input. (The name of the cpp * tempfile is constructed below. It has a "." in the tail, which * Cygwin needs to prevent it from appending ".exe" to the filename.) */ #include <string.h> #include "allheaders.h" static const l_int32 L_BUF_SIZE = 512; static const char *version = "1.5"; int main(int argc, char **argv) { char *filein, *str, *tempfile, *prestring, *outprotos, *protostr; const char *spacestr = " "; char buf[L_BUF_SIZE]; l_uint8 *allheaders; l_int32 i, maxindex, in_line, nflags, protos_added, firstfile, len, ret; size_t nbytes; L_BYTEA *ba, *ba2; SARRAY *sa, *safirst; static char mainName[] = "xtractprotos"; if (argc == 1) { fprintf(stderr, "xtractprotos [-prestring=<string>] [-protos=<where>] " "[list of C files]\n" "where the prestring is prepended to each prototype, and \n" "protos can be either 'inline' or the name of an output " "prototype file\n"); return 1; } /* ---------------------------------------------------------------- */ /* Parse input flags and find prestring and outprotos, if requested */ /* ---------------------------------------------------------------- */ prestring = outprotos = NULL; in_line = FALSE; nflags = 0; maxindex = L_MIN(3, argc); for (i = 1; i < maxindex; i++) { if (argv[i][0] == '-') { if (!strncmp(argv[i], "-prestring", 10)) { nflags++; ret = sscanf(argv[i] + 1, "prestring=%s", buf); if (ret != 1) { fprintf(stderr, "parse failure for prestring\n"); return 1; } if ((len = strlen(buf)) > L_BUF_SIZE - 3) { L_WARNING("prestring too large; omitting!\n", mainName); } else { buf[len] = ' '; buf[len + 1] = '\0'; prestring = stringNew(buf); } } else if (!strncmp(argv[i], "-protos", 7)) { nflags++; ret = sscanf(argv[i] + 1, "protos=%s", buf); if (ret != 1) { fprintf(stderr, "parse failure for protos\n"); return 1; } outprotos = stringNew(buf); if (!strncmp(outprotos, "inline", 7)) in_line = TRUE; } } } if (argc - nflags < 2) { fprintf(stderr, "no files specified!\n"); return 1; } /* ---------------------------------------------------------------- */ /* Generate the prototype string */ /* ---------------------------------------------------------------- */ ba = l_byteaCreate(500); /* First the extern C head */ sa = sarrayCreate(0); sarrayAddString(sa, (char *)"/*", L_COPY); snprintf(buf, L_BUF_SIZE, " * These prototypes were autogen'd by xtractprotos, v. %s", version); sarrayAddString(sa, buf, L_COPY); sarrayAddString(sa, (char *)" */", L_COPY); sarrayAddString(sa, (char *)"#ifdef __cplusplus", L_COPY); sarrayAddString(sa, (char *)"extern \"C\" {", L_COPY); sarrayAddString(sa, (char *)"#endif /* __cplusplus */\n", L_COPY); str = sarrayToString(sa, 1); l_byteaAppendString(ba, str); lept_free(str); sarrayDestroy(&sa); /* Then the prototypes */ firstfile = 1 + nflags; protos_added = FALSE; if ((tempfile = l_makeTempFilename()) == NULL) { fprintf(stderr, "failure to make a writeable temp file\n"); return 1; } for (i = firstfile; i < argc; i++) { filein = argv[i]; len = strlen(filein); if (filein[len - 1] == 'h') /* skip .h files */ continue; snprintf(buf, L_BUF_SIZE, "cpp -ansi -DNO_PROTOS %s %s", filein, tempfile); ret = system(buf); /* cpp */ if (ret) { fprintf(stderr, "cpp failure for %s; continuing\n", filein); continue; } if ((str = parseForProtos(tempfile, prestring)) == NULL) { fprintf(stderr, "parse failure for %s; continuing\n", filein); continue; } if (strlen(str) > 1) { /* strlen(str) == 1 is a file without protos */ l_byteaAppendString(ba, str); protos_added = TRUE; } lept_free(str); } lept_rmfile(tempfile); lept_free(tempfile); /* Lastly the extern C tail */ sa = sarrayCreate(0); sarrayAddString(sa, (char *)"\n#ifdef __cplusplus", L_COPY); sarrayAddString(sa, (char *)"}", L_COPY); sarrayAddString(sa, (char *)"#endif /* __cplusplus */", L_COPY); str = sarrayToString(sa, 1); l_byteaAppendString(ba, str); lept_free(str); sarrayDestroy(&sa); protostr = (char *)l_byteaCopyData(ba, &nbytes); l_byteaDestroy(&ba); /* ---------------------------------------------------------------- */ /* Generate the output */ /* ---------------------------------------------------------------- */ if (!outprotos) { /* just write to stdout */ fprintf(stderr, "%s\n", protostr); lept_free(protostr); return 0; } /* If no protos were found, do nothing further */ if (!protos_added) { fprintf(stderr, "No protos found\n"); lept_free(protostr); return 1; } /* Make the output files */ ba = l_byteaInitFromFile("allheaders_top.txt"); if (!in_line) { snprintf(buf, sizeof(buf), "#include \"%s\"\n", outprotos); l_byteaAppendString(ba, buf); l_binaryWrite(outprotos, "w", protostr, nbytes); } else { l_byteaAppendString(ba, protostr); } ba2 = l_byteaInitFromFile("allheaders_bot.txt"); l_byteaJoin(ba, &ba2); l_byteaWrite("allheaders.h", ba, 0, 0); l_byteaDestroy(&ba); lept_free(protostr); return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_622_1
crossvul-cpp_data_good_2568_1
/* Copyright (c) 2014. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #if _WIN32 || __CYGWIN__ #define PRIu64 "I64d" #else #include <inttypes.h> #endif #include <yara/mem.h> #include <yara/error.h> #include <yara/object.h> #include <yara/exec.h> #include <yara/utils.h> int yr_object_create( int8_t type, const char* identifier, YR_OBJECT* parent, YR_OBJECT** object) { YR_OBJECT* obj; int i; size_t object_size = 0; assert(parent != NULL || object != NULL); switch (type) { case OBJECT_TYPE_STRUCTURE: object_size = sizeof(YR_OBJECT_STRUCTURE); break; case OBJECT_TYPE_ARRAY: object_size = sizeof(YR_OBJECT_ARRAY); break; case OBJECT_TYPE_DICTIONARY: object_size = sizeof(YR_OBJECT_DICTIONARY); break; case OBJECT_TYPE_INTEGER: object_size = sizeof(YR_OBJECT); break; case OBJECT_TYPE_FLOAT: object_size = sizeof(YR_OBJECT); break; case OBJECT_TYPE_STRING: object_size = sizeof(YR_OBJECT); break; case OBJECT_TYPE_FUNCTION: object_size = sizeof(YR_OBJECT_FUNCTION); break; default: assert(FALSE); } obj = (YR_OBJECT*) yr_malloc(object_size); if (obj == NULL) return ERROR_INSUFFICIENT_MEMORY; obj->type = type; obj->identifier = yr_strdup(identifier); obj->parent = parent; obj->data = NULL; switch(type) { case OBJECT_TYPE_INTEGER: obj->value.i = UNDEFINED; break; case OBJECT_TYPE_FLOAT: obj->value.d = NAN; break; case OBJECT_TYPE_STRING: obj->value.ss = NULL; break; case OBJECT_TYPE_STRUCTURE: object_as_structure(obj)->members = NULL; break; case OBJECT_TYPE_ARRAY: object_as_array(obj)->items = NULL; object_as_array(obj)->prototype_item = NULL; break; case OBJECT_TYPE_DICTIONARY: object_as_dictionary(obj)->items = NULL; object_as_dictionary(obj)->prototype_item = NULL; break; case OBJECT_TYPE_FUNCTION: object_as_function(obj)->return_obj = NULL; for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++) { object_as_function(obj)->prototypes[i].arguments_fmt = NULL; object_as_function(obj)->prototypes[i].code = NULL; } break; } if (obj->identifier == NULL) { yr_free(obj); return ERROR_INSUFFICIENT_MEMORY; } if (parent != NULL) { assert(parent->type == OBJECT_TYPE_STRUCTURE || parent->type == OBJECT_TYPE_ARRAY || parent->type == OBJECT_TYPE_DICTIONARY || parent->type == OBJECT_TYPE_FUNCTION); switch(parent->type) { case OBJECT_TYPE_STRUCTURE: FAIL_ON_ERROR_WITH_CLEANUP( yr_object_structure_set_member(parent, obj), { yr_free((void*) obj->identifier); yr_free(obj); }); break; case OBJECT_TYPE_ARRAY: object_as_array(parent)->prototype_item = obj; break; case OBJECT_TYPE_DICTIONARY: object_as_dictionary(parent)->prototype_item = obj; break; case OBJECT_TYPE_FUNCTION: object_as_function(parent)->return_obj = obj; break; } } if (object != NULL) *object = obj; return ERROR_SUCCESS; } int yr_object_function_create( const char* identifier, const char* arguments_fmt, const char* return_fmt, YR_MODULE_FUNC code, YR_OBJECT* parent, YR_OBJECT** function) { YR_OBJECT* return_obj; YR_OBJECT* o = NULL; YR_OBJECT_FUNCTION* f = NULL; int8_t return_type; int i; switch (*return_fmt) { case 'i': return_type = OBJECT_TYPE_INTEGER; break; case 's': return_type = OBJECT_TYPE_STRING; break; case 'f': return_type = OBJECT_TYPE_FLOAT; break; default: return ERROR_INVALID_FORMAT; } if (parent != NULL) { // The parent of a function must be a structure. assert(parent->type == OBJECT_TYPE_STRUCTURE); // Try to find if the structure already has a function // with that name. In that case this is a function overload. f = object_as_function(yr_object_lookup_field(parent, identifier)); // Overloaded functions must have the same return type. if (f != NULL && return_type != f->return_obj->type) return ERROR_WRONG_RETURN_TYPE; } if (f == NULL) // Function doesn't exist yet { FAIL_ON_ERROR( yr_object_create( OBJECT_TYPE_FUNCTION, identifier, parent, &o)); FAIL_ON_ERROR_WITH_CLEANUP( yr_object_create( return_type, "result", o, &return_obj), yr_object_destroy(o)); f = object_as_function(o); } for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++) { if (f->prototypes[i].arguments_fmt == NULL) { f->prototypes[i].arguments_fmt = arguments_fmt; f->prototypes[i].code = code; break; } } if (function != NULL) *function = (YR_OBJECT*) f; return ERROR_SUCCESS; } int yr_object_from_external_variable( YR_EXTERNAL_VARIABLE* external, YR_OBJECT** object) { YR_OBJECT* obj; int result; uint8_t obj_type = 0; switch(external->type) { case EXTERNAL_VARIABLE_TYPE_INTEGER: case EXTERNAL_VARIABLE_TYPE_BOOLEAN: obj_type = OBJECT_TYPE_INTEGER; break; case EXTERNAL_VARIABLE_TYPE_FLOAT: obj_type = OBJECT_TYPE_FLOAT; break; case EXTERNAL_VARIABLE_TYPE_STRING: case EXTERNAL_VARIABLE_TYPE_MALLOC_STRING: obj_type = OBJECT_TYPE_STRING; break; default: assert(FALSE); } result = yr_object_create( obj_type, external->identifier, NULL, &obj); if (result == ERROR_SUCCESS) { switch(external->type) { case EXTERNAL_VARIABLE_TYPE_INTEGER: case EXTERNAL_VARIABLE_TYPE_BOOLEAN: yr_object_set_integer(external->value.i, obj, NULL); break; case EXTERNAL_VARIABLE_TYPE_FLOAT: yr_object_set_float(external->value.f, obj, NULL); break; case EXTERNAL_VARIABLE_TYPE_STRING: case EXTERNAL_VARIABLE_TYPE_MALLOC_STRING: yr_object_set_string( external->value.s, strlen(external->value.s), obj, NULL); break; } *object = obj; } return result; } void yr_object_destroy( YR_OBJECT* object) { YR_STRUCTURE_MEMBER* member; YR_STRUCTURE_MEMBER* next_member; YR_ARRAY_ITEMS* array_items; YR_DICTIONARY_ITEMS* dict_items; int i; if (object == NULL) return; switch(object->type) { case OBJECT_TYPE_STRUCTURE: member = object_as_structure(object)->members; while (member != NULL) { next_member = member->next; yr_object_destroy(member->object); yr_free(member); member = next_member; } break; case OBJECT_TYPE_STRING: if (object->value.ss != NULL) yr_free(object->value.ss); break; case OBJECT_TYPE_ARRAY: if (object_as_array(object)->prototype_item != NULL) yr_object_destroy(object_as_array(object)->prototype_item); array_items = object_as_array(object)->items; if (array_items != NULL) { for (i = 0; i < array_items->count; i++) if (array_items->objects[i] != NULL) yr_object_destroy(array_items->objects[i]); } yr_free(array_items); break; case OBJECT_TYPE_DICTIONARY: if (object_as_dictionary(object)->prototype_item != NULL) yr_object_destroy(object_as_dictionary(object)->prototype_item); dict_items = object_as_dictionary(object)->items; if (dict_items != NULL) { for (i = 0; i < dict_items->used; i++) { if (dict_items->objects[i].key != NULL) yr_free(dict_items->objects[i].key); if (dict_items->objects[i].obj != NULL) yr_object_destroy(dict_items->objects[i].obj); } } yr_free(dict_items); break; case OBJECT_TYPE_FUNCTION: yr_object_destroy(object_as_function(object)->return_obj); break; } yr_free((void*) object->identifier); yr_free(object); } YR_OBJECT* yr_object_lookup_field( YR_OBJECT* object, const char* field_name) { YR_STRUCTURE_MEMBER* member; assert(object != NULL); assert(object->type == OBJECT_TYPE_STRUCTURE); member = object_as_structure(object)->members; while (member != NULL) { if (strcmp(member->object->identifier, field_name) == 0) return member->object; member = member->next; } return NULL; } YR_OBJECT* _yr_object_lookup( YR_OBJECT* object, int flags, const char* pattern, va_list args) { YR_OBJECT* obj = object; const char* p = pattern; const char* key = NULL; char str[256]; int i; int index = -1; while (obj != NULL) { i = 0; while(*p != '\0' && *p != '.' && *p != '[' && i < sizeof(str) - 1) { str[i++] = *p++; } str[i] = '\0'; if (obj->type != OBJECT_TYPE_STRUCTURE) return NULL; obj = yr_object_lookup_field(obj, str); if (obj == NULL) return NULL; if (*p == '[') { p++; if (*p == '%') { p++; switch(*p++) { case 'i': index = va_arg(args, int); break; case 's': key = va_arg(args, const char*); break; default: return NULL; } } else if (*p >= '0' && *p <= '9') { index = (int) strtol(p, (char**) &p, 10); } else if (*p == '"') { i = 0; p++; // skip the opening quotation mark while (*p != '"' && *p != '\0' && i < sizeof(str)) str[i++] = *p++; str[i] = '\0'; p++; // skip the closing quotation mark key = str; } else { return NULL; } assert(*p == ']'); p++; assert(*p == '.' || *p == '\0'); switch(obj->type) { case OBJECT_TYPE_ARRAY: assert(index != -1); obj = yr_object_array_get_item(obj, flags, index); break; case OBJECT_TYPE_DICTIONARY: assert(key != NULL); obj = yr_object_dict_get_item(obj, flags, key); break; } } if (*p == '\0') break; p++; } return obj; } YR_OBJECT* yr_object_lookup( YR_OBJECT* object, int flags, const char* pattern, ...) { YR_OBJECT* result; va_list args; va_start(args, pattern); result = _yr_object_lookup(object, flags, pattern, args); va_end(args); return result; } int yr_object_copy( YR_OBJECT* object, YR_OBJECT** object_copy) { YR_OBJECT* copy; YR_OBJECT* o; YR_STRUCTURE_MEMBER* structure_member; int i; *object_copy = NULL; FAIL_ON_ERROR(yr_object_create( object->type, object->identifier, NULL, &copy)); switch(object->type) { case OBJECT_TYPE_INTEGER: copy->value.i = object->value.i; break; case OBJECT_TYPE_FLOAT: copy->value.d = object->value.d; break; case OBJECT_TYPE_STRING: if (object->value.ss != NULL) copy->value.ss = sized_string_dup(object->value.ss); else copy->value.ss = NULL; break; case OBJECT_TYPE_FUNCTION: FAIL_ON_ERROR_WITH_CLEANUP( yr_object_copy( object_as_function(object)->return_obj, &object_as_function(copy)->return_obj), yr_object_destroy(copy)); for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++) object_as_function(copy)->prototypes[i] = \ object_as_function(object)->prototypes[i]; break; case OBJECT_TYPE_STRUCTURE: structure_member = object_as_structure(object)->members; while (structure_member != NULL) { FAIL_ON_ERROR_WITH_CLEANUP( yr_object_copy(structure_member->object, &o), yr_object_destroy(copy)); FAIL_ON_ERROR_WITH_CLEANUP( yr_object_structure_set_member(copy, o), yr_free(o); yr_object_destroy(copy)); structure_member = structure_member->next; } break; case OBJECT_TYPE_ARRAY: FAIL_ON_ERROR_WITH_CLEANUP( yr_object_copy(object_as_array(object)->prototype_item, &o), yr_object_destroy(copy)); object_as_array(copy)->prototype_item = o; break; case OBJECT_TYPE_DICTIONARY: FAIL_ON_ERROR_WITH_CLEANUP( yr_object_copy(object_as_dictionary(object)->prototype_item, &o), yr_object_destroy(copy)); object_as_dictionary(copy)->prototype_item = o; break; default: assert(FALSE); } *object_copy = copy; return ERROR_SUCCESS; } int yr_object_structure_set_member( YR_OBJECT* object, YR_OBJECT* member) { YR_STRUCTURE_MEMBER* sm; assert(object->type == OBJECT_TYPE_STRUCTURE); // Check if the object already have a member with the same identifier if (yr_object_lookup_field(object, member->identifier) != NULL) return ERROR_DUPLICATED_STRUCTURE_MEMBER; sm = (YR_STRUCTURE_MEMBER*) yr_malloc(sizeof(YR_STRUCTURE_MEMBER)); if (sm == NULL) return ERROR_INSUFFICIENT_MEMORY; member->parent = object; sm->object = member; sm->next = object_as_structure(object)->members; object_as_structure(object)->members = sm; return ERROR_SUCCESS; } YR_OBJECT* yr_object_array_get_item( YR_OBJECT* object, int flags, int index) { YR_OBJECT* result = NULL; YR_OBJECT_ARRAY* array; assert(object->type == OBJECT_TYPE_ARRAY); if (index < 0) return NULL; array = object_as_array(object); if (array->items != NULL && array->items->count > index) result = array->items->objects[index]; if (result == NULL && flags & OBJECT_CREATE) { yr_object_copy(array->prototype_item, &result); if (result != NULL) yr_object_array_set_item(object, result, index); } return result; } int yr_object_array_set_item( YR_OBJECT* object, YR_OBJECT* item, int index) { YR_OBJECT_ARRAY* array; int i; int count; assert(index >= 0); assert(object->type == OBJECT_TYPE_ARRAY); array = object_as_array(object); if (array->items == NULL) { count = 64; while (count <= index) count *= 2; array->items = (YR_ARRAY_ITEMS*) yr_malloc( sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; memset(array->items->objects, 0, count * sizeof(YR_OBJECT*)); array->items->count = count; } else if (index >= array->items->count) { count = array->items->count * 2; while (count <= index) count *= 2; array->items = (YR_ARRAY_ITEMS*) yr_realloc( array->items, sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; for (i = array->items->count; i < count; i++) array->items->objects[i] = NULL; array->items->count = count; } item->parent = object; array->items->objects[index] = item; return ERROR_SUCCESS; } YR_OBJECT* yr_object_dict_get_item( YR_OBJECT* object, int flags, const char* key) { int i; YR_OBJECT* result = NULL; YR_OBJECT_DICTIONARY* dict; assert(object->type == OBJECT_TYPE_DICTIONARY); dict = object_as_dictionary(object); if (dict->items != NULL) { for (i = 0; i < dict->items->used; i++) { if (strcmp(dict->items->objects[i].key, key) == 0) result = dict->items->objects[i].obj; } } if (result == NULL && flags & OBJECT_CREATE) { yr_object_copy(dict->prototype_item, &result); if (result != NULL) yr_object_dict_set_item(object, result, key); } return result; } int yr_object_dict_set_item( YR_OBJECT* object, YR_OBJECT* item, const char* key) { YR_OBJECT_DICTIONARY* dict; int i; int count; assert(object->type == OBJECT_TYPE_DICTIONARY); dict = object_as_dictionary(object); if (dict->items == NULL) { count = 64; dict->items = (YR_DICTIONARY_ITEMS*) yr_malloc( sizeof(YR_DICTIONARY_ITEMS) + count * sizeof(dict->items->objects[0])); if (dict->items == NULL) return ERROR_INSUFFICIENT_MEMORY; memset(dict->items->objects, 0, count * sizeof(dict->items->objects[0])); dict->items->free = count; dict->items->used = 0; } else if (dict->items->free == 0) { count = dict->items->used * 2; dict->items = (YR_DICTIONARY_ITEMS*) yr_realloc( dict->items, sizeof(YR_DICTIONARY_ITEMS) + count * sizeof(dict->items->objects[0])); if (dict->items == NULL) return ERROR_INSUFFICIENT_MEMORY; for (i = dict->items->used; i < count; i++) { dict->items->objects[i].key = NULL; dict->items->objects[i].obj = NULL; } dict->items->free = dict->items->used; } item->parent = object; dict->items->objects[dict->items->used].key = yr_strdup(key); dict->items->objects[dict->items->used].obj = item; dict->items->used++; dict->items->free--; return ERROR_SUCCESS; } int yr_object_has_undefined_value( YR_OBJECT* object, const char* field, ...) { YR_OBJECT* field_obj; va_list args; va_start(args, field); if (field != NULL) field_obj = _yr_object_lookup(object, 0, field, args); else field_obj = object; va_end(args); if (field_obj == NULL) return TRUE; switch(field_obj->type) { case OBJECT_TYPE_FLOAT: return isnan(field_obj->value.d); case OBJECT_TYPE_STRING: return field_obj->value.ss == NULL; case OBJECT_TYPE_INTEGER: return field_obj->value.i == UNDEFINED; } return FALSE; } int64_t yr_object_get_integer( YR_OBJECT* object, const char* field, ...) { YR_OBJECT* integer_obj; va_list args; va_start(args, field); if (field != NULL) integer_obj = _yr_object_lookup(object, 0, field, args); else integer_obj = object; va_end(args); if (integer_obj == NULL) return UNDEFINED; assertf(integer_obj->type == OBJECT_TYPE_INTEGER, "type of \"%s\" is not integer\n", field); return integer_obj->value.i; } double yr_object_get_float( YR_OBJECT* object, const char* field, ...) { YR_OBJECT* double_obj; va_list args; va_start(args, field); if (field != NULL) double_obj = _yr_object_lookup(object, 0, field, args); else double_obj = object; va_end(args); if (double_obj == NULL) return NAN; assertf(double_obj->type == OBJECT_TYPE_FLOAT, "type of \"%s\" is not double\n", field); return double_obj->value.d; } SIZED_STRING* yr_object_get_string( YR_OBJECT* object, const char* field, ...) { YR_OBJECT* string_obj; va_list args; va_start(args, field); if (field != NULL) string_obj = _yr_object_lookup(object, 0, field, args); else string_obj = object; va_end(args); if (string_obj == NULL) return NULL; assertf(string_obj->type == OBJECT_TYPE_STRING, "type of \"%s\" is not string\n", field); return string_obj->value.ss; } int yr_object_set_integer( int64_t value, YR_OBJECT* object, const char* field, ...) { YR_OBJECT* integer_obj; va_list args; va_start(args, field); if (field != NULL) integer_obj = _yr_object_lookup(object, OBJECT_CREATE, field, args); else integer_obj = object; va_end(args); assert(integer_obj != NULL); assert(integer_obj->type == OBJECT_TYPE_INTEGER); integer_obj->value.i = value; return ERROR_SUCCESS; } int yr_object_set_float( double value, YR_OBJECT* object, const char* field, ...) { YR_OBJECT* double_obj; va_list args; va_start(args, field); if (field != NULL) double_obj = _yr_object_lookup(object, OBJECT_CREATE, field, args); else double_obj = object; va_end(args); assert(double_obj != NULL); assert(double_obj->type == OBJECT_TYPE_FLOAT); double_obj->value.d = value; return ERROR_SUCCESS; } int yr_object_set_string( const char* value, size_t len, YR_OBJECT* object, const char* field, ...) { YR_OBJECT* string_obj; va_list args; va_start(args, field); if (field != NULL) string_obj = _yr_object_lookup(object, OBJECT_CREATE, field, args); else string_obj = object; va_end(args); assert(string_obj != NULL); assert(string_obj->type == OBJECT_TYPE_STRING); if (string_obj->value.ss != NULL) yr_free(string_obj->value.ss); if (value != NULL) { string_obj->value.ss = (SIZED_STRING*) yr_malloc( len + sizeof(SIZED_STRING)); if (string_obj->value.ss == NULL) return ERROR_INSUFFICIENT_MEMORY; string_obj->value.ss->length = (uint32_t) len; string_obj->value.ss->flags = 0; memcpy(string_obj->value.ss->c_string, value, len); string_obj->value.ss->c_string[len] = '\0'; } else { string_obj->value.ss = NULL; } return ERROR_SUCCESS; } YR_OBJECT* yr_object_get_root( YR_OBJECT* object) { YR_OBJECT* o = object; while (o->parent != NULL) o = o->parent; return o; } YR_API void yr_object_print_data( YR_OBJECT* object, int indent, int print_identifier) { YR_DICTIONARY_ITEMS* dict_items; YR_ARRAY_ITEMS* array_items; YR_STRUCTURE_MEMBER* member; char indent_spaces[32]; int i; indent = yr_min(indent, sizeof(indent_spaces) - 1); memset(indent_spaces, '\t', indent); indent_spaces[indent] = '\0'; if (print_identifier && object->type != OBJECT_TYPE_FUNCTION) printf("%s%s", indent_spaces, object->identifier); switch(object->type) { case OBJECT_TYPE_INTEGER: if (object->value.i != UNDEFINED) printf(" = %" PRIu64, object->value.i); else printf(" = UNDEFINED"); break; case OBJECT_TYPE_STRING: if (object->value.ss != NULL) { size_t l; printf(" = \""); for (l = 0; l < object->value.ss->length; l++) { char c = object->value.ss->c_string[l]; if (isprint((unsigned char) c)) printf("%c", c); else printf("\\x%02x", (unsigned char) c); } printf("\""); } else { printf(" = UNDEFINED"); } break; case OBJECT_TYPE_STRUCTURE: member = object_as_structure(object)->members; while (member != NULL) { if (member->object->type != OBJECT_TYPE_FUNCTION) { printf("\n"); yr_object_print_data(member->object, indent + 1, 1); } member = member->next; } break; case OBJECT_TYPE_ARRAY: array_items = object_as_array(object)->items; if (array_items != NULL) { for (i = 0; i < array_items->count; i++) { if (array_items->objects[i] != NULL) { printf("\n%s\t[%d]", indent_spaces, i); yr_object_print_data(array_items->objects[i], indent + 1, 0); } } } break; case OBJECT_TYPE_DICTIONARY: dict_items = object_as_dictionary(object)->items; if (dict_items != NULL) { for (i = 0; i < dict_items->used; i++) { printf("\n%s\t%s", indent_spaces, dict_items->objects[i].key); yr_object_print_data(dict_items->objects[i].obj, indent + 1, 0); } } break; } }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2568_1
crossvul-cpp_data_good_344_1
/* * Support for ePass2003 smart cards * * Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com> * Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #ifdef ENABLE_SM /* empty file without SM enabled */ #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table epass2003_atrs[] = { /* This is a FIPS certified card using SCP01 security messaging. */ {"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e", "FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00", "FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL }, {NULL, NULL, NULL, 0, 0, NULL} }; static struct sc_card_operations *iso_ops = NULL; static struct sc_card_operations epass2003_ops; static struct sc_card_driver epass2003_drv = { "epass2003", "epass2003", &epass2003_ops, NULL, 0, NULL }; #define KEY_TYPE_AES 0x01 /* FIPS mode */ #define KEY_TYPE_DES 0x02 /* Non-FIPS mode */ #define KEY_LEN_AES 16 #define KEY_LEN_DES 8 #define KEY_LEN_DES3 24 #define HASH_LEN 24 static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID }; /*0x00:plain; 0x01:scp01 sm*/ #define SM_PLAIN 0x00 #define SM_SCP01 0x01 static unsigned char g_init_key_enc[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_init_key_mac[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_random[8] = { 0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40 }; typedef struct epass2003_exdata_st { unsigned char sm; /* SM_PLAIN or SM_SCP01 */ unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */ unsigned char sk_enc[16]; /* encrypt session key */ unsigned char sk_mac[16]; /* mac session key */ unsigned char icv_mac[16]; /* instruction counter vector(for sm) */ unsigned char currAlg; /* current Alg */ unsigned int ecAlgFlags; /* Ec Alg mechanism type*/ } epass2003_exdata; #define REVERSE_ORDER4(x) ( \ ((unsigned long)x & 0xFF000000)>> 24 | \ ((unsigned long)x & 0x00FF0000)>> 8 | \ ((unsigned long)x & 0x0000FF00)<< 8 | \ ((unsigned long)x & 0x000000FF)<< 24) static const struct sc_card_error epass2003_errors[] = { { 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" }, { 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" }, { 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" }, { 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" }, { 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" }, { 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"}, { 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"}, { 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" }, { 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" }, { 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" }, { 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" }, { 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" }, { 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" }, { 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" }, { 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" }, { 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" }, { 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" }, { 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" }, { 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" }, { 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" }, { 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" }, { 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" }, { 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" }, { 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" }, { 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" }, { 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" }, { 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" }, { 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" }, { 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" }, { 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" }, { 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" }, { 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"}, { 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"}, { 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" }, { 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" }, { 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" }, { 0x9000,SC_SUCCESS, NULL } }; static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu); static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out); int epass2003_refresh(struct sc_card *card); static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType); static int epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]); int i; /* Handle special cases here */ if (sw1 == 0x6C) { sc_log(card->ctx, "Wrong length; correct length is %d", sw2); return SC_ERROR_WRONG_LENGTH; } for (i = 0; i < err_count; i++) { if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) { sc_log(card->ctx, "%s", epass2003_errors[i].errorstr); return epass2003_errors[i].errorno; } } sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2); return SC_ERROR_CARD_CMD_FAILED; } static int sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu) { int r = sc_transmit_apdu(card, apdu); if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2))) { epass2003_refresh(card); r = sc_transmit_apdu(card, apdu); } return r; } static int openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_EncryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_DecryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int aes128_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, size_t length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output); } static int aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output); } static int aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output); } static int des3_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, int length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output); } static int des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_des_cbc(), key, iv, input, length, output); } static int des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_des_cbc(), key, iv, input, length, output); } static int openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length, unsigned char *output) { int r = 0; EVP_MD_CTX *ctx = NULL; unsigned outl = 0; ctx = EVP_MD_CTX_create(); if (ctx == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } EVP_MD_CTX_init(ctx); EVP_DigestInit_ex(ctx, digest, NULL); if (!EVP_DigestUpdate(ctx, input, length)) { r = SC_ERROR_INTERNAL; goto err; } if (!EVP_DigestFinal_ex(ctx, output, &outl)) { r = SC_ERROR_INTERNAL; goto err; } r = SC_SUCCESS; err: if (ctx) EVP_MD_CTX_destroy(ctx); return r; } static int sha1_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha1(), input, length, output); } static int sha256_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha256(), input, length, output); } static int gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac, unsigned char *result, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned char data[256] = { 0 }; unsigned char tmp_sm; unsigned long blocksize = 0; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = sizeof(g_random); apdu.data = g_random; /* host random */ apdu.le = apdu.resplen = 28; apdu.resp = result; /* card random is result[12~19] */ tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "gen_init_key failed"); /* Step 1 - Generate Derivation data */ memcpy(data, &result[16], 4); memcpy(&data[4], g_random, 4); memcpy(&data[8], &result[12], 4); memcpy(&data[12], &g_random[4], 4); /* Step 2,3 - Create S-ENC/S-MAC Session Key */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } else { des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } memcpy(data, g_random, 8); memcpy(&data[8], &result[12], 8); data[16] = 0x80; blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); memset(&data[17], 0x00, blocksize - 1); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); /* verify card cryptogram */ if (0 != memcmp(&cryptogram[16], &result[20], 8)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); unsigned char data[256] = { 0 }; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; unsigned char mac[256] = { 0 }; unsigned long i; unsigned char tmp_sm; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); memcpy(data, ran_key, 8); memcpy(&data[8], g_random, 8); data[16] = 0x80; memset(&data[17], 0x00, blocksize - 1); memset(iv, 0, 16); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } else { des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } memset(data, 0, sizeof(data)); memcpy(data, "\x84\x82\x03\x00\x10", 5); memcpy(&data[5], &cryptogram[16], 8); memcpy(&data[13], "\x80\x00\x00", 3); /* calculate mac icv */ memset(iv, 0x00, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 0; } else { des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 8; } /* save mac icv */ memset(exdata->icv_mac, 0x00, 16); memcpy(exdata->icv_mac, &mac[i], 8); /* verify host cryptogram */ memcpy(data, &cryptogram[16], 8); memcpy(&data[8], &mac[i], 8); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00); apdu.cla = 0x84; apdu.lc = apdu.datalen = 16; apdu.data = data; tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU verify_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "verify_init_key failed"); return r; } static int mutual_auth(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac) { struct sc_context *ctx = card->ctx; int r; unsigned char result[256] = { 0 }; unsigned char ran_key[8] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(ctx); r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype); LOG_TEST_RET(ctx, r, "gen_init_key failed"); memcpy(ran_key, &result[12], 8); r = verify_init_key(card, ran_key, exdata->smtype); LOG_TEST_RET(ctx, r, "verify_init_key failed"); LOG_FUNC_RETURN(ctx, r); } int epass2003_refresh(struct sc_card *card) { int r = SC_SUCCESS; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (exdata->sm) { card->sm_ctx.sm_mode = 0; r = mutual_auth(card, g_init_key_enc, g_init_key_mac); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; LOG_TEST_RET(card->ctx, r, "mutual_auth failed"); } return r; } /* Data(TLV)=0x87|L|0x01+Cipher */ static int construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf, unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char pad[4096] = { 0 }; size_t pad_len; size_t tlv_more; /* increased tlv length */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* padding */ apdu_buf[block_size] = 0x87; memcpy(pad, apdu->data, apdu->lc); pad[apdu->lc] = 0x80; if ((apdu->lc + 1) % block_size) pad_len = ((apdu->lc + 1) / block_size + 1) * block_size; else pad_len = apdu->lc + 1; /* encode Lc' */ if (pad_len > 0x7E) { /* Lc' > 0x7E, use extended APDU */ apdu_buf[block_size + 1] = 0x82; apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100); apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100); apdu_buf[block_size + 4] = 0x01; tlv_more = 5; } else { apdu_buf[block_size + 1] = (unsigned char)pad_len + 1; apdu_buf[block_size + 2] = 0x01; tlv_more = 3; } memcpy(data_tlv, &apdu_buf[block_size], tlv_more); /* encrypt Data */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len); *data_tlv_len = tlv_more + pad_len; return 0; } /* Le(TLV)=0x97|L|Le */ static int construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len, unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); *(apdu_buf + block_size + data_tlv_len) = 0x97; if (apdu->le > 0x7F) { /* Le' > 0x7E, use extended APDU */ *(apdu_buf + block_size + data_tlv_len + 1) = 2; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100); *(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100); memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4); *le_tlv_len = 4; } else { *(apdu_buf + block_size + data_tlv_len + 1) = 1; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le; memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3); *le_tlv_len = 3; } return 0; } /* MAC(TLV)=0x8e|0x08|MAC */ static int construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, sizeof iv); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; } /* According to GlobalPlatform Card Specification's SCP01 * encode APDU from * CLA INS P1 P2 [Lc] Data [Le] * to * CLA INS P1 P2 Lc' Data' [Le] * where * Data'=Data(TLV)+Le(TLV)+MAC(TLV) */ static int encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm, unsigned char *apdu_buf, size_t * apdu_buf_len) { size_t block_size = 0; unsigned char dataTLV[4096] = { 0 }; size_t data_tlv_len = 0; unsigned char le_tlv[256] = { 0 }; size_t le_tlv_len = 0; size_t mac_tlv_len = 10; size_t tmp_lc = 0; size_t tmp_le = 0; unsigned char mac_tlv[256] = { 0 }; epass2003_exdata *exdata = NULL; mac_tlv[0] = 0x8E; mac_tlv[1] = 8; /* size_t plain_le = 0; */ if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata*)card->drv_data; block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8); sm->cse = SC_APDU_CASE_4_SHORT; apdu_buf[0] = (unsigned char)plain->cla; apdu_buf[1] = (unsigned char)plain->ins; apdu_buf[2] = (unsigned char)plain->p1; apdu_buf[3] = (unsigned char)plain->p2; /* plain_le = plain->le; */ /* padding */ apdu_buf[4] = 0x80; memset(&apdu_buf[5], 0x00, block_size - 5); /* Data -> Data' */ if (plain->lc != 0) if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype)) return -1; if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0)) if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv, &le_tlv_len, exdata->smtype)) return -1; if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype)) return -1; memset(apdu_buf + 4, 0, *apdu_buf_len - 4); sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len; if (sm->lc > 0xFF) { sm->cse = SC_APDU_CASE_4_EXT; apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000); apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100); apdu_buf[6] = (unsigned char)((sm->lc) % 0x100); tmp_lc = 3; } else { apdu_buf[4] = (unsigned char)sm->lc; tmp_lc = 1; } memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len); memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen); *apdu_buf_len = 0; if (4 == le_tlv_len) { sm->cse = SC_APDU_CASE_4_EXT; *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100); *(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100); tmp_le = 2; } else if (3 == le_tlv_len) { *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le; tmp_le = 1; } *apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le; /* sm->le = calc_le(plain_le); */ return 0; } static int epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm) { unsigned char buf[4096] = { 0 }; /* APDU buffer */ size_t buf_len = sizeof(buf); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); if (exdata->sm) plain->cla |= 0x0C; sm->cse = plain->cse; sm->cla = plain->cla; sm->ins = plain->ins; sm->p1 = plain->p1; sm->p2 = plain->p2; sm->lc = plain->lc; sm->le = plain->le; sm->control = plain->control; sm->flags = plain->flags; switch (sm->cla & 0x0C) { case 0x00: case 0x04: sm->datalen = plain->datalen; memcpy((void *)sm->data, plain->data, plain->datalen); sm->resplen = plain->resplen; memcpy(sm->resp, plain->resp, plain->resplen); break; case 0x0C: memset(buf, 0, sizeof(buf)); if (0 != encode_apdu(card, plain, sm, buf, &buf_len)) return SC_ERROR_CARD_CMD_FAILED; break; default: return SC_ERROR_INCORRECT_PARAMETERS; } return SC_SUCCESS; } /* According to GlobalPlatform Card Specification's SCP01 * decrypt APDU response from * ResponseData' SW1 SW2 * to * ResponseData SW1 SW2 * where * ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV) * where * Data(TLV)=0x87|L|Cipher * SW12(TLV)=0x99|0x02|SW1+SW2 * MAC(TLV)=0x8e|0x08|MAC */ static int decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len || *out_len < cipher_len - 2) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } static int epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { len = plain->resplen; if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); if (!sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); if (!(*sm_apdu)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (plain) rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain); if ((*sm_apdu)->data) { unsigned char * p = (unsigned char *)((*sm_apdu)->data); free(p); } if ((*sm_apdu)->resp) { free((*sm_apdu)->resp); } free(*sm_apdu); *sm_apdu = NULL; LOG_FUNC_RETURN(ctx, rv); } static int epass2003_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; struct sc_apdu *apdu = NULL; int rv; LOG_FUNC_CALLED(ctx); if (!plain || !sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); *sm_apdu = NULL; //construct new SM apdu from original apdu apdu = calloc(1, sizeof(struct sc_apdu)); if (!apdu) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->resp) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE; apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE; rv = epass2003_sm_wrap_apdu(card, plain, apdu); if (rv) { rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu); if (rv < 0) goto err; } *sm_apdu = apdu; apdu = NULL; err: if (apdu) { free((unsigned char *) apdu->data); free(apdu->resp); free(apdu); apdu = NULL; } LOG_FUNC_RETURN(ctx, rv); } static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu) { int r; LOG_FUNC_CALLED(card->ctx); r = sc_transmit_apdu_t(card, apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return r; } static int get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t resplen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type); apdu.resp = resp; apdu.le = 0; apdu.resplen = resplen; if (0x86 == type) { /* No SM temporarily */ unsigned char tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = sc_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; } else { r = sc_transmit_apdu_t(card, &apdu); } LOG_TEST_RET(card->ctx, r, "APDU get_data failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get_data failed"); memcpy(data, resp, datalen); return r; } /* card driver functions */ static int epass2003_match_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); r = _sc_match_atr(card, epass2003_atrs, &card->type); if (r < 0) return 0; return 1; } static int epass2003_init(struct sc_card *card) { unsigned int flags; unsigned int ext_flags; unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t datalen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); card->name = "epass2003"; card->cla = 0x00; exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata)); if (!exdata) return SC_ERROR_OUT_OF_MEMORY; card->drv_data = exdata; exdata->sm = SM_SCP01; /* decide FIPS/Non-FIPS mode */ if (SC_SUCCESS != get_data(card, 0x86, data, datalen)) return SC_ERROR_INVALID_CARD; if (0x01 == data[2]) exdata->smtype = KEY_TYPE_AES; else exdata->smtype = KEY_TYPE_DES; if (0x84 == data[14]) { if (0x00 == data[16]) { exdata->sm = SM_PLAIN; } } /* mutual authentication */ card->max_recv_size = 0xD8; card->max_send_size = 0xE8; card->sm_ctx.ops.open = epass2003_refresh; card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu; card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu; /* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */ epass2003_refresh(card); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); //set EC Alg Flags flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW; ext_flags = 0; _sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL); card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_finish(sc_card_t *card) { epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data; if (exdata) free(exdata); return SC_SUCCESS; } /* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the * same DF, so use hook functions to increase/decrease FID by 0x20 */ static int epass2003_hook_path(struct sc_path *path, int inc) { u8 fid_h = path->value[path->len - 2]; u8 fid_l = path->value[path->len - 1]; switch (fid_h) { case 0x29: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: if (inc) fid_l = fid_l * FID_STEP; else fid_l = fid_l / FID_STEP; path->value[path->len - 1] = fid_l; return 1; default: break; } return 0; } static void epass2003_hook_file(struct sc_file *file, int inc) { int fidl = file->id & 0xff; int fidh = file->id & 0xff00; if (epass2003_hook_path(&file->path, inc)) { if (inc) file->id = fidh + fidl * FID_STEP; else file->id = fidh + fidl / FID_STEP; } } static int epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out) { struct sc_apdu apdu; u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen; sc_file_t *file = NULL; epass2003_hook_path(in_path, 1); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: apdu.p1 = 0; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.p2 = 0; /* first record, return FCI */ apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 0; } else { apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */ /* Not allowed to select private key file, so fake fci. */ /* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */ apdu.resplen = 0x18; memcpy(apdu.resp, "\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff", apdu.resplen); apdu.resp[9] = path[1]; apdu.sw1 = 0x90; apdu.sw2 = 0x00; } else { r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); } if (file_out == NULL) { if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(card->ctx, 0); LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(card->ctx, r); if (apdu.resplen < 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); switch (apdu.resp[0]) { case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; if (card->ops->process_fci == NULL) { sc_file_free(file); LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } if ((size_t) apdu.resp[1] + 2 <= apdu.resplen) card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]); epass2003_hook_file(file, 0); *file_out = file; break; case 0x00: /* proprietary coding */ LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } return 0; } static int epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo, sc_file_t ** file_out) { int r; sc_file_t *file = 0; sc_path_t path; memset(&path, 0, sizeof(path)); path.type = SC_PATH_TYPE_FILE_ID; path.value[0] = id_hi; path.value[1] = id_lo; path.len = 2; r = epass2003_select_fid_(card, &path, &file); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ if (file && file->type == SC_FILE_TYPE_DF) { card->cache.current_path.type = SC_PATH_TYPE_PATH; card->cache.current_path.value[0] = 0x3f; card->cache.current_path.value[1] = 0x00; if (id_hi == 0x3f && id_lo == 0x00) { card->cache.current_path.len = 2; } else { card->cache.current_path.len = 4; card->cache.current_path.value[2] = id_hi; card->cache.current_path.value[3] = id_lo; } } if (file_out) *file_out = file; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r = 0; if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_DF_NAME && card->cache.current_path.len == in_path->len && memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) { if (file_out) { *file_out = sc_file_new(); if (!file_out) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } } else { r = iso_ops->select_file(card, in_path, file_out); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ card->cache.current_path.type = SC_PATH_TYPE_DF_NAME; card->cache.current_path.len = in_path->len; memcpy(card->cache.current_path.value, in_path->value, in_path->len); } if (file_out) { sc_file_t *file = *file_out; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->path.len = 0; file->size = 0; /* AID */ memcpy(file->name, in_path->value, in_path->len); file->namelen = in_path->len; file->id = 0x0000; } LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len, sc_file_t ** file_out) { u8 n_pathbuf[SC_MAX_PATH_SIZE]; const u8 *path = pathbuf; size_t pathlen = len; int bMatch = -1; unsigned int i; int r; if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* if pathlen == 6 then the first FID must be MF (== 3F00) */ if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* unify path (the first FID should be MF) */ if (path[0] != 0x3f || path[1] != 0x00) { n_pathbuf[0] = 0x3f; n_pathbuf[1] = 0x00; for (i = 0; i < pathlen; i++) n_pathbuf[i + 2] = pathbuf[i]; path = n_pathbuf; pathlen += 2; } /* check current working directory */ if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_PATH && card->cache.current_path.len >= 2 && card->cache.current_path.len <= pathlen) { bMatch = 0; for (i = 0; i < card->cache.current_path.len; i += 2) if (card->cache.current_path.value[i] == path[i] && card->cache.current_path.value[i + 1] == path[i + 1]) bMatch += 2; } if (card->cache.valid && bMatch > 2) { if (pathlen - bMatch == 2) { /* we are in the right directory */ return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out); } else if (pathlen - bMatch > 2) { /* two more steps to go */ sc_path_t new_path; /* first step: change directory */ r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); new_path.type = SC_PATH_TYPE_PATH; new_path.len = pathlen - bMatch - 2; memcpy(new_path.value, &(path[bMatch + 2]), new_path.len); /* final step: select file */ return epass2003_select_file(card, &new_path, file_out); } else { /* if (bMatch - pathlen == 0) */ /* done: we are already in the * requested directory */ sc_log(card->ctx, "cache hit\n"); /* copy file info (if necessary) */ if (file_out) { sc_file_t *file = sc_file_new(); if (!file) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->id = (path[pathlen - 2] << 8) + path[pathlen - 1]; file->path = card->cache.current_path; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->size = 0; file->namelen = 0; file->magic = SC_FILE_MAGIC; *file_out = file; } /* nothing left to do */ return SC_SUCCESS; } } else { /* no usable cache */ for (i = 0; i < pathlen - 2; i += 2) { r = epass2003_select_fid(card, path[i], path[i + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); } return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out); } } static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r; char pbuf[SC_MAX_PATH_STRING_SIZE]; LOG_FUNC_CALLED(card->ctx); r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path); if (r != SC_SUCCESS) pbuf[0] = '\0'; sc_log(card->ctx, "current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n", card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ? "aid" : "path", card->cache.valid ? "valid" : "invalid", pbuf, card->cache.current_path.len); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (in_path->len != 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out); case SC_PATH_TYPE_DF_NAME: return epass2003_select_aid(card, in_path, file_out); case SC_PATH_TYPE_PATH: return epass2003_select_path(card, in_path->value, in_path->len, file_out); default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } } static int epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num) { struct sc_apdu apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 *p; unsigned short fid = 0; int r, locked = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0); p = sbuf; *p++ = 0x80; /* algorithm reference */ *p++ = 0x01; *p++ = 0x84; *p++ = 0x81; *p++ = 0x02; fid = 0x2900; fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff)); *p++ = fid >> 8; *p++ = fid & 0xff; r = p - sbuf; apdu.lc = r; apdu.datalen = r; apdu.data = sbuf; if (env->algorithm == SC_ALGORITHM_EC) { apdu.p2 = 0xB6; exdata->currAlg = SC_ALGORITHM_EC; if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1) { sbuf[2] = 0x91; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1; } else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256) { sbuf[2] = 0x92; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256; } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags); goto err; } } else if(env->algorithm == SC_ALGORITHM_RSA) { exdata->currAlg = SC_ALGORITHM_RSA; apdu.p2 = 0xB8; sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags); } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm); } if (se_num > 0) { r = sc_lock(card); LOG_TEST_RET(card->ctx, r, "sc_lock() failed"); locked = 1; } if (apdu.datalen != 0) { r = sc_transmit_apdu_t(card, &apdu); if (r) { sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r)); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) { sc_log(card->ctx, "%s: Card returned error", sc_strerror(r)); goto err; } } if (se_num <= 0) return 0; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num); r = sc_transmit_apdu_t(card, &apdu); sc_unlock(card); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); err: if (locked) sc_unlock(card); return r; } static int epass2003_restore_security_env(struct sc_card *card, int se_num) { LOG_FUNC_CALLED(card->ctx); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if(exdata->currAlg == SC_ALGORITHM_EC) { if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x14; apdu.datalen = 0x14; } else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x20; apdu.datalen = 0x20; } else { return SC_ERROR_NOT_SUPPORTED; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } else if(exdata->currAlg == SC_ALGORITHM_RSA) { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } else { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e) { if (e == NULL) return SC_ERROR_OBJECT_NOT_FOUND; switch (e->method) { case SC_AC_NONE: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE); case SC_AC_NEVER: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE); default: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); } static int epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen) { sc_context_t *ctx = card->ctx; size_t taglen, len = buflen; const u8 *tag = NULL, *p = buf; sc_log(ctx, "processing FCI bytes"); tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen); if (tag != NULL && taglen == 2) { file->id = (tag[0] << 8) | tag[1]; sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]); } tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen); if (tag != NULL && taglen > 0 && taglen < 3) { file->size = tag[0]; if (taglen == 2) file->size = (file->size << 8) + tag[1]; sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u", file->size); } if (tag == NULL) { tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen); if (tag != NULL && taglen >= 2) { int bytes = (tag[0] << 8) + tag[1]; sc_log(ctx, " bytes in file: %d", bytes); file->size = bytes; } } tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen); if (tag != NULL) { if (taglen > 0) { unsigned char byte = tag[0]; const char *type; if (byte == 0x38) { type = "DF"; file->type = SC_FILE_TYPE_DF; } else if (0x01 <= byte && byte <= 0x07) { type = "working EF"; file->type = SC_FILE_TYPE_WORKING_EF; switch (byte) { case 0x01: file->ef_structure = SC_FILE_EF_TRANSPARENT; break; case 0x02: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x04: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x03: case 0x05: case 0x06: case 0x07: break; default: break; } } else if (0x10 == byte) { type = "BSO"; file->type = SC_FILE_TYPE_BSO; } else if (0x11 <= byte) { type = "internal EF"; file->type = SC_FILE_TYPE_INTERNAL_EF; switch (byte) { case 0x11: break; case 0x12: break; default: break; } } else { type = "unknown"; file->type = SC_FILE_TYPE_INTERNAL_EF; } sc_log(ctx, "type %s, EF structure %d", type, byte); } } tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen); if (tag != NULL && taglen > 0 && taglen <= 16) { memcpy(file->name, tag, taglen); file->namelen = taglen; sc_log_hex(ctx, "File name", file->name, file->namelen); if (!file->type) file->type = SC_FILE_TYPE_DF; } tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); else file->prop_attr_len = 0; tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen); if (tag != NULL && taglen) sc_file_set_sec_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen); if (tag != NULL && taglen == 1) { if (tag[0] == 0x01) file->status = SC_FILE_STATUS_CREATION; else if (tag[0] == 0x07 || tag[0] == 0x05) file->status = SC_FILE_STATUS_ACTIVATED; else if (tag[0] == 0x06 || tag[0] == 0x04) file->status = SC_FILE_STATUS_INVALIDATED; } file->magic = SC_FILE_MAGIC; return 0; } static int epass2003_construct_fci(struct sc_card *card, const sc_file_t * file, u8 * out, size_t * outlen) { u8 *p = out; u8 buf[64]; unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; int rv; unsigned ii; if (*outlen < 2) return SC_ERROR_BUFFER_TOO_SMALL; *p++ = 0x62; p++; if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p); } } if (file->type == SC_FILE_TYPE_DF) { buf[0] = 0x38; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_WORKING_EF) { buf[0] = file->ef_structure & 7; if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { buf[1] = 0x00; buf[2] = 0x00; buf[3] = 0x40; /* record length */ buf[4] = 0x00; /* record count */ sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p); } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { buf[0] = 0x11; buf[1] = 0x00; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = 0x12; buf[1] = 0x00; } else { return SC_ERROR_NOT_SUPPORTED; } sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = 0x10; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p); if (file->type == SC_FILE_TYPE_DF) { if (file->namelen != 0) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p); } else { return SC_ERROR_INVALID_ARGUMENTS; } } if (file->type == SC_FILE_TYPE_DF) { unsigned char data[2] = {0x00, 0x7F}; /* 127 files at most */ sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = file->size & 0xff; sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p); } } if (file->sec_attr_len) { memcpy(buf, file->sec_attr, file->sec_attr_len); sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p); } else { sc_log(card->ctx, "SC_FILE_ACL"); if (file->type == SC_FILE_TYPE_DF) { ops[0] = SC_AC_OP_LIST_FILES; ops[1] = SC_AC_OP_CREATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_WRITE; ops[3] = SC_AC_OP_DELETE; } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_BSO) { ops[0] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } } else { return SC_ERROR_NOT_SUPPORTED; } for (ii = 0; ii < sizeof(ops); ii++) { const struct sc_acl_entry *entry; buf[ii] = 0xFF; if (ops[ii] == 0xFF) continue; entry = sc_file_get_acl_entry(file, ops[ii]); rv = acl_to_ac_byte(card, entry); LOG_TEST_RET(card->ctx, rv, "Invalid ACL"); buf[ii] = rv; } sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x13; } } /* VT ??? */ if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { unsigned char data[2] = {0x00, 0x66}; sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x14; } } out[1] = p - out - 2; *outlen = p - out; return 0; } static int epass2003_create_file(struct sc_card *card, sc_file_t * file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; struct sc_apdu apdu; len = SC_MAX_APDU_BUFFER_SIZE; epass2003_hook_file(file, 1); if (card->ops->construct_fci == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); r = epass2003_construct_fci(card, file, sbuf, &len); LOG_TEST_RET(card->ctx, r, "construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong"); epass2003_hook_file(file, 0); return r; } static int epass2003_delete_file(struct sc_card *card, const sc_path_t * path) { int r; u8 sbuf[2]; struct sc_apdu apdu; LOG_FUNC_CALLED(card->ctx); r = sc_select_file(card, path, NULL); epass2003_hook_path((struct sc_path *)path, 1); if (r == SC_SUCCESS) { sbuf[0] = path->value[path->len - 2]; sbuf[1] = path->value[path->len - 1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Delete file failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen) { struct sc_apdu apdu; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00); apdu.cla = 0x80; apdu.le = 0; apdu.resplen = sizeof(rbuf); apdu.resp = rbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Card returned error"); if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0) LOG_FUNC_RETURN(card->ctx, 0); buflen = buflen < apdu.resplen ? buflen : apdu.resplen; memcpy(buf, rbuf, buflen); LOG_FUNC_RETURN(card->ctx, buflen); } static int internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor, sc_pkcs15_bignum_t data) { int r; struct sc_apdu apdu; u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); sbuff[0] = ((fid & 0xff00) >> 8); sbuff[1] = (fid & 0x00ff); memcpy(&sbuff[2], data.data, data.len); // sc_mem_reverse(&sbuff[2], data.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 2 + data.len; apdu.data = sbuff; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa) { int r; LOG_FUNC_CALLED(card->ctx); r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus); LOG_TEST_RET(card->ctx, r, "write n failed"); r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d); LOG_TEST_RET(card->ctx, r, "write d failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType) { if ((NULL == data) || (NULL == hash)) return SC_ERROR_INVALID_ARGUMENTS; if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1) { unsigned char data_hash[24] = { 0 }; size_t len = 0; sha1_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[20], &len, 4); memcpy(hash, data_hash, 24); } else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256) { unsigned char data_hash[36] = { 0 }; size_t len = 0; sha256_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[32], &len, 4); memcpy(hash, data_hash, 36); } else { return SC_ERROR_NOT_SUPPORTED; } return SC_SUCCESS; } static int install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, unsigned char useac, unsigned char modifyac, unsigned char EC, unsigned char *data, unsigned long dataLen) { int r; struct sc_apdu apdu; unsigned char isapp = 0x00; /* appendable */ unsigned char tmp_data[256] = { 0 }; tmp_data[0] = ktype; tmp_data[1] = kid; tmp_data[2] = useac; tmp_data[3] = modifyac; tmp_data[8] = 0xFF; if (0x04 == ktype || 0x06 == ktype) { tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO); tmp_data[9] = (EC << 4) | EC; } memcpy(&tmp_data[10], data, dataLen); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 10 + dataLen; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "install_secret_key failed"); return r; } static int internal_install_pre(struct sc_card *card) { int r; /* init key for enc */ r = install_secret_key(card, 0x01, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_enc, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); /* init key for mac */ r = install_secret_key(card, 0x02, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_mac, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); return r; } /* use external auth secret as pin */ static int internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin) { int r; unsigned char hash[HASH_LEN] = { 0 }; r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid, pin->key_data.es_secret.ac[0], pin->key_data.es_secret.ac[1], pin->key_data.es_secret.EC, hash, HASH_LEN); LOG_TEST_RET(card->ctx, r, "Install failed"); return r; } static int epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data) { LOG_FUNC_CALLED(card->ctx); if (data->type & SC_EPASS2003_KEY) { if (data->type == SC_EPASS2003_KEY_RSA) return internal_write_rsa_key(card, data->key_data.es_key.fid, data->key_data.es_key.rsa); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else if (data->type & SC_EPASS2003_SECRET) { if (data->type == SC_EPASS2003_SECRET_PRE) return internal_install_pre(card); else if (data->type == SC_EPASS2003_SECRET_PIN) return internal_install_pin(card, data); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data) { int r; size_t len = data->key_length; struct sc_apdu apdu; u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); if(len == 256) { sbuf[0] = 0x02; } else { sbuf[0] = 0x01; } sbuf[1] = (u8) ((len >> 8) & 0xff); sbuf[2] = (u8) (len & 0xff); sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF); sbuf[4] = (u8) ((data->prkey_id) & 0xFF); sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF); sbuf[6] = (u8) ((data->pukey_id) & 0xFF); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.lc = apdu.datalen = 7; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "generate keypair failed"); /* read public key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00); if(len == 256) { apdu.p1 = 0x00; } apdu.cla = 0x80; apdu.lc = apdu.datalen = 2; apdu.data = &sbuf[5]; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x00; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get pukey failed"); if (len < apdu.resplen) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); data->modulus = (u8 *) malloc(len); if (!data->modulus) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(data->modulus, rbuf, len); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_erase_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); sc_invalidate_cache(card); r = sc_delete_file(card, sc_get_mf_path()); LOG_TEST_RET(card->ctx, r, "delete MF failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial) { u8 rbuf[8]; size_t rbuf_len = sizeof(rbuf); LOG_FUNC_CALLED(card->ctx); if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len)) return SC_ERROR_CARD_CMD_FAILED; card->serialnr.len = serial->len = 8; memcpy(card->serialnr.value, rbuf, 8); memcpy(serial->value, rbuf, 8); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd is %0lx", cmd); switch (cmd) { case SC_CARDCTL_ENTERSAFE_WRITE_KEY: return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr); case SC_CARDCTL_ENTERSAFE_GENERATE_KEY: return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr); case SC_CARDCTL_ERASE_CARD: return epass2003_erase_card(card); case SC_CARDCTL_GET_SERIALNR: return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr); default: return SC_ERROR_NOT_SUPPORTED; } } static void internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num) { pin->encoding = SC_PIN_ENCODING_ASCII; pin->min_length = 4; pin->max_length = 16; pin->pad_length = 16; pin->offset = 5 + num * 16; pin->pad_char = 0x00; } static int get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries) { unsigned char maxcounter[2] = { 0 }; static const sc_path_t file_path = { {0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6, 0, 0, SC_PATH_TYPE_PATH, {{0}, 0} }; int ret; ret = sc_select_file(card, &file_path, NULL); LOG_TEST_RET(card->ctx, ret, "select max counter file failed"); ret = sc_read_binary(card, 0, maxcounter, 2, 0); LOG_TEST_RET(card->ctx, ret, "read max counter file failed"); *maxtries = maxcounter[0]; return SC_SUCCESS; } static int get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid); apdu.resp = NULL; apdu.resplen = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed"); if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) { *retries = (apdu.sw2 & 0x0f); r = SC_SUCCESS; } else { LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed"); r = SC_ERROR_CARD_CMD_FAILED; } return r; } static int epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { u8 rbuf[16]; size_t out_len; int r; LOG_FUNC_CALLED(card->ctx); r = iso_ops->get_challenge(card, rbuf, sizeof rbuf); LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed"); if (len < (size_t) r) { out_len = len; } else { out_len = (size_t) r; } memcpy(rnd, rbuf, out_len); LOG_FUNC_RETURN(card->ctx, (int) out_len); } static int external_key_auth(struct sc_card *card, unsigned char kid, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; unsigned char tmp_data[16] = { 0 }; unsigned char hash[HASH_LEN] = { 0 }; unsigned char iv[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed"); r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid); apdu.lc = apdu.datalen = 8; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "external_key_auth failed"); return r; } static int update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, const unsigned char *data, unsigned long datalen) { int r; struct sc_apdu apdu; unsigned char hash[HASH_LEN] = { 0 }; unsigned char tmp_data[256] = { 0 }; unsigned char maxtries = 0; r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); tmp_data[0] = (maxtries << 4) | maxtries; memcpy(&tmp_data[1], hash, HASH_LEN); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid); apdu.cla = 0x80; apdu.lc = apdu.datalen = 1 + HASH_LEN; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "update_secret_key failed"); return r; } /* use external auth secret as pin */ static int epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { int r; u8 kid; u8 retries = 0; u8 pin_low = 3; unsigned char maxtries = 0; LOG_FUNC_CALLED(card->ctx); internal_sanitize_pin_info(&data->pin1, 0); internal_sanitize_pin_info(&data->pin2, 1); data->flags |= SC_PIN_CMD_NEED_PADDING; kid = data->pin_reference; /* get pin retries */ if (data->cmd == SC_PIN_CMD_GET_INFO) { r = get_external_key_retries(card, 0x80 | kid, &retries); if (r == SC_SUCCESS) { data->pin1.tries_left = retries; if (tries_left) *tries_left = retries; r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); data->pin1.max_tries = maxtries; } //remove below code, because the old implement only return PIN retries, now modify the code and return PIN status // return r; } else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */ r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data, data->pin1.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */ r = update_secret_key(card, 0x04, kid, data->pin2.data, (unsigned long)data->pin2.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else { r = external_key_auth(card, kid, (unsigned char *)data->pin1.data, data->pin1.len); get_external_key_retries(card, 0x80 | kid, &retries); if (retries < pin_low) sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries); } LOG_TEST_RET(card->ctx, r, "verify pin failed"); if (r == SC_SUCCESS) { data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN; } return r; } static struct sc_card_driver *sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; epass2003_ops = *iso_ops; epass2003_ops.match_card = epass2003_match_card; epass2003_ops.init = epass2003_init; epass2003_ops.finish = epass2003_finish; epass2003_ops.write_binary = NULL; epass2003_ops.write_record = NULL; epass2003_ops.select_file = epass2003_select_file; epass2003_ops.get_response = NULL; epass2003_ops.restore_security_env = epass2003_restore_security_env; epass2003_ops.set_security_env = epass2003_set_security_env; epass2003_ops.decipher = epass2003_decipher; epass2003_ops.compute_signature = epass2003_decipher; epass2003_ops.create_file = epass2003_create_file; epass2003_ops.delete_file = epass2003_delete_file; epass2003_ops.list_files = epass2003_list_files; epass2003_ops.card_ctl = epass2003_card_ctl; epass2003_ops.process_fci = epass2003_process_fci; epass2003_ops.construct_fci = epass2003_construct_fci; epass2003_ops.pin_cmd = epass2003_pin_cmd; epass2003_ops.check_sw = epass2003_check_sw; epass2003_ops.get_challenge = epass2003_get_challenge; return &epass2003_drv; } struct sc_card_driver *sc_get_epass2003_driver(void) { return sc_get_driver(); } #endif /* #ifdef ENABLE_OPENSSL */ #endif /* #ifdef ENABLE_SM */
./CrossVul/dataset_final_sorted/CWE-119/c/good_344_1
crossvul-cpp_data_good_340_6
/* * pkcs15-sc-hsm.c : Initialize PKCS#15 emulation * * Copyright (C) 2012 Andreas Schwier, CardContact, Minden, Germany * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #include "asn1.h" #include "common/compat_strlcpy.h" #include "common/compat_strnlen.h" #include "card-sc-hsm.h" extern struct sc_aid sc_hsm_aid; void sc_hsm_set_serialnr(sc_card_t *card, char *serial); static struct ec_curve curves[] = { { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x01", 8}, // secp192r1 aka prime192r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 24}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 24}, { (unsigned char *) "\x64\x21\x05\x19\xE5\x9C\x80\xE7\x0F\xA7\xE9\xAB\x72\x24\x30\x49\xFE\xB8\xDE\xEC\xC1\x46\xB9\xB1", 24}, { (unsigned char *) "\x04\x18\x8D\xA8\x0E\xB0\x30\x90\xF6\x7C\xBF\x20\xEB\x43\xA1\x88\x00\xF4\xFF\x0A\xFD\x82\xFF\x10\x12\x07\x19\x2B\x95\xFF\xC8\xDA\x78\x63\x10\x11\xED\x6B\x24\xCD\xD5\x73\xF9\x77\xA1\x1E\x79\x48\x11", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x99\xDE\xF8\x36\x14\x6B\xC9\xB1\xB4\xD2\x28\x31", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8}, // secp256r1 aka prime256r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 32}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 32}, { (unsigned char *) "\x5A\xC6\x35\xD8\xAA\x3A\x93\xE7\xB3\xEB\xBD\x55\x76\x98\x86\xBC\x65\x1D\x06\xB0\xCC\x53\xB0\xF6\x3B\xCE\x3C\x3E\x27\xD2\x60\x4B", 32}, { (unsigned char *) "\x04\x6B\x17\xD1\xF2\xE1\x2C\x42\x47\xF8\xBC\xE6\xE5\x63\xA4\x40\xF2\x77\x03\x7D\x81\x2D\xEB\x33\xA0\xF4\xA1\x39\x45\xD8\x98\xC2\x96\x4F\xE3\x42\xE2\xFE\x1A\x7F\x9B\x8E\xE7\xEB\x4A\x7C\x0F\x9E\x16\x2B\xCE\x33\x57\x6B\x31\x5E\xCE\xCB\xB6\x40\x68\x37\xBF\x51\xF5", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBC\xE6\xFA\xAD\xA7\x17\x9E\x84\xF3\xB9\xCA\xC2\xFC\x63\x25\x51", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x03", 9}, // brainpoolP192r1 { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x30\x93\xD1\x8D\xB7\x8F\xCE\x47\x6D\xE1\xA8\x62\x97", 24}, { (unsigned char *) "\x6A\x91\x17\x40\x76\xB1\xE0\xE1\x9C\x39\xC0\x31\xFE\x86\x85\xC1\xCA\xE0\x40\xE5\xC6\x9A\x28\xEF", 24}, { (unsigned char *) "\x46\x9A\x28\xEF\x7C\x28\xCC\xA3\xDC\x72\x1D\x04\x4F\x44\x96\xBC\xCA\x7E\xF4\x14\x6F\xBF\x25\xC9", 24}, { (unsigned char *) "\x04\xC0\xA0\x64\x7E\xAA\xB6\xA4\x87\x53\xB0\x33\xC5\x6C\xB0\xF0\x90\x0A\x2F\x5C\x48\x53\x37\x5F\xD6\x14\xB6\x90\x86\x6A\xBD\x5B\xB8\x8B\x5F\x48\x28\xC1\x49\x00\x02\xE6\x77\x3F\xA2\xFA\x29\x9B\x8F", 49}, { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x2F\x9E\x9E\x91\x6B\x5B\xE8\xF1\x02\x9A\xC4\xAC\xC1", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x05", 9}, // brainpoolP224r1 { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF", 28}, { (unsigned char *) "\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA\xD2\x9F\x43", 28}, { (unsigned char *) "\x25\x80\xF6\x3C\xCF\xE4\x41\x38\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66\xDB\xB3\x72\x38\x6C\x40\x0B", 28}, { (unsigned char *) "\x04\x0D\x90\x29\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02\xCD", 57}, { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD0\xFB\x98\xD1\x16\xBC\x4B\x6D\xDE\xBC\xA3\xA5\xA7\x93\x9F", 28}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x07", 9}, // brainpoolP256r1 { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x72\x6E\x3B\xF6\x23\xD5\x26\x20\x28\x20\x13\x48\x1D\x1F\x6E\x53\x77", 32}, { (unsigned char *) "\x7D\x5A\x09\x75\xFC\x2C\x30\x57\xEE\xF6\x75\x30\x41\x7A\xFF\xE7\xFB\x80\x55\xC1\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9", 32}, { (unsigned char *) "\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9\xBB\xD7\x7C\xBF\x95\x84\x16\x29\x5C\xF7\xE1\xCE\x6B\xCC\xDC\x18\xFF\x8C\x07\xB6", 32}, { (unsigned char *) "\x04\x8B\xD2\xAE\xB9\xCB\x7E\x57\xCB\x2C\x4B\x48\x2F\xFC\x81\xB7\xAF\xB9\xDE\x27\xE1\xE3\xBD\x23\xC2\x3A\x44\x53\xBD\x9A\xCE\x32\x62\x54\x7E\xF8\x35\xC3\xDA\xC4\xFD\x97\xF8\x46\x1A\x14\x61\x1D\xC9\xC2\x77\x45\x13\x2D\xED\x8E\x54\x5C\x1D\x54\xC7\x2F\x04\x69\x97", 65}, { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x71\x8C\x39\x7A\xA3\xB5\x61\xA6\xF7\x90\x1E\x0E\x82\x97\x48\x56\xA7", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x09", 9}, // brainpoolP320r1 { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA6\xF6\xF4\x0D\xEF\x4F\x92\xB9\xEC\x78\x93\xEC\x28\xFC\xD4\x12\xB1\xF1\xB3\x2E\x27", 40}, { (unsigned char *) "\x3E\xE3\x0B\x56\x8F\xBA\xB0\xF8\x83\xCC\xEB\xD4\x6D\x3F\x3B\xB8\xA2\xA7\x35\x13\xF5\xEB\x79\xDA\x66\x19\x0E\xB0\x85\xFF\xA9\xF4\x92\xF3\x75\xA9\x7D\x86\x0E\xB4", 40}, { (unsigned char *) "\x52\x08\x83\x94\x9D\xFD\xBC\x42\xD3\xAD\x19\x86\x40\x68\x8A\x6F\xE1\x3F\x41\x34\x95\x54\xB4\x9A\xCC\x31\xDC\xCD\x88\x45\x39\x81\x6F\x5E\xB4\xAC\x8F\xB1\xF1\xA6", 40}, { (unsigned char *) "\x04\x43\xBD\x7E\x9A\xFB\x53\xD8\xB8\x52\x89\xBC\xC4\x8E\xE5\xBF\xE6\xF2\x01\x37\xD1\x0A\x08\x7E\xB6\xE7\x87\x1E\x2A\x10\xA5\x99\xC7\x10\xAF\x8D\x0D\x39\xE2\x06\x11\x14\xFD\xD0\x55\x45\xEC\x1C\xC8\xAB\x40\x93\x24\x7F\x77\x27\x5E\x07\x43\xFF\xED\x11\x71\x82\xEA\xA9\xC7\x78\x77\xAA\xAC\x6A\xC7\xD3\x52\x45\xD1\x69\x2E\x8E\xE1", 81}, { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA5\xB6\x8F\x12\xA3\x2D\x48\x2E\xC7\xEE\x86\x58\xE9\x86\x91\x55\x5B\x44\xC5\x93\x11", 40}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x1F", 5}, // secp192k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xEE\x37", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03", 24}, { (unsigned char *) "\x04\xDB\x4F\xF1\x0E\xC0\x57\xE9\xAE\x26\xB0\x7D\x02\x80\xB7\xF4\x34\x1D\xA5\xD1\xB1\xEA\xE0\x6C\x7D\x9B\x2F\x2F\x6D\x9C\x56\x28\xA7\x84\x41\x63\xD0\x15\xBE\x86\x34\x40\x82\xAA\x88\xD9\x5E\x2F\x9D", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\x26\xF2\xFC\x17\x0F\x69\x46\x6A\x74\xDE\xFD\x8D", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x0A", 5}, // secp256k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFC\x2F", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07", 32}, { (unsigned char *) "\x04\x79\xBE\x66\x7E\xF9\xDC\xBB\xAC\x55\xA0\x62\x95\xCE\x87\x0B\x07\x02\x9B\xFC\xDB\x2D\xCE\x28\xD9\x59\xF2\x81\x5B\x16\xF8\x17\x98\x48\x3A\xDA\x77\x26\xA3\xC4\x65\x5D\xA4\xFB\xFC\x0E\x11\x08\xA8\xFD\x17\xB4\x48\xA6\x85\x54\x19\x9C\x47\xD0\x8F\xFB\x10\xD4\xB8", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B\xBF\xD2\x5E\x8C\xD0\x36\x41\x41", 32}, { (unsigned char *) "\x01", 1} }, { { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0} } }; #define C_ASN1_CVC_PUBKEY_SIZE 10 static const struct sc_asn1_entry c_asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE] = { { "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL }, { "primeOrModulus", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientAorExponent", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 2, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientB", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 3, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "basePointG", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 4, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "order", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 5, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "cofactor", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 7, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "modulusSize", SC_ASN1_INTEGER, SC_ASN1_UNI | SC_ASN1_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_BODY_SIZE 5 static const struct sc_asn1_entry c_asn1_cvc_body[C_ASN1_CVC_BODY_SIZE] = { { "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL }, { "certificationAuthorityReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL }, { "certificateHolderReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVCERT_SIZE 3 static const struct sc_asn1_entry c_asn1_cvcert[C_ASN1_CVCERT_SIZE] = { { "certificateBody", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F4E, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_SIZE 2 static const struct sc_asn1_entry c_asn1_cvc[C_ASN1_CVC_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_AUTHREQ_SIZE 4 static const struct sc_asn1_entry c_asn1_authreq[C_ASN1_AUTHREQ_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { "outerCAR", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_REQ_SIZE 2 static const struct sc_asn1_entry c_asn1_req[C_ASN1_REQ_SIZE] = { { "authenticatedrequest", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 7, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static int read_file(sc_pkcs15_card_t * p15card, u8 fid[2], u8 *efbin, size_t *len, int optional) { sc_path_t path; int r; sc_path_set(&path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); /* look this up with our AID */ path.aid = sc_hsm_aid; /* we don't have a pre-known size of the file */ path.count = -1; if (!p15card->opts.use_file_cache || !efbin || SC_SUCCESS != sc_pkcs15_read_cached_file(p15card, &path, &efbin, len)) { /* avoid re-selection of SC-HSM */ path.aid.len = 0; r = sc_select_file(p15card->card, &path, NULL); if (r < 0) { sc_log(p15card->card->ctx, "Could not select EF"); } else { r = sc_read_binary(p15card->card, 0, efbin, *len, 0); } if (r < 0) { sc_log(p15card->card->ctx, "Could not read EF"); if (!optional) { return r; } /* optional files are saved as empty files to avoid card * transactions. Parsing the file's data will reveal that they were * missing. */ *len = 0; } else { *len = r; } if (p15card->opts.use_file_cache) { /* save this with our AID */ path.aid = sc_hsm_aid; sc_pkcs15_cache_file(p15card, &path, efbin, *len); } } return SC_SUCCESS; } /* * Decode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_decode_cvc(sc_pkcs15_card_t * p15card, const u8 ** buf, size_t *buflen, sc_cvc_t *cvc) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_req[C_ASN1_REQ_SIZE]; struct sc_asn1_entry asn1_authreq[C_ASN1_AUTHREQ_SIZE]; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; unsigned int cla,tag; size_t taglen; size_t lenchr = sizeof(cvc->chr); size_t lencar = sizeof(cvc->car); size_t lenoutercar = sizeof(cvc->outer_car); const u8 *tbuf; int r; memset(cvc, 0, sizeof(*cvc)); sc_copy_asn1_entry(c_asn1_req, asn1_req); sc_copy_asn1_entry(c_asn1_authreq, asn1_authreq); sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 1, &cvc->primeOrModulus, &cvc->primeOrModuluslen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 2, &cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 3, &cvc->coefficientB, &cvc->coefficientBlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 4, &cvc->basePointG, &cvc->basePointGlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 5, &cvc->order, &cvc->orderlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 6, &cvc->publicPoint, &cvc->publicPointlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 7, &cvc->cofactor, &cvc->cofactorlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 0); sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 0); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 0); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 0); sc_format_asn1_entry(asn1_cvcert + 1, &cvc->signature, &cvc->signatureLen, 0); sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq + 1, &cvc->outer_car, &lenoutercar, 0); sc_format_asn1_entry(asn1_authreq + 2, &cvc->outerSignature, &cvc->outerSignatureLen, 0); sc_format_asn1_entry(asn1_req , &asn1_authreq, NULL, 0); /* sc_asn1_print_tags(*buf, *buflen); */ tbuf = *buf; r = sc_asn1_read_tag(&tbuf, *buflen, &cla, &tag, &taglen); LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); /* Determine if we deal with an authenticated request, plain request or certificate */ if ((cla == (SC_ASN1_TAG_APPLICATION|SC_ASN1_TAG_CONSTRUCTED)) && (tag == 7)) { r = sc_asn1_decode(card->ctx, asn1_req, *buf, *buflen, buf, buflen); } else { r = sc_asn1_decode(card->ctx, asn1_cvc, *buf, *buflen, buf, buflen); } LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Encode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_encode_cvc(sc_pkcs15_card_t * p15card, sc_cvc_t *cvc, u8 ** buf, size_t *buflen) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; size_t lenchr; size_t lencar; int r; sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); asn1_cvc_pubkey[1].flags = SC_ASN1_OPTIONAL; asn1_cvcert[1].flags = SC_ASN1_OPTIONAL; sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 1); if (cvc->primeOrModulus && (cvc->primeOrModuluslen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 1, cvc->primeOrModulus, &cvc->primeOrModuluslen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 2, cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 1); if (cvc->coefficientB && (cvc->coefficientBlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 3, cvc->coefficientB, &cvc->coefficientBlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 4, cvc->basePointG, &cvc->basePointGlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 5, cvc->order, &cvc->orderlen, 1); if (cvc->publicPoint && (cvc->publicPointlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 6, cvc->publicPoint, &cvc->publicPointlen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 7, cvc->cofactor, &cvc->cofactorlen, 1); } if (cvc->modulusSize > 0) { sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 1); } sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 1); lencar = strnlen(cvc->car, sizeof cvc->car); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 1); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 1); lenchr = strnlen(cvc->chr, sizeof cvc->chr); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 1); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 1); if (cvc->signature && (cvc->signatureLen > 0)) { sc_format_asn1_entry(asn1_cvcert + 1, cvc->signature, &cvc->signatureLen, 1); } sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 1); r = sc_asn1_encode(card->ctx, asn1_cvc, buf, buflen); LOG_TEST_RET(card->ctx, r, "Could not encode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_get_curve(struct ec_curve **curve, u8 *oid, size_t oidlen) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].oid.len == oidlen) && !memcmp(curves[i].oid.value, oid, oidlen)) { *curve = &curves[i]; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } int sc_pkcs15emu_sc_hsm_get_curve_oid(sc_cvc_t *cvc, const struct sc_lv_data **oid) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].prime.len == cvc->primeOrModuluslen) && !memcmp(curves[i].prime.value, cvc->primeOrModulus, cvc->primeOrModuluslen)) { *oid = &curves[i].oid; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } static int sc_pkcs15emu_sc_hsm_get_rsa_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { pubkey->algorithm = SC_ALGORITHM_RSA; pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) return SC_ERROR_OUT_OF_MEMORY; pubkey->alg_id->algorithm = SC_ALGORITHM_RSA; pubkey->u.rsa.modulus.len = cvc->primeOrModuluslen; pubkey->u.rsa.modulus.data = malloc(pubkey->u.rsa.modulus.len); pubkey->u.rsa.exponent.len = cvc->coefficientAorExponentlen; pubkey->u.rsa.exponent.data = malloc(pubkey->u.rsa.exponent.len); if (!pubkey->u.rsa.modulus.data || !pubkey->u.rsa.exponent.data) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.rsa.exponent.data, cvc->coefficientAorExponent, pubkey->u.rsa.exponent.len); memcpy(pubkey->u.rsa.modulus.data, cvc->primeOrModulus, pubkey->u.rsa.modulus.len); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_get_ec_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { struct sc_ec_parameters *ecp; const struct sc_lv_data *oid; int r; pubkey->algorithm = SC_ALGORITHM_EC; r = sc_pkcs15emu_sc_hsm_get_curve_oid(cvc, &oid); if (r != SC_SUCCESS) return r; ecp = calloc(1, sizeof(struct sc_ec_parameters)); if (!ecp) return SC_ERROR_OUT_OF_MEMORY; ecp->der.len = oid->len + 2; ecp->der.value = calloc(ecp->der.len, 1); if (!ecp->der.value) { free(ecp); return SC_ERROR_OUT_OF_MEMORY; } *(ecp->der.value + 0) = 0x06; *(ecp->der.value + 1) = (u8)oid->len; memcpy(ecp->der.value + 2, oid->value, oid->len); ecp->type = 1; // Named curve pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) { free(ecp->der.value); free(ecp); return SC_ERROR_OUT_OF_MEMORY; } pubkey->alg_id->algorithm = SC_ALGORITHM_EC; pubkey->alg_id->params = ecp; pubkey->u.ec.ecpointQ.value = malloc(cvc->publicPointlen); if (!pubkey->u.ec.ecpointQ.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.ecpointQ.value, cvc->publicPoint, cvc->publicPointlen); pubkey->u.ec.ecpointQ.len = cvc->publicPointlen; pubkey->u.ec.params.der.value = malloc(ecp->der.len); if (!pubkey->u.ec.params.der.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.params.der.value, ecp->der.value, ecp->der.len); pubkey->u.ec.params.der.len = ecp->der.len; /* FIXME: check return value? */ sc_pkcs15_fix_ec_parameters(ctx, &pubkey->u.ec.params); return SC_SUCCESS; } int sc_pkcs15emu_sc_hsm_get_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { if (cvc->publicPoint && cvc->publicPointlen) { return sc_pkcs15emu_sc_hsm_get_ec_public_key(ctx, cvc, pubkey); } else { return sc_pkcs15emu_sc_hsm_get_rsa_public_key(ctx, cvc, pubkey); } } void sc_pkcs15emu_sc_hsm_free_cvc(sc_cvc_t *cvc) { if (cvc->signature) { free(cvc->signature); cvc->signature = NULL; } if (cvc->primeOrModulus) { free(cvc->primeOrModulus); cvc->primeOrModulus = NULL; } if (cvc->coefficientAorExponent) { free(cvc->coefficientAorExponent); cvc->coefficientAorExponent = NULL; } if (cvc->coefficientB) { free(cvc->coefficientB); cvc->coefficientB = NULL; } if (cvc->basePointG) { free(cvc->basePointG); cvc->basePointG = NULL; } if (cvc->order) { free(cvc->order); cvc->order = NULL; } if (cvc->publicPoint) { free(cvc->publicPoint); cvc->publicPoint = NULL; } if (cvc->cofactor) { free(cvc->cofactor); cvc->cofactor = NULL; } } static int sc_pkcs15emu_sc_hsm_add_pubkey(sc_pkcs15_card_t *p15card, u8 *efbin, size_t len, sc_pkcs15_prkey_info_t *key_info, char *label) { struct sc_context *ctx = p15card->card->ctx; sc_card_t *card = p15card->card; sc_pkcs15_pubkey_info_t pubkey_info; sc_pkcs15_object_t pubkey_obj; struct sc_pkcs15_pubkey pubkey; sc_cvc_t cvc; u8 *cvcpo; int r; cvcpo = efbin; memset(&cvc, 0, sizeof(cvc)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&cvcpo, &len, &cvc); LOG_TEST_RET(ctx, r, "Could decode certificate signing request"); memset(&pubkey, 0, sizeof(pubkey)); r = sc_pkcs15emu_sc_hsm_get_public_key(ctx, &cvc, &pubkey); LOG_TEST_RET(card->ctx, r, "Could not extract public key"); memset(&pubkey_info, 0, sizeof(pubkey_info)); memset(&pubkey_obj, 0, sizeof(pubkey_obj)); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_obj.content.value, &pubkey_obj.content.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_info.direct.raw.value, &pubkey_info.direct.raw.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey_as_spki(ctx, &pubkey, &pubkey_info.direct.spki.value, &pubkey_info.direct.spki.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); pubkey_info.id = key_info->id; strlcpy(pubkey_obj.label, label, sizeof(pubkey_obj.label)); if (pubkey.algorithm == SC_ALGORITHM_RSA) { pubkey_info.modulus_length = pubkey.u.rsa.modulus.len << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_VERIFY|SC_PKCS15_PRKEY_USAGE_WRAP; r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info); } else { /* TODO fix if support of non multiple of 8 curves are added */ pubkey_info.field_length = cvc.primeOrModuluslen << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_VERIFY; r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info); } LOG_TEST_RET(ctx, r, "Could not add public key"); sc_pkcs15emu_sc_hsm_free_cvc(&cvc); sc_pkcs15_erase_pubkey(&pubkey); return SC_SUCCESS; } /* * Add a key and the key description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t cert_info; sc_pkcs15_object_t cert_obj; struct sc_pkcs15_object prkd; sc_pkcs15_prkey_info_t *key_info; u8 fid[2]; /* enough to hold a complete certificate */ u8 efbin[4096]; u8 *ptr; size_t len; int r; fid[0] = PRKD_PREFIX; fid[1] = keyid; /* Try to select a related EF containing the PKCS#15 description of the key */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); ptr = efbin; memset(&prkd, 0, sizeof(prkd)); r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); /* All keys require user PIN authentication */ prkd.auth_id.len = 1; prkd.auth_id.value[0] = 1; /* * Set private key flag as all keys are private anyway */ prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE; key_info = (sc_pkcs15_prkey_info_t *)prkd.data; key_info->key_reference = keyid; key_info->path.aid.len = 0; if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) { r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info); } else { r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info); } LOG_TEST_RET(card->ctx, r, "Could not add private key to framework"); /* Check if we also have a certificate for the private key */ fid[0] = EE_CERTIFICATE_PREFIX; len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 0); LOG_TEST_RET(card->ctx, r, "Could not read EF"); if (efbin[0] == 0x67) { /* Decode CSR and create public key object */ sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label); free(key_info); return SC_SUCCESS; /* Ignore any errors */ } if (efbin[0] != 0x30) { free(key_info); return SC_SUCCESS; } memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id = key_info->id; sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); cert_info.path.count = -1; if (p15card->opts.use_file_cache) { /* look this up with our AID, which should already be cached from the * call to `read_file`. This may have the side effect that OpenSC's * caching layer re-selects our applet *if the cached file cannot be * found/used* and we may loose the authentication status. We assume * that caching works perfectly without this side effect. */ cert_info.path.aid = sc_hsm_aid; } strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); free(key_info); LOG_TEST_RET(card->ctx, r, "Could not add certificate"); return SC_SUCCESS; } /* * Add a data object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_dcod(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_data_info_t *data_info; sc_pkcs15_object_t data_obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = DCOD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&data_obj, 0, sizeof(data_obj)); r = sc_pkcs15_decode_dodf_entry(p15card, &data_obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Could not decode optional EF.DCOD"); data_info = (sc_pkcs15_data_info_t *)data_obj.data; r = sc_pkcs15emu_add_data_object(p15card, &data_obj, data_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } /* * Add a unrelated certificate object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_cd(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t *cert_info; sc_pkcs15_object_t obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = CD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&obj, 0, sizeof(obj)); r = sc_pkcs15_decode_cdf_entry(p15card, &obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.CDOD"); cert_info = (sc_pkcs15_cert_info_t *)obj.data; r = sc_pkcs15emu_add_x509_cert(p15card, &obj, cert_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_read_tokeninfo (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; int r; u8 efbin[512]; size_t len; LOG_FUNC_CALLED(card->ctx); /* Read token info */ len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x03", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); r = sc_pkcs15_parse_tokeninfo(card->ctx, p15card->tokeninfo, efbin, len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Initialize PKCS#15 emulation with user PIN, private keys, certificate and data objects * */ static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data; sc_file_t *file = NULL; sc_path_t path; u8 filelist[MAX_EXT_APDU_LENGTH]; int filelistlength; int r, i; sc_cvc_t devcert; struct sc_app_info *appinfo; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; struct sc_pin_cmd_data pindata; u8 efbin[1024]; u8 *ptr; size_t len; LOG_FUNC_CALLED(card->ctx); appinfo = calloc(1, sizeof(struct sc_app_info)); if (appinfo == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->aid = sc_hsm_aid; appinfo->ddo.aid = sc_hsm_aid; p15card->app = appinfo; sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0); r = sc_select_file(card, &path, &file); LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application"); p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */ p15card->card->version.hw_minor = 13; if (file && file->prop_attr && file->prop_attr_len >= 2) { p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2]; p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1]; } sc_file_free(file); /* Read device certificate to determine serial number */ if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) { ptr = priv->EF_C_DevAut; len = priv->EF_C_DevAut_len; } else { len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut"); if (len > 0) { /* save EF_C_DevAut for further use */ ptr = realloc(priv->EF_C_DevAut, len); if (ptr) { memcpy(ptr, efbin, len); priv->EF_C_DevAut = ptr; priv->EF_C_DevAut_len = len; } } ptr = efbin; } memset(&devcert, 0 ,sizeof(devcert)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert); LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut"); sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card); if (p15card->tokeninfo->label == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->label = strdup("GoID"); } else { p15card->tokeninfo->label = strdup("SmartCard-HSM"); } if (p15card->tokeninfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) { free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = NULL; } if (p15card->tokeninfo->manufacturer_id == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH"); } else { p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de"); } if (p15card->tokeninfo->manufacturer_id == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->label = strdup(p15card->tokeninfo->label); if (appinfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */ assert(len >= 8); len -= 5; p15card->tokeninfo->serial_number = calloc(len + 1, 1); if (p15card->tokeninfo->serial_number == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(p15card->tokeninfo->serial_number, devcert.chr, len); *(p15card->tokeninfo->serial_number + len) = 0; sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number); sc_pkcs15emu_sc_hsm_free_cvc(&devcert); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 1; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x81; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = 6; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 15; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 3; pin_info.max_tries = 3; pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 2; strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 2; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x88; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD; pin_info.attrs.pin.min_length = 16; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 16; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 15; pin_info.max_tries = 15; strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); if (card->type == SC_CARD_TYPE_SC_HSM_SOC || card->type == SC_CARD_TYPE_SC_HSM_GOID) { /* SC-HSM of this type always has a PIN-Pad */ r = SC_SUCCESS; } else { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x85; r = sc_pin_cmd(card, &pindata, NULL); } if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x86; r = sc_pin_cmd(card, &pindata, NULL); } if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS)) card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH; filelistlength = sc_list_files(card, filelist, sizeof(filelist)); LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier"); for (i = 0; i < filelistlength; i += 2) { switch(filelist[i]) { case KEY_PREFIX: r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]); break; case DCOD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]); break; case CD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]); break; } if (r != SC_SUCCESS) { sc_log(card->ctx, "Error %d adding elements to framework", r); } } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) { return sc_pkcs15emu_sc_hsm_init(p15card); } else { if (p15card->card->type != SC_CARD_TYPE_SC_HSM && p15card->card->type != SC_CARD_TYPE_SC_HSM_SOC && p15card->card->type != SC_CARD_TYPE_SC_HSM_GOID) { return SC_ERROR_WRONG_CARD; } return sc_pkcs15emu_sc_hsm_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-119/c/good_340_6
crossvul-cpp_data_good_2483_2
/* * Instruction-patching support. * * Copyright (C) 2003 Hewlett-Packard Co * David Mosberger-Tang <davidm@hpl.hp.com> */ #include <linux/init.h> #include <linux/string.h> #include <asm/patch.h> #include <asm/processor.h> #include <asm/sections.h> #include <asm/system.h> #include <asm/unistd.h> /* * This was adapted from code written by Tony Luck: * * The 64-bit value in a "movl reg=value" is scattered between the two words of the bundle * like this: * * 6 6 5 4 3 2 1 * 3210987654321098765432109876543210987654321098765432109876543210 * ABBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCDEEEEEFFFFFFFFFGGGGGGG * * CCCCCCCCCCCCCCCCCCxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx * xxxxAFFFFFFFFFEEEEEDxGGGGGGGxxxxxxxxxxxxxBBBBBBBBBBBBBBBBBBBBBBB */ static u64 get_imm64 (u64 insn_addr) { u64 *p = (u64 *) (insn_addr & -16); /* mask out slot number */ return ( (p[1] & 0x0800000000000000UL) << 4) | /*A*/ ((p[1] & 0x00000000007fffffUL) << 40) | /*B*/ ((p[0] & 0xffffc00000000000UL) >> 24) | /*C*/ ((p[1] & 0x0000100000000000UL) >> 23) | /*D*/ ((p[1] & 0x0003e00000000000UL) >> 29) | /*E*/ ((p[1] & 0x07fc000000000000UL) >> 43) | /*F*/ ((p[1] & 0x000007f000000000UL) >> 36); /*G*/ } /* Patch instruction with "val" where "mask" has 1 bits. */ void ia64_patch (u64 insn_addr, u64 mask, u64 val) { u64 m0, m1, v0, v1, b0, b1, *b = (u64 *) (insn_addr & -16); # define insn_mask ((1UL << 41) - 1) unsigned long shift; b0 = b[0]; b1 = b[1]; shift = 5 + 41 * (insn_addr % 16); /* 5 bits of template, then 3 x 41-bit instructions */ if (shift >= 64) { m1 = mask << (shift - 64); v1 = val << (shift - 64); } else { m0 = mask << shift; m1 = mask >> (64 - shift); v0 = val << shift; v1 = val >> (64 - shift); b[0] = (b0 & ~m0) | (v0 & m0); } b[1] = (b1 & ~m1) | (v1 & m1); } void ia64_patch_imm64 (u64 insn_addr, u64 val) { /* The assembler may generate offset pointing to either slot 1 or slot 2 for a long (2-slot) instruction, occupying slots 1 and 2. */ insn_addr &= -16UL; ia64_patch(insn_addr + 2, 0x01fffefe000UL, ( ((val & 0x8000000000000000UL) >> 27) /* bit 63 -> 36 */ | ((val & 0x0000000000200000UL) << 0) /* bit 21 -> 21 */ | ((val & 0x00000000001f0000UL) << 6) /* bit 16 -> 22 */ | ((val & 0x000000000000ff80UL) << 20) /* bit 7 -> 27 */ | ((val & 0x000000000000007fUL) << 13) /* bit 0 -> 13 */)); ia64_patch(insn_addr + 1, 0x1ffffffffffUL, val >> 22); } void ia64_patch_imm60 (u64 insn_addr, u64 val) { /* The assembler may generate offset pointing to either slot 1 or slot 2 for a long (2-slot) instruction, occupying slots 1 and 2. */ insn_addr &= -16UL; ia64_patch(insn_addr + 2, 0x011ffffe000UL, ( ((val & 0x0800000000000000UL) >> 23) /* bit 59 -> 36 */ | ((val & 0x00000000000fffffUL) << 13) /* bit 0 -> 13 */)); ia64_patch(insn_addr + 1, 0x1fffffffffcUL, val >> 18); } /* * We need sometimes to load the physical address of a kernel * object. Often we can convert the virtual address to physical * at execution time, but sometimes (either for performance reasons * or during error recovery) we cannot to this. Patch the marked * bundles to load the physical address. */ void __init ia64_patch_vtop (unsigned long start, unsigned long end) { s32 *offp = (s32 *) start; u64 ip; while (offp < (s32 *) end) { ip = (u64) offp + *offp; /* replace virtual address with corresponding physical address: */ ia64_patch_imm64(ip, ia64_tpa(get_imm64(ip))); ia64_fc((void *) ip); ++offp; } ia64_sync_i(); ia64_srlz_i(); } /* * Disable the RSE workaround by turning the conditional branch * that we tagged in each place the workaround was used into an * unconditional branch. */ void __init ia64_patch_rse (unsigned long start, unsigned long end) { s32 *offp = (s32 *) start; u64 ip, *b; while (offp < (s32 *) end) { ip = (u64) offp + *offp; b = (u64 *)(ip & -16); b[1] &= ~0xf800000L; ia64_fc((void *) ip); ++offp; } ia64_sync_i(); ia64_srlz_i(); } void __init ia64_patch_mckinley_e9 (unsigned long start, unsigned long end) { static int first_time = 1; int need_workaround; s32 *offp = (s32 *) start; u64 *wp; need_workaround = (local_cpu_data->family == 0x1f && local_cpu_data->model == 0); if (first_time) { first_time = 0; if (need_workaround) printk(KERN_INFO "Leaving McKinley Errata 9 workaround enabled\n"); } if (need_workaround) return; while (offp < (s32 *) end) { wp = (u64 *) ia64_imva((char *) offp + *offp); wp[0] = 0x0000000100000011UL; /* nop.m 0; nop.i 0; br.ret.sptk.many b6 */ wp[1] = 0x0084006880000200UL; wp[2] = 0x0000000100000000UL; /* nop.m 0; nop.i 0; nop.i 0 */ wp[3] = 0x0004000000000200UL; ia64_fc(wp); ia64_fc(wp + 2); ++offp; } ia64_sync_i(); ia64_srlz_i(); } static void __init patch_fsyscall_table (unsigned long start, unsigned long end) { extern unsigned long fsyscall_table[NR_syscalls]; s32 *offp = (s32 *) start; u64 ip; while (offp < (s32 *) end) { ip = (u64) ia64_imva((char *) offp + *offp); ia64_patch_imm64(ip, (u64) fsyscall_table); ia64_fc((void *) ip); ++offp; } ia64_sync_i(); ia64_srlz_i(); } static void __init patch_brl_fsys_bubble_down (unsigned long start, unsigned long end) { extern char fsys_bubble_down[]; s32 *offp = (s32 *) start; u64 ip; while (offp < (s32 *) end) { ip = (u64) offp + *offp; ia64_patch_imm60((u64) ia64_imva((void *) ip), (u64) (fsys_bubble_down - (ip & -16)) / 16); ia64_fc((void *) ip); ++offp; } ia64_sync_i(); ia64_srlz_i(); } void __init ia64_patch_gate (void) { # define START(name) ((unsigned long) __start_gate_##name##_patchlist) # define END(name) ((unsigned long)__end_gate_##name##_patchlist) patch_fsyscall_table(START(fsyscall), END(fsyscall)); patch_brl_fsys_bubble_down(START(brl_fsys_bubble_down), END(brl_fsys_bubble_down)); ia64_patch_vtop(START(vtop), END(vtop)); ia64_patch_mckinley_e9(START(mckinley_e9), END(mckinley_e9)); } void ia64_patch_phys_stack_reg(unsigned long val) { s32 * offp = (s32 *) __start___phys_stack_reg_patchlist; s32 * end = (s32 *) __end___phys_stack_reg_patchlist; u64 ip, mask, imm; /* see instruction format A4: adds r1 = imm13, r3 */ mask = (0x3fUL << 27) | (0x7f << 13); imm = (((val >> 7) & 0x3f) << 27) | (val & 0x7f) << 13; while (offp < end) { ip = (u64) offp + *offp; ia64_patch(ip, mask, imm); ia64_fc(ip); ++offp; } ia64_sync_i(); ia64_srlz_i(); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2483_2
crossvul-cpp_data_good_507_2
/****************************************************************************** ** Copyright (c) 2014-2018, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its ** ** contributors may be used to endorse or promote products derived ** ** from this software without specific prior written permission. ** ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ /* Alexander Heinecke (Intel Corp.) ******************************************************************************/ #include <libxsmm.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <sys/time.h> #define REPS 100 #define REALTYPE double static double sec(struct timeval start, struct timeval end) { return ((double)(((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)))) / 1.0e6; } int my_csr_reader( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, REALTYPE** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return -1; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return -1; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) && 0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return -1; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return -1; } /* now we read the actual content */ } else { unsigned int l_row, l_column; REALTYPE l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return -1; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return -1; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } return 0; } int main(int argc, char* argv[]) { char* l_csr_file; REALTYPE* l_a_sp; unsigned int* l_rowptr; unsigned int* l_colidx; unsigned int l_rowcount, l_colcount, l_elements; REALTYPE* l_a_dense; REALTYPE* l_b; REALTYPE* l_c_betaone; REALTYPE* l_c_betazero; REALTYPE* l_c_gold_betaone; REALTYPE* l_c_gold_betazero; REALTYPE* l_c_dense_betaone; REALTYPE* l_c_dense_betazero; REALTYPE l_max_error = 0.0; unsigned int l_m; unsigned int l_n; unsigned int l_k; unsigned int l_i; unsigned int l_j; unsigned int l_z; unsigned int l_elems; unsigned int l_reps; unsigned int l_n_block; struct timeval l_start, l_end; double l_total; double alpha = 1.0; double beta = 1.0; char trans = 'N'; libxsmm_dfsspmdm* gemm_op_betazero = NULL; libxsmm_dfsspmdm* gemm_op_betaone = NULL; if (argc != 4 ) { fprintf( stderr, "need csr-filename N reps!\n" ); exit(-1); } /* read sparse A */ l_csr_file = argv[1]; l_n = atoi(argv[2]); l_reps = atoi(argv[3]); if (my_csr_reader( l_csr_file, &l_rowptr, &l_colidx, &l_a_sp, &l_rowcount, &l_colcount, &l_elements ) != 0 ) { exit(-1); } l_m = l_rowcount; l_k = l_colcount; printf("CSR matrix data structure we just read:\n"); printf("rows: %u, columns: %u, elements: %u\n", l_rowcount, l_colcount, l_elements); /* allocate dense matrices */ l_a_dense = (REALTYPE*)_mm_malloc(l_k * l_m * sizeof(REALTYPE), 64); l_b = (REALTYPE*)_mm_malloc(l_k * l_n * sizeof(REALTYPE), 64); l_c_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_gold_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_gold_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_dense_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_dense_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); /* touch B */ for ( l_i = 0; l_i < l_k*l_n; l_i++) { l_b[l_i] = (REALTYPE)libxsmm_rand_f64(); } /* touch dense A */ for ( l_i = 0; l_i < l_k*l_m; l_i++) { l_a_dense[l_i] = (REALTYPE)0.0; } /* init dense A using sparse A */ for ( l_i = 0; l_i < l_m; l_i++ ) { l_elems = l_rowptr[l_i+1] - l_rowptr[l_i]; for ( l_z = 0; l_z < l_elems; l_z++ ) { l_a_dense[(l_i*l_k)+l_colidx[l_rowptr[l_i]+l_z]] = l_a_sp[l_rowptr[l_i]+l_z]; } } /* touch C */ for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_gold_betaone[l_i] = (REALTYPE)libxsmm_rand_f64(); } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_betaone[l_i] = l_c_gold_betaone[l_i]; } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_dense_betaone[l_i] = l_c_gold_betaone[l_i]; } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_betazero[l_i] = l_c_betaone[l_i]; } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_gold_betazero[l_i] = l_c_gold_betaone[l_i]; } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_dense_betazero[l_i] = l_c_dense_betaone[l_i]; } /* setting up fsspmdm */ l_n_block = 48; beta = 0.0; gemm_op_betazero = libxsmm_dfsspmdm_create( l_m, l_n_block, l_k, l_k, l_n, l_n, 1.0, beta, l_a_dense ); beta = 1.0; gemm_op_betaone = libxsmm_dfsspmdm_create( l_m, l_n_block, l_k, l_k, l_n, l_n, 1.0, beta, l_a_dense ); /* compute golden results */ printf("computing golden solution...\n"); for ( l_j = 0; l_j < l_n; l_j++ ) { for (l_i = 0; l_i < l_m; l_i++ ) { l_elems = l_rowptr[l_i+1] - l_rowptr[l_i]; l_c_gold_betazero[(l_n*l_i) + l_j] = 0.0; for (l_z = 0; l_z < l_elems; l_z++) { l_c_gold_betazero[(l_n*l_i) + l_j] += l_a_sp[l_rowptr[l_i]+l_z] * l_b[(l_n*l_colidx[l_rowptr[l_i]+l_z])+l_j]; } } } for ( l_j = 0; l_j < l_n; l_j++ ) { for (l_i = 0; l_i < l_m; l_i++ ) { l_elems = l_rowptr[l_i+1] - l_rowptr[l_i]; for (l_z = 0; l_z < l_elems; l_z++) { l_c_gold_betaone[(l_n*l_i) + l_j] += l_a_sp[l_rowptr[l_i]+l_z] * l_b[(l_n*l_colidx[l_rowptr[l_i]+l_z])+l_j]; } } } printf("...done!\n"); /* libxsmm generated code */ printf("computing libxsmm (A sparse) solution...\n"); #ifdef _OPENMP #pragma omp parallel for private(l_z) #endif for (l_z = 0; l_z < l_n; l_z+=l_n_block) { libxsmm_dfsspmdm_execute( gemm_op_betazero, l_b+l_z, l_c_betazero+l_z ); } #ifdef _OPENMP #pragma omp parallel for private(l_z) #endif for (l_z = 0; l_z < l_n; l_z+=l_n_block) { libxsmm_dfsspmdm_execute( gemm_op_betaone, l_b+l_z, l_c_betaone+l_z ); } printf("...done!\n"); /* BLAS code */ printf("computing BLAS (A dense) solution...\n"); beta = 0.0; dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betazero, &l_n ); beta = 1.0; dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betaone, &l_n ); printf("...done!\n"); /* check for errors */ l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_betazero[l_i]-l_c_gold_betazero[l_i]) > l_max_error ) { l_max_error = fabs(l_c_betazero[l_i]-l_c_gold_betazero[l_i]); } } printf("max error beta=0 (libxmm vs. gold): %f\n", l_max_error); l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_betaone[l_i]-l_c_gold_betaone[l_i]) > l_max_error ) { l_max_error = fabs(l_c_betaone[l_i]-l_c_gold_betaone[l_i]); } } printf("max error beta=1 (libxmm vs. gold): %f\n", l_max_error); l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_dense_betazero[l_i]-l_c_gold_betazero[l_i]) > l_max_error ) { l_max_error = fabs(l_c_dense_betazero[l_i]-l_c_gold_betazero[l_i]); } } printf("max error beta=0 (dense vs. gold): %f\n", l_max_error); l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_dense_betaone[l_i]-l_c_gold_betaone[l_i]) > l_max_error ) { l_max_error = fabs(l_c_dense_betaone[l_i]-l_c_gold_betaone[l_i]); } } printf("max error beta=1 (dense vs. gold): %f\n", l_max_error); /* Let's measure performance */ gettimeofday(&l_start, NULL); for ( l_j = 0; l_j < l_reps; l_j++ ) { #ifdef _OPENMP #pragma omp parallel for private(l_z) #endif for (l_z = 0; l_z < l_n; l_z+=l_n_block) { libxsmm_dfsspmdm_execute( gemm_op_betazero, l_b+l_z, l_c_betazero+l_z ); } } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f (sparse)\n", l_m, l_n, l_k, (2.0 * (double)l_elements * (double)l_n * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f (dense)\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); gettimeofday(&l_start, NULL); for ( l_j = 0; l_j < l_reps; l_j++ ) { #ifdef _OPENMP #pragma omp parallel for private(l_z) #endif for (l_z = 0; l_z < l_n; l_z+=l_n_block) { libxsmm_dfsspmdm_execute( gemm_op_betaone, l_b+l_z, l_c_betaone+l_z ); } } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f (sparse)\n", l_m, l_n, l_k, (2.0 * (double)l_elements * (double)l_n * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f (dense)\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); gettimeofday(&l_start, NULL); beta = 0.0; for ( l_j = 0; l_j < l_reps; l_j++ ) { dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betazero, &l_n ); } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); gettimeofday(&l_start, NULL); beta = 1.0; for ( l_j = 0; l_j < l_reps; l_j++ ) { dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betaone, &l_n ); } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); /* free */ libxsmm_dfsspmdm_destroy( gemm_op_betazero ); libxsmm_dfsspmdm_destroy( gemm_op_betaone ); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_507_2
crossvul-cpp_data_bad_525_3
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / Scene Management sub-project * * GPAC is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GPAC 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <gpac/scene_manager.h> #include <gpac/constants.h> #include <gpac/media_tools.h> #include <gpac/bifs.h> #include <gpac/xml.h> #include <gpac/internal/scenegraph_dev.h> #include <gpac/network.h> GF_EXPORT GF_SceneManager *gf_sm_new(GF_SceneGraph *graph) { GF_SceneManager *tmp; if (!graph) return NULL; GF_SAFEALLOC(tmp, GF_SceneManager); if (!tmp) return NULL; tmp->streams = gf_list_new(); tmp->scene_graph = graph; return tmp; } GF_EXPORT GF_StreamContext *gf_sm_stream_new(GF_SceneManager *ctx, u16 ES_ID, u8 streamType, u8 objectType) { u32 i; GF_StreamContext *tmp; i=0; while ((tmp = (GF_StreamContext*)gf_list_enum(ctx->streams, &i))) { /*we MUST use the same ST*/ if (tmp->streamType!=streamType) continue; /*if no ESID/OTI specified this is a base layer (default stream created by parsers) if ESID/OTI specified this is a stream already setup */ if ( tmp->ESID==ES_ID ) { //tmp->objectType = objectType; return tmp; } } GF_SAFEALLOC(tmp, GF_StreamContext); if (!tmp) return NULL; tmp->AUs = gf_list_new(); tmp->ESID = ES_ID; tmp->streamType = streamType; tmp->objectType = objectType ? objectType : 1; tmp->timeScale = 1000; gf_list_add(ctx->streams, tmp); return tmp; } GF_StreamContext *gf_sm_stream_find(GF_SceneManager *ctx, u16 ES_ID) { u32 i, count; if (!ES_ID) return NULL; count = gf_list_count(ctx->streams); for (i=0; i<count; i++) { GF_StreamContext *tmp = (GF_StreamContext *)gf_list_get(ctx->streams, i); if (tmp->ESID==ES_ID) return tmp; } return NULL; } GF_EXPORT GF_MuxInfo *gf_sm_get_mux_info(GF_ESD *src) { u32 i; GF_MuxInfo *mux; i=0; while ((mux = (GF_MuxInfo *)gf_list_enum(src->extensionDescriptors, &i))) { if (mux->tag == GF_ODF_MUXINFO_TAG) return mux; } return NULL; } static void gf_sm_au_del(GF_StreamContext *sc, GF_AUContext *au) { while (gf_list_count(au->commands)) { void *comptr = gf_list_last(au->commands); gf_list_rem_last(au->commands); switch (sc->streamType) { case GF_STREAM_OD: gf_odf_com_del((GF_ODCom**) & comptr); break; case GF_STREAM_SCENE: gf_sg_command_del((GF_Command *)comptr); break; } } gf_list_del(au->commands); gf_free(au); } static void gf_sm_reset_stream(GF_StreamContext *sc) { while (gf_list_count(sc->AUs)) { GF_AUContext *au = (GF_AUContext *)gf_list_last(sc->AUs); gf_list_rem_last(sc->AUs); gf_sm_au_del(sc, au); } } static void gf_sm_delete_stream(GF_StreamContext *sc) { gf_sm_reset_stream(sc); gf_list_del(sc->AUs); if (sc->name) gf_free(sc->name); if (sc->dec_cfg) gf_free(sc->dec_cfg); gf_free(sc); } GF_EXPORT void gf_sm_stream_del(GF_SceneManager *ctx, GF_StreamContext *sc) { if (gf_list_del_item(ctx->streams, sc)>=0) { gf_sm_delete_stream(sc); } } GF_EXPORT void gf_sm_del(GF_SceneManager *ctx) { u32 count; while ( (count = gf_list_count(ctx->streams)) ) { GF_StreamContext *sc = (GF_StreamContext *)gf_list_get(ctx->streams, count-1); gf_list_rem(ctx->streams, count-1); gf_sm_delete_stream(sc); } gf_list_del(ctx->streams); if (ctx->root_od) gf_odf_desc_del((GF_Descriptor *) ctx->root_od); gf_free(ctx); } GF_EXPORT void gf_sm_reset(GF_SceneManager *ctx) { GF_StreamContext *sc; u32 i=0; while ( (sc = gf_list_enum(ctx->streams, &i)) ) { gf_sm_reset_stream(sc); } if (ctx->root_od) gf_odf_desc_del((GF_Descriptor *) ctx->root_od); ctx->root_od = NULL; } GF_EXPORT GF_AUContext *gf_sm_stream_au_new(GF_StreamContext *stream, u64 timing, Double time_sec, Bool isRap) { u32 i; GF_AUContext *tmp; u64 tmp_timing; tmp_timing = timing ? timing : (u64) (time_sec*1000); if (stream->imp_exp_time >= tmp_timing) { /*look for existing AU*/ i=0; while ((tmp = (GF_AUContext *)gf_list_enum(stream->AUs, &i))) { if (timing && (tmp->timing==timing)) return tmp; else if (time_sec && (tmp->timing_sec == time_sec)) return tmp; else if (!time_sec && !timing && !tmp->timing && !tmp->timing_sec) return tmp; /*insert AU*/ else if ((time_sec && time_sec<tmp->timing_sec) || (timing && timing<tmp->timing)) { GF_SAFEALLOC(tmp, GF_AUContext); if (!tmp) return NULL; tmp->commands = gf_list_new(); if (isRap) tmp->flags = GF_SM_AU_RAP; tmp->timing = timing; tmp->timing_sec = time_sec; tmp->owner = stream; gf_list_insert(stream->AUs, tmp, i-1); return tmp; } } } GF_SAFEALLOC(tmp, GF_AUContext); if (!tmp) return NULL; tmp->commands = gf_list_new(); if (isRap) tmp->flags = GF_SM_AU_RAP; tmp->timing = timing; tmp->timing_sec = time_sec; tmp->owner = stream; if (stream->disable_aggregation) tmp->flags |= GF_SM_AU_NOT_AGGREGATED; gf_list_add(stream->AUs, tmp); stream->imp_exp_time = tmp_timing; return tmp; } static Bool node_in_commands_subtree(GF_Node *node, GF_List *commands) { #ifndef GPAC_DISABLE_VRML u32 i, j, count, nb_fields; count = gf_list_count(commands); for (i=0; i<count; i++) { GF_Command *com = gf_list_get(commands, i); if (com->tag>=GF_SG_LAST_BIFS_COMMAND) { GF_LOG(GF_LOG_ERROR, GF_LOG_SCENE, ("[Scene Manager] Command check for LASeR/DIMS not supported\n")); return 0; } if (com->tag==GF_SG_SCENE_REPLACE) { if (gf_node_parent_of(com->node, node)) return 1; continue; } nb_fields = gf_list_count(com->command_fields); for (j=0; j<nb_fields; j++) { GF_CommandField *field = gf_list_get(com->command_fields, j); switch (field->fieldType) { case GF_SG_VRML_SFNODE: if (field->new_node) { if (gf_node_parent_of(field->new_node, node)) return 1; } break; case GF_SG_VRML_MFNODE: if (field->field_ptr) { GF_ChildNodeItem *child; child = field->node_list; while (child) { if (gf_node_parent_of(child->node, node)) return 1; child = child->next; } } break; } } } #endif return 0; } static u32 store_or_aggregate(GF_StreamContext *sc, GF_Command *com, GF_List *commands, Bool *has_modif) { #ifndef GPAC_DISABLE_VRML u32 i, count, j, nb_fields; GF_CommandField *field, *check_field; /*if our command deals with a node inserted in the commands list, apply command list*/ if (node_in_commands_subtree(com->node, commands)) return 0; /*otherwise, check if we can substitute a previous command with this one*/ count = gf_list_count(commands); for (i=0; i<count; i++) { GF_Command *check = gf_list_get(commands, i); if (sc->streamType == GF_STREAM_SCENE) { Bool check_index=0; Bool original_is_index = 0; Bool apply; switch (com->tag) { case GF_SG_INDEXED_REPLACE: check_index=1; case GF_SG_MULTIPLE_INDEXED_REPLACE: case GF_SG_FIELD_REPLACE: case GF_SG_MULTIPLE_REPLACE: if (check->node != com->node) break; /*we may aggregate an indexed insertion and a replace one*/ if (check_index) { if (check->tag == GF_SG_INDEXED_REPLACE) {} else if (check->tag == GF_SG_INDEXED_INSERT) { original_is_index = 1; } else { break; } } else { if (check->tag != com->tag) break; } nb_fields = gf_list_count(com->command_fields); if (gf_list_count(check->command_fields) != nb_fields) break; apply=1; for (j=0; j<nb_fields; j++) { field = gf_list_get(com->command_fields, j); check_field = gf_list_get(check->command_fields, j); if ((field->pos != check_field->pos) || (field->fieldIndex != check_field->fieldIndex)) { apply=0; break; } } /*same target node+fields, destroy first command and store new one*/ if (apply) { /*if indexed, change command tag*/ if (original_is_index) com->tag = GF_SG_INDEXED_INSERT; gf_sg_command_del((GF_Command *)check); gf_list_rem(commands, i); if (has_modif) *has_modif = 1; return 1; } break; case GF_SG_NODE_REPLACE: if (check->tag != GF_SG_NODE_REPLACE) { break; } /*TODO - THIS IS NOT SUPPORTED IN GPAC SINCE WE NEVER ALLOW FOR DUPLICATE NODE IDs IN THE SCENE !!!*/ if (gf_node_get_id(check->node) != gf_node_get_id(com->node) ) { break; } /*same node ID, destroy first command and store new one*/ gf_sg_command_del((GF_Command *)check); gf_list_rem(commands, i); if (has_modif) *has_modif = 1; return 1; case GF_SG_INDEXED_DELETE: /*look for an indexed insert before the indexed delete with same target pos and node. If found, discard both commands!*/ if (check->tag != GF_SG_INDEXED_INSERT) break; if (com->node != check->node) break; field = gf_list_get(com->command_fields, 0); check_field = gf_list_get(check->command_fields, 0); if (!field || !check_field) break; if (field->pos != check_field->pos) break; if (field->fieldIndex != check_field->fieldIndex) break; gf_sg_command_del((GF_Command *)check); gf_list_rem(commands, i); if (has_modif) *has_modif = 1; return 2; default: GF_LOG(GF_LOG_ERROR, GF_LOG_SCENE, ("[Scene Manager] Stream Aggregation not implemented for command - aggregating on main scene\n")); break; } } } /*the command modifies another stream than associated current carousel stream, we have to store it.*/ if (has_modif) *has_modif=1; #endif return 1; } static GF_StreamContext *gf_sm_get_stream(GF_SceneManager *ctx, u16 ESID) { u32 i, count; count = gf_list_count(ctx->streams); for (i=0; i<count; i++) { GF_StreamContext *sc = gf_list_get(ctx->streams, i); if (sc->ESID==ESID) return sc; } return NULL; } GF_EXPORT GF_Err gf_sm_aggregate(GF_SceneManager *ctx, u16 ESID) { GF_Err e; u32 i, stream_count; #ifndef GPAC_DISABLE_VRML u32 j; GF_AUContext *au; GF_Command *com; #endif e = GF_OK; #if DEBUG_RAP com_count = 0; stream_count = gf_list_count(ctx->streams); for (i=0; i<stream_count; i++) { GF_StreamContext *sc = (GF_StreamContext *)gf_list_get(ctx->streams, i); if (sc->streamType == GF_STREAM_SCENE) { au_count = gf_list_count(sc->AUs); for (j=0; j<au_count; j++) { au = (GF_AUContext *)gf_list_get(sc->AUs, j); com_count += gf_list_count(au->commands); } } } GF_LOG(GF_LOG_INFO, GF_LOG_SCENE, ("[SceneManager] Making RAP with %d commands\n", com_count)); #endif stream_count = gf_list_count(ctx->streams); for (i=0; i<stream_count; i++) { GF_AUContext *carousel_au; GF_List *carousel_commands; GF_StreamContext *aggregate_on_stream; GF_StreamContext *sc = (GF_StreamContext *)gf_list_get(ctx->streams, i); if (ESID && (sc->ESID!=ESID)) continue; /*locate the AU in which our commands will be aggregated*/ carousel_au = NULL; carousel_commands = NULL; aggregate_on_stream = sc->aggregate_on_esid ? gf_sm_get_stream(ctx, sc->aggregate_on_esid) : NULL; if (aggregate_on_stream==sc) { carousel_commands = gf_list_new(); } else if (aggregate_on_stream) { if (!gf_list_count(aggregate_on_stream->AUs)) { carousel_au = gf_sm_stream_au_new(aggregate_on_stream, 0, 0, 1); } else { /* assert we already performed aggregation */ assert(gf_list_count(aggregate_on_stream->AUs)==1); carousel_au = gf_list_get(aggregate_on_stream->AUs, 0); } carousel_commands = carousel_au->commands; } /*TODO - do this as well for ODs*/ #ifndef GPAC_DISABLE_VRML if (sc->streamType == GF_STREAM_SCENE) { Bool has_modif = 0; /*we check for each stream if it is a base stream (SceneReplace ...) - several streams may carry RAPs if inline nodes are used*/ Bool base_stream_found = 0; /*in DIMS we use an empty initial AU with no commands to signal the RAP*/ if (sc->objectType == GPAC_OTI_SCENE_DIMS) base_stream_found = 1; /*apply all commands - this will also apply the SceneReplace*/ while (gf_list_count(sc->AUs)) { u32 count; au = (GF_AUContext *) gf_list_get(sc->AUs, 0); gf_list_rem(sc->AUs, 0); /*AU not aggregated*/ if (au->flags & GF_SM_AU_NOT_AGGREGATED) { gf_sm_au_del(sc, au); continue; } count = gf_list_count(au->commands); for (j=0; j<count; j++) { u32 store=0; com = gf_list_get(au->commands, j); if (!base_stream_found) { switch (com->tag) { case GF_SG_SCENE_REPLACE: case GF_SG_LSR_NEW_SCENE: case GF_SG_LSR_REFRESH_SCENE: base_stream_found = 1; break; } } /*aggregate the command*/ /*if stream doesn't carry a carousel or carries the base carousel (scene replace), always apply the command*/ if (base_stream_found || !sc->aggregate_on_esid) { store = 0; } /*otherwise, check wether the command should be kept in this stream as is, or can be aggregated on this stream*/ else { switch (com->tag) { /*the following commands do not impact a sub-tree (eg do not deal with nodes), we cannot aggregate them... */ case GF_SG_ROUTE_REPLACE: case GF_SG_ROUTE_DELETE: case GF_SG_ROUTE_INSERT: case GF_SG_PROTO_INSERT: case GF_SG_PROTO_DELETE: case GF_SG_PROTO_DELETE_ALL: case GF_SG_GLOBAL_QUANTIZER: case GF_SG_LSR_RESTORE: case GF_SG_LSR_SAVE: case GF_SG_LSR_SEND_EVENT: case GF_SG_LSR_CLEAN: /*todo check in which category to put these commands*/ // case GF_SG_LSR_ACTIVATE: // case GF_SG_LSR_DEACTIVATE: store = 1; break; /*other commands: !!! we need to know if the target node of the command has been inserted in this stream !!! This is a tedious task, for now we will consider the following cases: - locate a similar command in the stored list: remove the similar one and aggregate on stream - by default all AUs are stored if the stream is in aggregate mode - we should fix that by checking insertion points: if a command apllies on a node that has been inserted in this stream, we can aggregate, otherwise store */ default: /*check if we can directly store the command*/ assert(carousel_commands); store = store_or_aggregate(sc, com, carousel_commands, &has_modif); break; } } switch (store) { /*command has been merged with a previous command in carousel and needs to be destroyed*/ case 2: gf_list_rem(au->commands, j); j--; count--; gf_sg_command_del((GF_Command *)com); break; /*command shall be moved to carousel without being applied*/ case 1: gf_list_insert(carousel_commands, com, 0); gf_list_rem(au->commands, j); j--; count--; break; /*command can be applied*/ default: e = gf_sg_command_apply(ctx->scene_graph, com, 0); break; } } gf_sm_au_del(sc, au); } /*and recreate scene replace*/ if (base_stream_found) { au = gf_sm_stream_au_new(sc, 0, 0, 1); switch (sc->objectType) { case GPAC_OTI_SCENE_BIFS: case GPAC_OTI_SCENE_BIFS_V2: com = gf_sg_command_new(ctx->scene_graph, GF_SG_SCENE_REPLACE); break; case GPAC_OTI_SCENE_LASER: com = gf_sg_command_new(ctx->scene_graph, GF_SG_LSR_NEW_SCENE); break; case GPAC_OTI_SCENE_DIMS: /* We do not create a new command, empty AU is enough in DIMS*/ default: com = NULL; break; } if (com) { com->node = ctx->scene_graph->RootNode; ctx->scene_graph->RootNode = NULL; gf_list_del(com->new_proto_list); com->new_proto_list = ctx->scene_graph->protos; ctx->scene_graph->protos = NULL; /*indicate the command is the aggregated scene graph, so that PROTOs and ROUTEs are taken from the scenegraph when encoding*/ com->aggregated = 1; gf_list_add(au->commands, com); } } /*update carousel flags of the AU*/ else if (carousel_commands) { /*if current stream caries its own carousel*/ if (!carousel_au) { carousel_au = gf_sm_stream_au_new(sc, 0, 0, 1); gf_list_del(carousel_au->commands); carousel_au->commands = carousel_commands; } carousel_au->flags |= GF_SM_AU_RAP | GF_SM_AU_CAROUSEL; if (has_modif) carousel_au->flags |= GF_SM_AU_MODIFIED; } } #endif } return e; } #ifndef GPAC_DISABLE_LOADER_BT GF_Err gf_sm_load_init_bt(GF_SceneLoader *load); #endif #ifndef GPAC_DISABLE_LOADER_XMT GF_Err gf_sm_load_init_xmt(GF_SceneLoader *load); #endif #ifndef GPAC_DISABLE_LOADER_ISOM GF_Err gf_sm_load_init_isom(GF_SceneLoader *load); #endif #ifndef GPAC_DISABLE_SVG GF_Err gf_sm_load_init_svg(GF_SceneLoader *load); GF_Err gf_sm_load_init_xbl(GF_SceneLoader *load); GF_Err gf_sm_load_run_xbl(GF_SceneLoader *load); void gf_sm_load_done_xbl(GF_SceneLoader *load); #endif #ifndef GPAC_DISABLE_SWF_IMPORT GF_Err gf_sm_load_init_swf(GF_SceneLoader *load); #endif #ifndef GPAC_DISABLE_QTVR GF_Err gf_sm_load_init_qt(GF_SceneLoader *load); #endif GF_EXPORT GF_Err gf_sm_load_string(GF_SceneLoader *load, const char *str, Bool do_clean) { GF_Err e; if (!load->type) e = GF_BAD_PARAM; else if (load->parse_string) e = load->parse_string(load, str); else e = GF_NOT_SUPPORTED; return e; } /*initializes the context loader*/ GF_EXPORT GF_Err gf_sm_load_init(GF_SceneLoader *load) { GF_Err e = GF_NOT_SUPPORTED; char *ext, szExt[50]; /*we need at least a scene graph*/ if (!load || (!load->ctx && !load->scene_graph) #ifndef GPAC_DISABLE_ISOM || (!load->fileName && !load->isom && !(load->flags & GF_SM_LOAD_FOR_PLAYBACK) ) #endif ) return GF_BAD_PARAM; if (!load->type) { #ifndef GPAC_DISABLE_ISOM if (load->isom) { load->type = GF_SM_LOAD_MP4; } else #endif { ext = (char *)strrchr(load->fileName, '.'); if (!ext) return GF_NOT_SUPPORTED; if (!stricmp(ext, ".gz")) { char *anext; ext[0] = 0; anext = (char *)strrchr(load->fileName, '.'); ext[0] = '.'; ext = anext; } strcpy(szExt, &ext[1]); strlwr(szExt); if (strstr(szExt, "bt")) load->type = GF_SM_LOAD_BT; else if (strstr(szExt, "wrl")) load->type = GF_SM_LOAD_VRML; else if (strstr(szExt, "x3dv")) load->type = GF_SM_LOAD_X3DV; #ifndef GPAC_DISABLE_LOADER_XMT else if (strstr(szExt, "xmt") || strstr(szExt, "xmta")) load->type = GF_SM_LOAD_XMTA; else if (strstr(szExt, "x3d")) load->type = GF_SM_LOAD_X3D; #endif else if (strstr(szExt, "swf")) load->type = GF_SM_LOAD_SWF; else if (strstr(szExt, "mov")) load->type = GF_SM_LOAD_QT; else if (strstr(szExt, "svg")) load->type = GF_SM_LOAD_SVG; else if (strstr(szExt, "xsr")) load->type = GF_SM_LOAD_XSR; else if (strstr(szExt, "xbl")) load->type = GF_SM_LOAD_XBL; else if (strstr(szExt, "xml")) { char *rtype = gf_xml_get_root_type(load->fileName, &e); if (rtype) { if (!strcmp(rtype, "SAFSession")) load->type = GF_SM_LOAD_XSR; else if (!strcmp(rtype, "XMT-A")) load->type = GF_SM_LOAD_XMTA; else if (!strcmp(rtype, "X3D")) load->type = GF_SM_LOAD_X3D; else if (!strcmp(rtype, "bindings")) load->type = GF_SM_LOAD_XBL; gf_free(rtype); } } } } if (!load->type) return e; if (!load->scene_graph) load->scene_graph = load->ctx->scene_graph; switch (load->type) { #ifndef GPAC_DISABLE_LOADER_BT case GF_SM_LOAD_BT: case GF_SM_LOAD_VRML: case GF_SM_LOAD_X3DV: return gf_sm_load_init_bt(load); #endif #ifndef GPAC_DISABLE_LOADER_XMT case GF_SM_LOAD_XMTA: case GF_SM_LOAD_X3D: return gf_sm_load_init_xmt(load); #endif #ifndef GPAC_DISABLE_SVG case GF_SM_LOAD_SVG: case GF_SM_LOAD_XSR: case GF_SM_LOAD_DIMS: return gf_sm_load_init_svg(load); case GF_SM_LOAD_XBL: e = gf_sm_load_init_xbl(load); load->process = gf_sm_load_run_xbl; load->done = gf_sm_load_done_xbl; return e; #endif #ifndef GPAC_DISABLE_SWF_IMPORT case GF_SM_LOAD_SWF: return gf_sm_load_init_swf(load); #endif #ifndef GPAC_DISABLE_LOADER_ISOM case GF_SM_LOAD_MP4: return gf_sm_load_init_isom(load); #endif #ifndef GPAC_DISABLE_QTVR case GF_SM_LOAD_QT: return gf_sm_load_init_qt(load); #endif default: return GF_NOT_SUPPORTED; } return GF_NOT_SUPPORTED; } GF_EXPORT void gf_sm_load_done(GF_SceneLoader *load) { if (load->done) load->done(load); } GF_EXPORT GF_Err gf_sm_load_run(GF_SceneLoader *load) { if (load->process) return load->process(load); return GF_OK; } GF_EXPORT GF_Err gf_sm_load_suspend(GF_SceneLoader *load, Bool suspend) { if (load->suspend) return load->suspend(load, suspend); return GF_OK; } #if !defined(GPAC_DISABLE_LOADER_BT) || !defined(GPAC_DISABLE_LOADER_XMT) #include <gpac/base_coding.h> void gf_sm_update_bitwrapper_buffer(GF_Node *node, const char *fileName) { u32 data_size = 0; char *data = NULL; char *buffer; M_BitWrapper *bw = (M_BitWrapper *)node; if (!bw->buffer.buffer) return; buffer = bw->buffer.buffer; if (!strnicmp(buffer, "file://", 7)) { char *url = gf_url_concatenate(fileName, buffer+7); if (url) { FILE *f = gf_fopen(url, "rb"); if (f) { fseek(f, 0, SEEK_END); data_size = (u32) ftell(f); fseek(f, 0, SEEK_SET); data = gf_malloc(sizeof(char)*data_size); if (data) { if (fread(data, 1, data_size, f) != data_size) { GF_LOG(GF_LOG_ERROR, GF_LOG_SCENE, ("[Scene Manager] error reading bitwrapper file %s\n", url)); } } gf_fclose(f); } gf_free(url); } } else { Bool base_64 = 0; if (!strnicmp(buffer, "data:application/octet-string", 29)) { char *sep = strchr(bw->buffer.buffer, ','); base_64 = strstr(bw->buffer.buffer, ";base64") ? 1 : 0; if (sep) buffer = sep+1; } if (base_64) { data_size = 2 * (u32) strlen(buffer); data = (char*)gf_malloc(sizeof(char)*data_size); if (data) data_size = gf_base64_decode(buffer, (u32) strlen(buffer), data, data_size); } else { u32 i, c; char s[3]; data_size = (u32) strlen(buffer) / 3; data = (char*)gf_malloc(sizeof(char) * data_size); if (data) { s[2] = 0; for (i=0; i<data_size; i++) { s[0] = buffer[3*i+1]; s[1] = buffer[3*i+2]; sscanf(s, "%02X", &c); data[i] = (unsigned char) c; } } } } gf_free(bw->buffer.buffer); bw->buffer.buffer = NULL; bw->buffer_len = 0; if (data) { bw->buffer.buffer = data; bw->buffer_len = data_size; } } #endif //!defined(GPAC_DISABLE_LOADER_BT) || !defined(GPAC_DISABLE_LOADER_XMT)
./CrossVul/dataset_final_sorted/CWE-119/c/bad_525_3
crossvul-cpp_data_good_3603_1
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Copyright (C) 2005,2006,2010 Yaacov Zamir, Nir Soffer */ #include <Python.h> #include <fribidi.h> static PyObject * unicode_log2vis (PyUnicodeObject* string, FriBidiParType base_direction, int clean, int reordernsm) { int i; int length = string->length; FriBidiChar *logical = NULL; /* input fribidi unicode buffer */ FriBidiChar *visual = NULL; /* output fribidi unicode buffer */ FriBidiStrIndex new_len = 0; /* length of the UTF-8 buffer */ PyUnicodeObject *result = NULL; /* Allocate fribidi unicode buffers TODO - Don't copy strings if sizeof(FriBidiChar) == sizeof(Py_UNICODE) */ logical = PyMem_New (FriBidiChar, length + 1); if (logical == NULL) { PyErr_NoMemory(); goto cleanup; } visual = PyMem_New (FriBidiChar, length + 1); if (visual == NULL) { PyErr_NoMemory(); goto cleanup; } for (i=0; i<length; ++i) { logical[i] = string->str[i]; } /* Convert to unicode and order visually */ fribidi_set_reorder_nsm(reordernsm); if (!fribidi_log2vis (logical, length, &base_direction, visual, NULL, NULL, NULL)) { PyErr_SetString (PyExc_RuntimeError, "fribidi failed to order string"); goto cleanup; } /* Cleanup the string if requested */ if (clean) { length = fribidi_remove_bidi_marks (visual, length, NULL, NULL, NULL); } result = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, length); if (result == NULL) { goto cleanup; } for (i=0; i<length; ++i) { result->str[i] = visual[i]; } cleanup: /* Delete unicode buffers */ PyMem_Del (logical); PyMem_Del (visual); return (PyObject *)result; } static PyObject * _pyfribidi_log2vis (PyObject * self, PyObject * args, PyObject * kw) { PyUnicodeObject *logical = NULL; /* input unicode or string object */ FriBidiParType base = FRIBIDI_TYPE_RTL; /* optional direction */ int clean = 0; /* optional flag to clean the string */ int reordernsm = 1; /* optional flag to allow reordering of non spacing marks*/ static char *kwargs[] = { "logical", "base_direction", "clean", "reordernsm", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kw, "U|iii", kwargs, &logical, &base, &clean, &reordernsm)) { return NULL; } /* Validate base */ if (!(base == FRIBIDI_TYPE_RTL || base == FRIBIDI_TYPE_LTR || base == FRIBIDI_TYPE_ON)) { return PyErr_Format (PyExc_ValueError, "invalid value %d: use either RTL, LTR or ON", base); } return unicode_log2vis (logical, base, clean, reordernsm); } static PyMethodDef PyfribidiMethods[] = { {"log2vis", (PyCFunction) _pyfribidi_log2vis, METH_VARARGS | METH_KEYWORDS, NULL}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC init_pyfribidi (void) { PyObject *module = Py_InitModule ("_pyfribidi", PyfribidiMethods); PyModule_AddIntConstant (module, "RTL", (long) FRIBIDI_TYPE_RTL); PyModule_AddIntConstant (module, "LTR", (long) FRIBIDI_TYPE_LTR); PyModule_AddIntConstant (module, "ON", (long) FRIBIDI_TYPE_ON); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_3603_1
crossvul-cpp_data_good_4839_0
/* * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "event2/event-config.h" #include "evconfig-private.h" #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> #define WIN32_LEAN_AND_MEAN #include <windows.h> #undef WIN32_LEAN_AND_MEAN #include <io.h> #include <tchar.h> #include <process.h> #undef _WIN32_WINNT /* For structs needed by GetAdaptersAddresses */ #define _WIN32_WINNT 0x0501 #include <iphlpapi.h> #endif #include <sys/types.h> #ifdef EVENT__HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef EVENT__HAVE_UNISTD_H #include <unistd.h> #endif #ifdef EVENT__HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef EVENT__HAVE_STDLIB_H #include <stdlib.h> #endif #include <errno.h> #include <limits.h> #include <stdio.h> #include <string.h> #ifdef EVENT__HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef EVENT__HAVE_NETINET_IN6_H #include <netinet/in6.h> #endif #ifdef EVENT__HAVE_NETINET_TCP_H #include <netinet/tcp.h> #endif #ifdef EVENT__HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #include <time.h> #include <sys/stat.h> #ifdef EVENT__HAVE_IFADDRS_H #include <ifaddrs.h> #endif #include "event2/util.h" #include "util-internal.h" #include "log-internal.h" #include "mm-internal.h" #include "evthread-internal.h" #include "strlcpy-internal.h" #include "ipv6-internal.h" #ifdef _WIN32 #define HT_NO_CACHE_HASH_VALUES #include "ht-internal.h" #define open _open #define read _read #define close _close #ifndef fstat #define fstat _fstati64 #endif #ifndef stat #define stat _stati64 #endif #define mode_t int #endif int evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode) { int fd; #ifdef O_CLOEXEC fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode); if (fd >= 0 || errno == EINVAL) return fd; /* If we got an EINVAL, fall through and try without O_CLOEXEC */ #endif fd = open(pathname, flags, (mode_t)mode); if (fd < 0) return -1; #if defined(FD_CLOEXEC) if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { close(fd); return -1; } #endif return fd; } /** Read the contents of 'filename' into a newly allocated NUL-terminated string. Set *content_out to hold this string, and *len_out to hold its length (not including the appended NUL). If 'is_binary', open the file in binary mode. Returns 0 on success, -1 if the open fails, and -2 for all other failures. Used internally only; may go away in a future version. */ int evutil_read_file_(const char *filename, char **content_out, size_t *len_out, int is_binary) { int fd, r; struct stat st; char *mem; size_t read_so_far=0; int mode = O_RDONLY; EVUTIL_ASSERT(content_out); EVUTIL_ASSERT(len_out); *content_out = NULL; *len_out = 0; #ifdef O_BINARY if (is_binary) mode |= O_BINARY; #endif fd = evutil_open_closeonexec_(filename, mode, 0); if (fd < 0) return -1; if (fstat(fd, &st) || st.st_size < 0 || st.st_size > EV_SSIZE_MAX-1 ) { close(fd); return -2; } mem = mm_malloc((size_t)st.st_size + 1); if (!mem) { close(fd); return -2; } read_so_far = 0; #ifdef _WIN32 #define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x)) #else #define N_TO_READ(x) (x) #endif while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) { read_so_far += r; if (read_so_far >= (size_t)st.st_size) break; EVUTIL_ASSERT(read_so_far < (size_t)st.st_size); } close(fd); if (r < 0) { mm_free(mem); return -2; } mem[read_so_far] = 0; *len_out = read_so_far; *content_out = mem; return 0; } int evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2]) { #ifndef _WIN32 return socketpair(family, type, protocol, fd); #else return evutil_ersatz_socketpair_(family, type, protocol, fd); #endif } int evutil_ersatz_socketpair_(int family, int type, int protocol, evutil_socket_t fd[2]) { /* This code is originally from Tor. Used with permission. */ /* This socketpair does not work when localhost is down. So * it's really not the same thing at all. But it's close enough * for now, and really, when localhost is down sometimes, we * have other problems too. */ #ifdef _WIN32 #define ERR(e) WSA##e #else #define ERR(e) e #endif evutil_socket_t listener = -1; evutil_socket_t connector = -1; evutil_socket_t acceptor = -1; struct sockaddr_in listen_addr; struct sockaddr_in connect_addr; ev_socklen_t size; int saved_errno = -1; int family_test; family_test = family != AF_INET; #ifdef AF_UNIX family_test = family_test && (family != AF_UNIX); #endif if (protocol || family_test) { EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT)); return -1; } if (!fd) { EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL)); return -1; } listener = socket(AF_INET, type, 0); if (listener < 0) return -1; memset(&listen_addr, 0, sizeof(listen_addr)); listen_addr.sin_family = AF_INET; listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); listen_addr.sin_port = 0; /* kernel chooses port. */ if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr)) == -1) goto tidy_up_and_fail; if (listen(listener, 1) == -1) goto tidy_up_and_fail; connector = socket(AF_INET, type, 0); if (connector < 0) goto tidy_up_and_fail; memset(&connect_addr, 0, sizeof(connect_addr)); /* We want to find out the port number to connect to. */ size = sizeof(connect_addr); if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1) goto tidy_up_and_fail; if (size != sizeof (connect_addr)) goto abort_tidy_up_and_fail; if (connect(connector, (struct sockaddr *) &connect_addr, sizeof(connect_addr)) == -1) goto tidy_up_and_fail; size = sizeof(listen_addr); acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size); if (acceptor < 0) goto tidy_up_and_fail; if (size != sizeof(listen_addr)) goto abort_tidy_up_and_fail; /* Now check we are talking to ourself by matching port and host on the two sockets. */ if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1) goto tidy_up_and_fail; if (size != sizeof (connect_addr) || listen_addr.sin_family != connect_addr.sin_family || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr || listen_addr.sin_port != connect_addr.sin_port) goto abort_tidy_up_and_fail; evutil_closesocket(listener); fd[0] = connector; fd[1] = acceptor; return 0; abort_tidy_up_and_fail: saved_errno = ERR(ECONNABORTED); tidy_up_and_fail: if (saved_errno < 0) saved_errno = EVUTIL_SOCKET_ERROR(); if (listener != -1) evutil_closesocket(listener); if (connector != -1) evutil_closesocket(connector); if (acceptor != -1) evutil_closesocket(acceptor); EVUTIL_SET_SOCKET_ERROR(saved_errno); return -1; #undef ERR } int evutil_make_socket_nonblocking(evutil_socket_t fd) { #ifdef _WIN32 { unsigned long nonblocking = 1; if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) { event_sock_warn(fd, "fcntl(%d, F_GETFL)", (int)fd); return -1; } } #else { int flags; if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) { event_warn("fcntl(%d, F_GETFL)", fd); return -1; } if (!(flags & O_NONBLOCK)) { if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) { event_warn("fcntl(%d, F_SETFL)", fd); return -1; } } } #endif return 0; } /* Faster version of evutil_make_socket_nonblocking for internal use. * * Requires that no F_SETFL flags were previously set on the fd. */ static int evutil_fast_socket_nonblocking(evutil_socket_t fd) { #ifdef _WIN32 return evutil_make_socket_nonblocking(fd); #else if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) { event_warn("fcntl(%d, F_SETFL)", fd); return -1; } return 0; #endif } int evutil_make_listen_socket_reuseable(evutil_socket_t sock) { #if defined(SO_REUSEADDR) && !defined(_WIN32) int one = 1; /* REUSEADDR on Unix means, "don't hang on to this address after the * listener is closed." On Windows, though, it means "don't keep other * processes from binding to this address while we're using it. */ return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one, (ev_socklen_t)sizeof(one)); #else return 0; #endif } int evutil_make_listen_socket_reuseable_port(evutil_socket_t sock) { #if defined __linux__ && defined(SO_REUSEPORT) int one = 1; /* REUSEPORT on Linux 3.9+ means, "Multiple servers (processes or * threads) can bind to the same port if they each set the option. */ return setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*) &one, (ev_socklen_t)sizeof(one)); #else return 0; #endif } int evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock) { #if defined(EVENT__HAVE_NETINET_TCP_H) && defined(TCP_DEFER_ACCEPT) int one = 1; /* TCP_DEFER_ACCEPT tells the kernel to call defer accept() only after data * has arrived and ready to read */ return setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &one, (ev_socklen_t)sizeof(one)); #endif return 0; } int evutil_make_socket_closeonexec(evutil_socket_t fd) { #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD) int flags; if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) { event_warn("fcntl(%d, F_GETFD)", fd); return -1; } if (!(flags & FD_CLOEXEC)) { if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) { event_warn("fcntl(%d, F_SETFD)", fd); return -1; } } #endif return 0; } /* Faster version of evutil_make_socket_closeonexec for internal use. * * Requires that no F_SETFD flags were previously set on the fd. */ static int evutil_fast_socket_closeonexec(evutil_socket_t fd) { #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD) if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) { event_warn("fcntl(%d, F_SETFD)", fd); return -1; } #endif return 0; } int evutil_closesocket(evutil_socket_t sock) { #ifndef _WIN32 return close(sock); #else return closesocket(sock); #endif } ev_int64_t evutil_strtoll(const char *s, char **endptr, int base) { #ifdef EVENT__HAVE_STRTOLL return (ev_int64_t)strtoll(s, endptr, base); #elif EVENT__SIZEOF_LONG == 8 return (ev_int64_t)strtol(s, endptr, base); #elif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1300 /* XXXX on old versions of MS APIs, we only support base * 10. */ ev_int64_t r; if (base != 10) return 0; r = (ev_int64_t) _atoi64(s); while (isspace(*s)) ++s; if (*s == '-') ++s; while (isdigit(*s)) ++s; if (endptr) *endptr = (char*) s; return r; #elif defined(_WIN32) return (ev_int64_t) _strtoi64(s, endptr, base); #elif defined(EVENT__SIZEOF_LONG_LONG) && EVENT__SIZEOF_LONG_LONG == 8 long long r; int n; if (base != 10 && base != 16) return 0; if (base == 10) { n = sscanf(s, "%lld", &r); } else { unsigned long long ru=0; n = sscanf(s, "%llx", &ru); if (ru > EV_INT64_MAX) return 0; r = (long long) ru; } if (n != 1) return 0; while (EVUTIL_ISSPACE_(*s)) ++s; if (*s == '-') ++s; if (base == 10) { while (EVUTIL_ISDIGIT_(*s)) ++s; } else { while (EVUTIL_ISXDIGIT_(*s)) ++s; } if (endptr) *endptr = (char*) s; return r; #else #error "I don't know how to parse 64-bit integers." #endif } #ifdef _WIN32 int evutil_socket_geterror(evutil_socket_t sock) { int optval, optvallen=sizeof(optval); int err = WSAGetLastError(); if (err == WSAEWOULDBLOCK && sock >= 0) { if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen)) return err; if (optval) return optval; } return err; } #endif /* XXX we should use an enum here. */ /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */ int evutil_socket_connect_(evutil_socket_t *fd_ptr, const struct sockaddr *sa, int socklen) { int made_fd = 0; if (*fd_ptr < 0) { if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0) goto err; made_fd = 1; if (evutil_make_socket_nonblocking(*fd_ptr) < 0) { goto err; } } if (connect(*fd_ptr, sa, socklen) < 0) { int e = evutil_socket_geterror(*fd_ptr); if (EVUTIL_ERR_CONNECT_RETRIABLE(e)) return 0; if (EVUTIL_ERR_CONNECT_REFUSED(e)) return 2; goto err; } else { return 1; } err: if (made_fd) { evutil_closesocket(*fd_ptr); *fd_ptr = -1; } return -1; } /* Check whether a socket on which we called connect() is done connecting. Return 1 for connected, 0 for not yet, -1 for error. In the error case, set the current socket errno to the error that happened during the connect operation. */ int evutil_socket_finished_connecting_(evutil_socket_t fd) { int e; ev_socklen_t elen = sizeof(e); if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0) return -1; if (e) { if (EVUTIL_ERR_CONNECT_RETRIABLE(e)) return 0; EVUTIL_SET_SOCKET_ERROR(e); return -1; } return 1; } #if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \ EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \ EVUTIL_AI_ADDRCONFIG) != \ (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \ EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \ EVUTIL_AI_ADDRCONFIG) #error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags" #endif /* We sometimes need to know whether we have an ipv4 address and whether we have an ipv6 address. If 'have_checked_interfaces', then we've already done the test. If 'had_ipv4_address', then it turns out we had an ipv4 address. If 'had_ipv6_address', then it turns out we had an ipv6 address. These are set by evutil_check_interfaces. */ static int have_checked_interfaces, had_ipv4_address, had_ipv6_address; /* Macro: True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8 */ #define EVUTIL_V4ADDR_IS_LOCALHOST(addr) (((addr)>>24) == 127) /* Macro: True iff the IPv4 address 'addr', in host order, is a class D * (multiclass) address. */ #define EVUTIL_V4ADDR_IS_CLASSD(addr) ((((addr)>>24) & 0xf0) == 0xe0) static void evutil_found_ifaddr(const struct sockaddr *sa) { const char ZEROES[] = "\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00"; if (sa->sa_family == AF_INET) { const struct sockaddr_in *sin = (struct sockaddr_in *)sa; ev_uint32_t addr = ntohl(sin->sin_addr.s_addr); if (addr == 0 || EVUTIL_V4ADDR_IS_LOCALHOST(addr) || EVUTIL_V4ADDR_IS_CLASSD(addr)) { /* Not actually a usable external address. */ } else { event_debug(("Detected an IPv4 interface")); had_ipv4_address = 1; } } else if (sa->sa_family == AF_INET6) { const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa; const unsigned char *addr = (unsigned char*)sin6->sin6_addr.s6_addr; if (!memcmp(addr, ZEROES, 8) || ((addr[0] & 0xfe) == 0xfc) || (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80) || (addr[0] == 0xfe && (addr[1] & 0xc0) == 0xc0) || (addr[0] == 0xff)) { /* This is a reserved, ipv4compat, ipv4map, loopback, * link-local, multicast, or unspecified address. */ } else { event_debug(("Detected an IPv6 interface")); had_ipv6_address = 1; } } } #ifdef _WIN32 typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)( ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG); #endif static int evutil_check_ifaddrs(void) { #if defined(EVENT__HAVE_GETIFADDRS) /* Most free Unixy systems provide getifaddrs, which gives us a linked list * of struct ifaddrs. */ struct ifaddrs *ifa = NULL; const struct ifaddrs *i; if (getifaddrs(&ifa) < 0) { event_warn("Unable to call getifaddrs()"); return -1; } for (i = ifa; i; i = i->ifa_next) { if (!i->ifa_addr) continue; evutil_found_ifaddr(i->ifa_addr); } freeifaddrs(ifa); return 0; #elif defined(_WIN32) /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a "GetAdaptersInfo", but that's deprecated; let's just try GetAdaptersAddresses and fall back to connect+getsockname. */ HMODULE lib = evutil_load_windows_system_library_(TEXT("ihplapi.dll")); GetAdaptersAddresses_fn_t fn; ULONG size, res; IP_ADAPTER_ADDRESSES *addresses = NULL, *address; int result = -1; #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \ GAA_FLAG_SKIP_MULTICAST | \ GAA_FLAG_SKIP_DNS_SERVER) if (!lib) goto done; if (!(fn = (GetAdaptersAddresses_fn_t) GetProcAddress(lib, "GetAdaptersAddresses"))) goto done; /* Guess how much space we need. */ size = 15*1024; addresses = mm_malloc(size); if (!addresses) goto done; res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size); if (res == ERROR_BUFFER_OVERFLOW) { /* we didn't guess that we needed enough space; try again */ mm_free(addresses); addresses = mm_malloc(size); if (!addresses) goto done; res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size); } if (res != NO_ERROR) goto done; for (address = addresses; address; address = address->Next) { IP_ADAPTER_UNICAST_ADDRESS *a; for (a = address->FirstUnicastAddress; a; a = a->Next) { /* Yes, it's a linked list inside a linked list */ struct sockaddr *sa = a->Address.lpSockaddr; evutil_found_ifaddr(sa); } } result = 0; done: if (lib) FreeLibrary(lib); if (addresses) mm_free(addresses); return result; #else return -1; #endif } /* Test whether we have an ipv4 interface and an ipv6 interface. Return 0 if * the test seemed successful. */ static int evutil_check_interfaces(int force_recheck) { evutil_socket_t fd = -1; struct sockaddr_in sin, sin_out; struct sockaddr_in6 sin6, sin6_out; ev_socklen_t sin_out_len = sizeof(sin_out); ev_socklen_t sin6_out_len = sizeof(sin6_out); int r; if (have_checked_interfaces && !force_recheck) return 0; if (evutil_check_ifaddrs() == 0) { /* Use a nice sane interface, if this system has one. */ return 0; } /* Ugh. There was no nice sane interface. So to check whether we have * an interface open for a given protocol, will try to make a UDP * 'connection' to a remote host on the internet. We don't actually * use it, so the address doesn't matter, but we want to pick one that * keep us from using a host- or link-local interface. */ memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(53); r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr); EVUTIL_ASSERT(r); memset(&sin6, 0, sizeof(sin6)); sin6.sin6_family = AF_INET6; sin6.sin6_port = htons(53); r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr); EVUTIL_ASSERT(r); memset(&sin_out, 0, sizeof(sin_out)); memset(&sin6_out, 0, sizeof(sin6_out)); /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */ if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 && connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 && getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) { /* We might have an IPv4 interface. */ evutil_found_ifaddr((struct sockaddr*) &sin_out); } if (fd >= 0) evutil_closesocket(fd); if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 && connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 && getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) { /* We might have an IPv6 interface. */ evutil_found_ifaddr((struct sockaddr*) &sin6_out); } if (fd >= 0) evutil_closesocket(fd); return 0; } /* Internal addrinfo flag. This one is set when we allocate the addrinfo from * inside libevent. Otherwise, the built-in getaddrinfo() function allocated * it, and we should trust what they said. **/ #define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000 /* Helper: construct a new addrinfo containing the socket address in * 'sa', which must be a sockaddr_in or a sockaddr_in6. Take the * socktype and protocol info from hints. If they weren't set, then * allocate both a TCP and a UDP addrinfo. */ struct evutil_addrinfo * evutil_new_addrinfo_(struct sockaddr *sa, ev_socklen_t socklen, const struct evutil_addrinfo *hints) { struct evutil_addrinfo *res; EVUTIL_ASSERT(hints); if (hints->ai_socktype == 0 && hints->ai_protocol == 0) { /* Indecisive user! Give them a UDP and a TCP. */ struct evutil_addrinfo *r1, *r2; struct evutil_addrinfo tmp; memcpy(&tmp, hints, sizeof(tmp)); tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP; r1 = evutil_new_addrinfo_(sa, socklen, &tmp); if (!r1) return NULL; tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP; r2 = evutil_new_addrinfo_(sa, socklen, &tmp); if (!r2) { evutil_freeaddrinfo(r1); return NULL; } r1->ai_next = r2; return r1; } /* We're going to allocate extra space to hold the sockaddr. */ res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen); if (!res) return NULL; res->ai_addr = (struct sockaddr*) (((char*)res) + sizeof(struct evutil_addrinfo)); memcpy(res->ai_addr, sa, socklen); res->ai_addrlen = socklen; res->ai_family = sa->sa_family; /* Same or not? XXX */ res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED; res->ai_socktype = hints->ai_socktype; res->ai_protocol = hints->ai_protocol; return res; } /* Append the addrinfo 'append' to the end of 'first', and return the start of * the list. Either element can be NULL, in which case we return the element * that is not NULL. */ struct evutil_addrinfo * evutil_addrinfo_append_(struct evutil_addrinfo *first, struct evutil_addrinfo *append) { struct evutil_addrinfo *ai = first; if (!ai) return append; while (ai->ai_next) ai = ai->ai_next; ai->ai_next = append; return first; } static int parse_numeric_servname(const char *servname) { int n; char *endptr=NULL; n = (int) strtol(servname, &endptr, 10); if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0]) return n; else return -1; } /** Parse a service name in 'servname', which can be a decimal port. * Return the port number, or -1 on error. */ static int evutil_parse_servname(const char *servname, const char *protocol, const struct evutil_addrinfo *hints) { int n = parse_numeric_servname(servname); if (n>=0) return n; #if defined(EVENT__HAVE_GETSERVBYNAME) || defined(_WIN32) if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) { struct servent *ent = getservbyname(servname, protocol); if (ent) { return ntohs(ent->s_port); } } #endif return -1; } /* Return a string corresponding to a protocol number that we can pass to * getservyname. */ static const char * evutil_unparse_protoname(int proto) { switch (proto) { case 0: return NULL; case IPPROTO_TCP: return "tcp"; case IPPROTO_UDP: return "udp"; #ifdef IPPROTO_SCTP case IPPROTO_SCTP: return "sctp"; #endif default: #ifdef EVENT__HAVE_GETPROTOBYNUMBER { struct protoent *ent = getprotobynumber(proto); if (ent) return ent->p_name; } #endif return NULL; } } static void evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints) { /* If we can guess the protocol from the socktype, do so. */ if (!hints->ai_protocol && hints->ai_socktype) { if (hints->ai_socktype == SOCK_DGRAM) hints->ai_protocol = IPPROTO_UDP; else if (hints->ai_socktype == SOCK_STREAM) hints->ai_protocol = IPPROTO_TCP; } /* Set the socktype if it isn't set. */ if (!hints->ai_socktype && hints->ai_protocol) { if (hints->ai_protocol == IPPROTO_UDP) hints->ai_socktype = SOCK_DGRAM; else if (hints->ai_protocol == IPPROTO_TCP) hints->ai_socktype = SOCK_STREAM; #ifdef IPPROTO_SCTP else if (hints->ai_protocol == IPPROTO_SCTP) hints->ai_socktype = SOCK_STREAM; #endif } } #if AF_UNSPEC != PF_UNSPEC #error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC" #endif /** Implements the part of looking up hosts by name that's common to both * the blocking and nonblocking resolver: * - Adjust 'hints' to have a reasonable socktype and protocol. * - Look up the port based on 'servname', and store it in *portnum, * - Handle the nodename==NULL case * - Handle some invalid arguments cases. * - Handle the cases where nodename is an IPv4 or IPv6 address. * * If we need the resolver to look up the hostname, we return * EVUTIL_EAI_NEED_RESOLVE. Otherwise, we can completely implement * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and * set *res as getaddrinfo would. */ int evutil_getaddrinfo_common_(const char *nodename, const char *servname, struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum) { int port = 0; const char *pname; if (nodename == NULL && servname == NULL) return EVUTIL_EAI_NONAME; /* We only understand 3 families */ if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET && hints->ai_family != PF_INET6) return EVUTIL_EAI_FAMILY; evutil_getaddrinfo_infer_protocols(hints); /* Look up the port number and protocol, if possible. */ pname = evutil_unparse_protoname(hints->ai_protocol); if (servname) { /* XXXX We could look at the protocol we got back from * getservbyname, but it doesn't seem too useful. */ port = evutil_parse_servname(servname, pname, hints); if (port < 0) { return EVUTIL_EAI_NONAME; } } /* If we have no node name, then we're supposed to bind to 'any' and * connect to localhost. */ if (nodename == NULL) { struct evutil_addrinfo *res4=NULL, *res6=NULL; if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */ struct sockaddr_in6 sin6; memset(&sin6, 0, sizeof(sin6)); sin6.sin6_family = AF_INET6; sin6.sin6_port = htons(port); if (hints->ai_flags & EVUTIL_AI_PASSIVE) { /* Bind to :: */ } else { /* connect to ::1 */ sin6.sin6_addr.s6_addr[15] = 1; } res6 = evutil_new_addrinfo_((struct sockaddr*)&sin6, sizeof(sin6), hints); if (!res6) return EVUTIL_EAI_MEMORY; } if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */ struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(port); if (hints->ai_flags & EVUTIL_AI_PASSIVE) { /* Bind to 0.0.0.0 */ } else { /* connect to 127.0.0.1 */ sin.sin_addr.s_addr = htonl(0x7f000001); } res4 = evutil_new_addrinfo_((struct sockaddr*)&sin, sizeof(sin), hints); if (!res4) { if (res6) evutil_freeaddrinfo(res6); return EVUTIL_EAI_MEMORY; } } *res = evutil_addrinfo_append_(res4, res6); return 0; } /* If we can, we should try to parse the hostname without resolving * it. */ /* Try ipv6. */ if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) { struct sockaddr_in6 sin6; memset(&sin6, 0, sizeof(sin6)); if (1==evutil_inet_pton(AF_INET6, nodename, &sin6.sin6_addr)) { /* Got an ipv6 address. */ sin6.sin6_family = AF_INET6; sin6.sin6_port = htons(port); *res = evutil_new_addrinfo_((struct sockaddr*)&sin6, sizeof(sin6), hints); if (!*res) return EVUTIL_EAI_MEMORY; return 0; } } /* Try ipv4. */ if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) { struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) { /* Got an ipv6 address. */ sin.sin_family = AF_INET; sin.sin_port = htons(port); *res = evutil_new_addrinfo_((struct sockaddr*)&sin, sizeof(sin), hints); if (!*res) return EVUTIL_EAI_MEMORY; return 0; } } /* If we have reached this point, we definitely need to do a DNS * lookup. */ if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) { /* If we're not allowed to do one, then say so. */ return EVUTIL_EAI_NONAME; } *portnum = port; return EVUTIL_EAI_NEED_RESOLVE; } #ifdef EVENT__HAVE_GETADDRINFO #define USE_NATIVE_GETADDRINFO #endif #ifdef USE_NATIVE_GETADDRINFO /* A mask of all the flags that we declare, so we can clear them before calling * the native getaddrinfo */ static const unsigned int ALL_NONNATIVE_AI_FLAGS = #ifndef AI_PASSIVE EVUTIL_AI_PASSIVE | #endif #ifndef AI_CANONNAME EVUTIL_AI_CANONNAME | #endif #ifndef AI_NUMERICHOST EVUTIL_AI_NUMERICHOST | #endif #ifndef AI_NUMERICSERV EVUTIL_AI_NUMERICSERV | #endif #ifndef AI_ADDRCONFIG EVUTIL_AI_ADDRCONFIG | #endif #ifndef AI_ALL EVUTIL_AI_ALL | #endif #ifndef AI_V4MAPPED EVUTIL_AI_V4MAPPED | #endif EVUTIL_AI_LIBEVENT_ALLOCATED; static const unsigned int ALL_NATIVE_AI_FLAGS = #ifdef AI_PASSIVE AI_PASSIVE | #endif #ifdef AI_CANONNAME AI_CANONNAME | #endif #ifdef AI_NUMERICHOST AI_NUMERICHOST | #endif #ifdef AI_NUMERICSERV AI_NUMERICSERV | #endif #ifdef AI_ADDRCONFIG AI_ADDRCONFIG | #endif #ifdef AI_ALL AI_ALL | #endif #ifdef AI_V4MAPPED AI_V4MAPPED | #endif 0; #endif #ifndef USE_NATIVE_GETADDRINFO /* Helper for systems with no getaddrinfo(): make one or more addrinfos out of * a struct hostent. */ static struct evutil_addrinfo * addrinfo_from_hostent(const struct hostent *ent, int port, const struct evutil_addrinfo *hints) { int i; struct sockaddr_in sin; struct sockaddr_in6 sin6; struct sockaddr *sa; int socklen; struct evutil_addrinfo *res=NULL, *ai; void *addrp; if (ent->h_addrtype == PF_INET) { memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(port); sa = (struct sockaddr *)&sin; socklen = sizeof(struct sockaddr_in); addrp = &sin.sin_addr; if (ent->h_length != sizeof(sin.sin_addr)) { event_warnx("Weird h_length from gethostbyname"); return NULL; } } else if (ent->h_addrtype == PF_INET6) { memset(&sin6, 0, sizeof(sin6)); sin6.sin6_family = AF_INET6; sin6.sin6_port = htons(port); sa = (struct sockaddr *)&sin6; socklen = sizeof(struct sockaddr_in6); addrp = &sin6.sin6_addr; if (ent->h_length != sizeof(sin6.sin6_addr)) { event_warnx("Weird h_length from gethostbyname"); return NULL; } } else return NULL; for (i = 0; ent->h_addr_list[i]; ++i) { memcpy(addrp, ent->h_addr_list[i], ent->h_length); ai = evutil_new_addrinfo_(sa, socklen, hints); if (!ai) { evutil_freeaddrinfo(res); return NULL; } res = evutil_addrinfo_append_(res, ai); } if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) { res->ai_canonname = mm_strdup(ent->h_name); if (res->ai_canonname == NULL) { evutil_freeaddrinfo(res); return NULL; } } return res; } #endif /* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so * that we'll only get addresses we could maybe connect to. */ void evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints) { if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG)) return; if (hints->ai_family != PF_UNSPEC) return; if (!have_checked_interfaces) evutil_check_interfaces(0); if (had_ipv4_address && !had_ipv6_address) { hints->ai_family = PF_INET; } else if (!had_ipv4_address && had_ipv6_address) { hints->ai_family = PF_INET6; } } #ifdef USE_NATIVE_GETADDRINFO static int need_numeric_port_hack_=0; static int need_socktype_protocol_hack_=0; static int tested_for_getaddrinfo_hacks=0; /* Some older BSDs (like OpenBSD up to 4.6) used to believe that giving a numeric port without giving an ai_socktype was verboten. We test for this so we can apply an appropriate workaround. If it turns out that the bug is present, then: - If nodename==NULL and servname is numeric, we build an answer ourselves using evutil_getaddrinfo_common_(). - If nodename!=NULL and servname is numeric, then we set servname=NULL when calling getaddrinfo, and post-process the result to set the ports on it. We test for this bug at runtime, since otherwise we can't have the same binary run on multiple BSD versions. - Some versions of Solaris believe that it's nice to leave to protocol field set to 0. We test for this so we can apply an appropriate workaround. */ static void test_for_getaddrinfo_hacks(void) { int r, r2; struct evutil_addrinfo *ai=NULL, *ai2=NULL; struct evutil_addrinfo hints; memset(&hints,0,sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_flags = #ifdef AI_NUMERICHOST AI_NUMERICHOST | #endif #ifdef AI_NUMERICSERV AI_NUMERICSERV | #endif 0; r = getaddrinfo("1.2.3.4", "80", &hints, &ai); hints.ai_socktype = SOCK_STREAM; r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2); if (r2 == 0 && r != 0) { need_numeric_port_hack_=1; } if (ai2 && ai2->ai_protocol == 0) { need_socktype_protocol_hack_=1; } if (ai) freeaddrinfo(ai); if (ai2) freeaddrinfo(ai2); tested_for_getaddrinfo_hacks=1; } static inline int need_numeric_port_hack(void) { if (!tested_for_getaddrinfo_hacks) test_for_getaddrinfo_hacks(); return need_numeric_port_hack_; } static inline int need_socktype_protocol_hack(void) { if (!tested_for_getaddrinfo_hacks) test_for_getaddrinfo_hacks(); return need_socktype_protocol_hack_; } static void apply_numeric_port_hack(int port, struct evutil_addrinfo **ai) { /* Now we run through the list and set the ports on all of the * results where ports would make sense. */ for ( ; *ai; ai = &(*ai)->ai_next) { struct sockaddr *sa = (*ai)->ai_addr; if (sa && sa->sa_family == AF_INET) { struct sockaddr_in *sin = (struct sockaddr_in*)sa; sin->sin_port = htons(port); } else if (sa && sa->sa_family == AF_INET6) { struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa; sin6->sin6_port = htons(port); } else { /* A numeric port makes no sense here; remove this one * from the list. */ struct evutil_addrinfo *victim = *ai; *ai = victim->ai_next; victim->ai_next = NULL; freeaddrinfo(victim); } } } static int apply_socktype_protocol_hack(struct evutil_addrinfo *ai) { struct evutil_addrinfo *ai_new; for (; ai; ai = ai->ai_next) { evutil_getaddrinfo_infer_protocols(ai); if (ai->ai_socktype || ai->ai_protocol) continue; ai_new = mm_malloc(sizeof(*ai_new)); if (!ai_new) return -1; memcpy(ai_new, ai, sizeof(*ai_new)); ai->ai_socktype = SOCK_STREAM; ai->ai_protocol = IPPROTO_TCP; ai_new->ai_socktype = SOCK_DGRAM; ai_new->ai_protocol = IPPROTO_UDP; ai_new->ai_next = ai->ai_next; ai->ai_next = ai_new; } return 0; } #endif int evutil_getaddrinfo(const char *nodename, const char *servname, const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res) { #ifdef USE_NATIVE_GETADDRINFO struct evutil_addrinfo hints; int portnum=-1, need_np_hack, err; if (hints_in) { memcpy(&hints, hints_in, sizeof(hints)); } else { memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; } #ifndef AI_ADDRCONFIG /* Not every system has AI_ADDRCONFIG, so fake it. */ if (hints.ai_family == PF_UNSPEC && (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) { evutil_adjust_hints_for_addrconfig_(&hints); } #endif #ifndef AI_NUMERICSERV /* Not every system has AI_NUMERICSERV, so fake it. */ if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) { if (servname && parse_numeric_servname(servname)<0) return EVUTIL_EAI_NONAME; } #endif /* Enough operating systems handle enough common non-resolve * cases here weirdly enough that we are better off just * overriding them. For example: * * - Windows doesn't like to infer the protocol from the * socket type, or fill in socket or protocol types much at * all. It also seems to do its own broken implicit * always-on version of AI_ADDRCONFIG that keeps it from * ever resolving even a literal IPv6 address when * ai_addrtype is PF_UNSPEC. */ #ifdef _WIN32 { int tmp_port; err = evutil_getaddrinfo_common_(nodename,servname,&hints, res, &tmp_port); if (err == 0 || err == EVUTIL_EAI_MEMORY || err == EVUTIL_EAI_NONAME) return err; /* If we make it here, the system getaddrinfo can * have a crack at it. */ } #endif /* See documentation for need_numeric_port_hack above.*/ need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype && ((portnum=parse_numeric_servname(servname)) >= 0); if (need_np_hack) { if (!nodename) return evutil_getaddrinfo_common_( NULL,servname,&hints, res, &portnum); servname = NULL; } if (need_socktype_protocol_hack()) { evutil_getaddrinfo_infer_protocols(&hints); } /* Make sure that we didn't actually steal any AI_FLAGS values that * the system is using. (This is a constant expression, and should ge * optimized out.) * * XXXX Turn this into a compile-time failure rather than a run-time * failure. */ EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0); /* Clear any flags that only libevent understands. */ hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS; err = getaddrinfo(nodename, servname, &hints, res); if (need_np_hack) apply_numeric_port_hack(portnum, res); if (need_socktype_protocol_hack()) { if (apply_socktype_protocol_hack(*res) < 0) { evutil_freeaddrinfo(*res); *res = NULL; return EVUTIL_EAI_MEMORY; } } return err; #else int port=0, err; struct hostent *ent = NULL; struct evutil_addrinfo hints; if (hints_in) { memcpy(&hints, hints_in, sizeof(hints)); } else { memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; } evutil_adjust_hints_for_addrconfig_(&hints); err = evutil_getaddrinfo_common_(nodename, servname, &hints, res, &port); if (err != EVUTIL_EAI_NEED_RESOLVE) { /* We either succeeded or failed. No need to continue */ return err; } err = 0; /* Use any of the various gethostbyname_r variants as available. */ { #ifdef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG /* This one is what glibc provides. */ char buf[2048]; struct hostent hostent; int r; r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent, &err); #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_5_ARG) char buf[2048]; struct hostent hostent; ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &err); #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_3_ARG) struct hostent_data data; struct hostent hostent; memset(&data, 0, sizeof(data)); err = gethostbyname_r(nodename, &hostent, &data); ent = err ? NULL : &hostent; #else /* fall back to gethostbyname. */ /* XXXX This needs a lock everywhere but Windows. */ ent = gethostbyname(nodename); #ifdef _WIN32 err = WSAGetLastError(); #else err = h_errno; #endif #endif /* Now we have either ent or err set. */ if (!ent) { /* XXX is this right for windows ? */ switch (err) { case TRY_AGAIN: return EVUTIL_EAI_AGAIN; case NO_RECOVERY: default: return EVUTIL_EAI_FAIL; case HOST_NOT_FOUND: return EVUTIL_EAI_NONAME; case NO_ADDRESS: #if NO_DATA != NO_ADDRESS case NO_DATA: #endif return EVUTIL_EAI_NODATA; } } if (ent->h_addrtype != hints.ai_family && hints.ai_family != PF_UNSPEC) { /* This wasn't the type we were hoping for. Too bad * we never had a chance to ask gethostbyname for what * we wanted. */ return EVUTIL_EAI_NONAME; } /* Make sure we got _some_ answers. */ if (ent->h_length == 0) return EVUTIL_EAI_NODATA; /* If we got an address type we don't know how to make a sockaddr for, give up. */ if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6) return EVUTIL_EAI_FAMILY; *res = addrinfo_from_hostent(ent, port, &hints); if (! *res) return EVUTIL_EAI_MEMORY; } return 0; #endif } void evutil_freeaddrinfo(struct evutil_addrinfo *ai) { #ifdef EVENT__HAVE_GETADDRINFO if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) { freeaddrinfo(ai); return; } #endif while (ai) { struct evutil_addrinfo *next = ai->ai_next; if (ai->ai_canonname) mm_free(ai->ai_canonname); mm_free(ai); ai = next; } } static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL; void evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn) { if (!evdns_getaddrinfo_impl) evdns_getaddrinfo_impl = fn; } /* Internal helper function: act like evdns_getaddrinfo if dns_base is set; * otherwise do a blocking resolve and pass the result to the callback in the * way that evdns_getaddrinfo would. */ int evutil_getaddrinfo_async_(struct evdns_base *dns_base, const char *nodename, const char *servname, const struct evutil_addrinfo *hints_in, void (*cb)(int, struct evutil_addrinfo *, void *), void *arg) { if (dns_base && evdns_getaddrinfo_impl) { evdns_getaddrinfo_impl( dns_base, nodename, servname, hints_in, cb, arg); } else { struct evutil_addrinfo *ai=NULL; int err; err = evutil_getaddrinfo(nodename, servname, hints_in, &ai); cb(err, ai, arg); } return 0; } const char * evutil_gai_strerror(int err) { /* As a sneaky side-benefit, this case statement will get most * compilers to tell us if any of the error codes we defined * conflict with the platform's native error codes. */ switch (err) { case EVUTIL_EAI_CANCEL: return "Request canceled"; case 0: return "No error"; case EVUTIL_EAI_ADDRFAMILY: return "address family for nodename not supported"; case EVUTIL_EAI_AGAIN: return "temporary failure in name resolution"; case EVUTIL_EAI_BADFLAGS: return "invalid value for ai_flags"; case EVUTIL_EAI_FAIL: return "non-recoverable failure in name resolution"; case EVUTIL_EAI_FAMILY: return "ai_family not supported"; case EVUTIL_EAI_MEMORY: return "memory allocation failure"; case EVUTIL_EAI_NODATA: return "no address associated with nodename"; case EVUTIL_EAI_NONAME: return "nodename nor servname provided, or not known"; case EVUTIL_EAI_SERVICE: return "servname not supported for ai_socktype"; case EVUTIL_EAI_SOCKTYPE: return "ai_socktype not supported"; case EVUTIL_EAI_SYSTEM: return "system error"; default: #if defined(USE_NATIVE_GETADDRINFO) && defined(_WIN32) return gai_strerrorA(err); #elif defined(USE_NATIVE_GETADDRINFO) return gai_strerror(err); #else return "Unknown error code"; #endif } } #ifdef _WIN32 /* destructively remove a trailing line terminator from s */ static void chomp (char *s) { size_t len; if (s && (len = strlen (s)) > 0 && s[len - 1] == '\n') { s[--len] = 0; if (len > 0 && s[len - 1] == '\r') s[--len] = 0; } } /* FormatMessage returns allocated strings, but evutil_socket_error_to_string * is supposed to return a string which is good indefinitely without having * to be freed. To make this work without leaking memory, we cache the * string the first time FormatMessage is called on a particular error * code, and then return the cached string on subsequent calls with the * same code. The strings aren't freed until libevent_global_shutdown * (or never). We use a linked list to cache the errors, because we * only expect there to be a few dozen, and that should be fast enough. */ struct cached_sock_errs_entry { HT_ENTRY(cached_sock_errs_entry) node; DWORD code; char *msg; /* allocated with LocalAlloc; free with LocalFree */ }; static inline unsigned hash_cached_sock_errs(const struct cached_sock_errs_entry *e) { /* Use Murmur3's 32-bit finalizer as an integer hash function */ DWORD h = e->code; h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } static inline int eq_cached_sock_errs(const struct cached_sock_errs_entry *a, const struct cached_sock_errs_entry *b) { return a->code == b->code; } #ifndef EVENT__DISABLE_THREAD_SUPPORT static void *windows_socket_errors_lock_ = NULL; #endif static HT_HEAD(cached_sock_errs_map, cached_sock_errs_entry) windows_socket_errors = HT_INITIALIZER(); HT_PROTOTYPE(cached_sock_errs_map, cached_sock_errs_entry, node, hash_cached_sock_errs, eq_cached_sock_errs); HT_GENERATE(cached_sock_errs_map, cached_sock_errs_entry, node, hash_cached_sock_errs, eq_cached_sock_errs, 0.5, mm_malloc, mm_realloc, mm_free); /** Equivalent to strerror, but for windows socket errors. */ const char * evutil_socket_error_to_string(int errcode) { struct cached_sock_errs_entry *errs, *newerr, find; char *msg = NULL; EVLOCK_LOCK(windows_socket_errors_lock_, 0); find.code = errcode; errs = HT_FIND(cached_sock_errs_map, &windows_socket_errors, &find); if (errs) { msg = errs->msg; goto done; } if (0 != FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, errcode, 0, (char *)&msg, 0, NULL)) chomp (msg); /* because message has trailing newline */ else { size_t len = 50; /* use LocalAlloc because FormatMessage does */ msg = LocalAlloc(LMEM_FIXED, len); if (!msg) { msg = (char *)"LocalAlloc failed during Winsock error"; goto done; } evutil_snprintf(msg, len, "winsock error 0x%08x", errcode); } newerr = (struct cached_sock_errs_entry *) mm_malloc(sizeof (struct cached_sock_errs_entry)); if (!newerr) { LocalFree(msg); msg = (char *)"malloc failed during Winsock error"; goto done; } newerr->code = errcode; newerr->msg = msg; HT_INSERT(cached_sock_errs_map, &windows_socket_errors, newerr); done: EVLOCK_UNLOCK(windows_socket_errors_lock_, 0); return msg; } #ifndef EVENT__DISABLE_THREAD_SUPPORT int evutil_global_setup_locks_(const int enable_locks) { EVTHREAD_SETUP_GLOBAL_LOCK(windows_socket_errors_lock_, 0); return 0; } #endif static void evutil_free_sock_err_globals(void) { struct cached_sock_errs_entry **errs, *tofree; for (errs = HT_START(cached_sock_errs_map, &windows_socket_errors) ; errs; ) { tofree = *errs; errs = HT_NEXT_RMV(cached_sock_errs_map, &windows_socket_errors, errs); LocalFree(tofree->msg); mm_free(tofree); } HT_CLEAR(cached_sock_errs_map, &windows_socket_errors); #ifndef EVENT__DISABLE_THREAD_SUPPORT if (windows_socket_errors_lock_ != NULL) { EVTHREAD_FREE_LOCK(windows_socket_errors_lock_, 0); windows_socket_errors_lock_ = NULL; } #endif } #else #ifndef EVENT__DISABLE_THREAD_SUPPORT int evutil_global_setup_locks_(const int enable_locks) { return 0; } #endif static void evutil_free_sock_err_globals(void) { } #endif int evutil_snprintf(char *buf, size_t buflen, const char *format, ...) { int r; va_list ap; va_start(ap, format); r = evutil_vsnprintf(buf, buflen, format, ap); va_end(ap); return r; } int evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap) { int r; if (!buflen) return 0; #if defined(_MSC_VER) || defined(_WIN32) r = _vsnprintf(buf, buflen, format, ap); if (r < 0) r = _vscprintf(format, ap); #elif defined(sgi) /* Make sure we always use the correct vsnprintf on IRIX */ extern int _xpg5_vsnprintf(char * __restrict, __SGI_LIBC_NAMESPACE_QUALIFIER size_t, const char * __restrict, /* va_list */ char *); r = _xpg5_vsnprintf(buf, buflen, format, ap); #else r = vsnprintf(buf, buflen, format, ap); #endif buf[buflen-1] = '\0'; return r; } #define USE_INTERNAL_NTOP #define USE_INTERNAL_PTON const char * evutil_inet_ntop(int af, const void *src, char *dst, size_t len) { #if defined(EVENT__HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP) return inet_ntop(af, src, dst, len); #else if (af == AF_INET) { const struct in_addr *in = src; const ev_uint32_t a = ntohl(in->s_addr); int r; r = evutil_snprintf(dst, len, "%d.%d.%d.%d", (int)(ev_uint8_t)((a>>24)&0xff), (int)(ev_uint8_t)((a>>16)&0xff), (int)(ev_uint8_t)((a>>8 )&0xff), (int)(ev_uint8_t)((a )&0xff)); if (r<0||(size_t)r>=len) return NULL; else return dst; #ifdef AF_INET6 } else if (af == AF_INET6) { const struct in6_addr *addr = src; char buf[64], *cp; int longestGapLen = 0, longestGapPos = -1, i, curGapPos = -1, curGapLen = 0; ev_uint16_t words[8]; for (i = 0; i < 8; ++i) { words[i] = (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1]; } if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) || (words[5] == 0xffff))) { /* This is an IPv4 address. */ if (words[5] == 0) { evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d", addr->s6_addr[12], addr->s6_addr[13], addr->s6_addr[14], addr->s6_addr[15]); } else { evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5], addr->s6_addr[12], addr->s6_addr[13], addr->s6_addr[14], addr->s6_addr[15]); } if (strlen(buf) > len) return NULL; strlcpy(dst, buf, len); return dst; } i = 0; while (i < 8) { if (words[i] == 0) { curGapPos = i++; curGapLen = 1; while (i<8 && words[i] == 0) { ++i; ++curGapLen; } if (curGapLen > longestGapLen) { longestGapPos = curGapPos; longestGapLen = curGapLen; } } else { ++i; } } if (longestGapLen<=1) longestGapPos = -1; cp = buf; for (i = 0; i < 8; ++i) { if (words[i] == 0 && longestGapPos == i) { if (i == 0) *cp++ = ':'; *cp++ = ':'; while (i < 8 && words[i] == 0) ++i; --i; /* to compensate for loop increment. */ } else { evutil_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]); cp += strlen(cp); if (i != 7) *cp++ = ':'; } } *cp = '\0'; if (strlen(buf) > len) return NULL; strlcpy(dst, buf, len); return dst; #endif } else { return NULL; } #endif } int evutil_inet_pton(int af, const char *src, void *dst) { #if defined(EVENT__HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON) return inet_pton(af, src, dst); #else if (af == AF_INET) { unsigned a,b,c,d; char more; struct in_addr *addr = dst; if (sscanf(src, "%u.%u.%u.%u%c", &a,&b,&c,&d,&more) != 4) return 0; if (a > 255) return 0; if (b > 255) return 0; if (c > 255) return 0; if (d > 255) return 0; addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d); return 1; #ifdef AF_INET6 } else if (af == AF_INET6) { struct in6_addr *out = dst; ev_uint16_t words[8]; int gapPos = -1, i, setWords=0; const char *dot = strchr(src, '.'); const char *eow; /* end of words. */ if (dot == src) return 0; else if (!dot) eow = src+strlen(src); else { unsigned byte1,byte2,byte3,byte4; char more; for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT_(*eow); --eow) ; ++eow; /* We use "scanf" because some platform inet_aton()s are too lax * about IPv4 addresses of the form "1.2.3" */ if (sscanf(eow, "%u.%u.%u.%u%c", &byte1,&byte2,&byte3,&byte4,&more) != 4) return 0; if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255) return 0; words[6] = (byte1<<8) | byte2; words[7] = (byte3<<8) | byte4; setWords += 2; } i = 0; while (src < eow) { if (i > 7) return 0; if (EVUTIL_ISXDIGIT_(*src)) { char *next; long r = strtol(src, &next, 16); if (next > 4+src) return 0; if (next == src) return 0; if (r<0 || r>65536) return 0; words[i++] = (ev_uint16_t)r; setWords++; src = next; if (*src != ':' && src != eow) return 0; ++src; } else if (*src == ':' && i > 0 && gapPos==-1) { gapPos = i; ++src; } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) { gapPos = i; src += 2; } else { return 0; } } if (setWords > 8 || (setWords == 8 && gapPos != -1) || (setWords < 8 && gapPos == -1)) return 0; if (gapPos >= 0) { int nToMove = setWords - (dot ? 2 : 0) - gapPos; int gapLen = 8 - setWords; /* assert(nToMove >= 0); */ if (nToMove < 0) return -1; /* should be impossible */ memmove(&words[gapPos+gapLen], &words[gapPos], sizeof(ev_uint16_t)*nToMove); memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen); } for (i = 0; i < 8; ++i) { out->s6_addr[2*i ] = words[i] >> 8; out->s6_addr[2*i+1] = words[i] & 0xff; } return 1; #endif } else { return -1; } #endif } int evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen) { int port; char buf[128]; const char *cp, *addr_part, *port_part; int is_ipv6; /* recognized formats are: * [ipv6]:port * ipv6 * [ipv6] * ipv4:port * ipv4 */ cp = strchr(ip_as_string, ':'); if (*ip_as_string == '[') { size_t len; if (!(cp = strchr(ip_as_string, ']'))) { return -1; } len = ( cp-(ip_as_string + 1) ); if (len > sizeof(buf)-1) { return -1; } memcpy(buf, ip_as_string+1, len); buf[len] = '\0'; addr_part = buf; if (cp[1] == ':') port_part = cp+2; else port_part = NULL; is_ipv6 = 1; } else if (cp && strchr(cp+1, ':')) { is_ipv6 = 1; addr_part = ip_as_string; port_part = NULL; } else if (cp) { is_ipv6 = 0; if (cp - ip_as_string > (int)sizeof(buf)-1) { return -1; } memcpy(buf, ip_as_string, cp-ip_as_string); buf[cp-ip_as_string] = '\0'; addr_part = buf; port_part = cp+1; } else { addr_part = ip_as_string; port_part = NULL; is_ipv6 = 0; } if (port_part == NULL) { port = 0; } else { port = atoi(port_part); if (port <= 0 || port > 65535) { return -1; } } if (!addr_part) return -1; /* Should be impossible. */ #ifdef AF_INET6 if (is_ipv6) { struct sockaddr_in6 sin6; memset(&sin6, 0, sizeof(sin6)); #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN sin6.sin6_len = sizeof(sin6); #endif sin6.sin6_family = AF_INET6; sin6.sin6_port = htons(port); if (1 != evutil_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr)) return -1; if ((int)sizeof(sin6) > *outlen) return -1; memset(out, 0, *outlen); memcpy(out, &sin6, sizeof(sin6)); *outlen = sizeof(sin6); return 0; } else #endif { struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN sin.sin_len = sizeof(sin); #endif sin.sin_family = AF_INET; sin.sin_port = htons(port); if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr)) return -1; if ((int)sizeof(sin) > *outlen) return -1; memset(out, 0, *outlen); memcpy(out, &sin, sizeof(sin)); *outlen = sizeof(sin); return 0; } } const char * evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen) { char b[128]; const char *res=NULL; int port; if (sa->sa_family == AF_INET) { const struct sockaddr_in *sin = (const struct sockaddr_in*)sa; res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b)); port = ntohs(sin->sin_port); if (res) { evutil_snprintf(out, outlen, "%s:%d", b, port); return out; } } else if (sa->sa_family == AF_INET6) { const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa; res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b)); port = ntohs(sin6->sin6_port); if (res) { evutil_snprintf(out, outlen, "[%s]:%d", b, port); return out; } } evutil_snprintf(out, outlen, "<addr with socktype %d>", (int)sa->sa_family); return out; } int evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2, int include_port) { int r; if (0 != (r = (sa1->sa_family - sa2->sa_family))) return r; if (sa1->sa_family == AF_INET) { const struct sockaddr_in *sin1, *sin2; sin1 = (const struct sockaddr_in *)sa1; sin2 = (const struct sockaddr_in *)sa2; if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr) return -1; else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr) return 1; else if (include_port && (r = ((int)sin1->sin_port - (int)sin2->sin_port))) return r; else return 0; } #ifdef AF_INET6 else if (sa1->sa_family == AF_INET6) { const struct sockaddr_in6 *sin1, *sin2; sin1 = (const struct sockaddr_in6 *)sa1; sin2 = (const struct sockaddr_in6 *)sa2; if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16))) return r; else if (include_port && (r = ((int)sin1->sin6_port - (int)sin2->sin6_port))) return r; else return 0; } #endif return 1; } /* Tables to implement ctypes-replacement EVUTIL_IS*() functions. Each table * has 256 bits to look up whether a character is in some set or not. This * fails on non-ASCII platforms, but so does every other place where we * take a char and write it onto the network. **/ static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] = { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 }; static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] = { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 }; static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 }; static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] = { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 }; static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 }; static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] = { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 }; static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 }; static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 }; /* Upper-casing and lowercasing tables to map characters to upper/lowercase * equivalents. */ static const unsigned char EVUTIL_TOUPPER_TABLE[256] = { 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,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,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 const unsigned char EVUTIL_TOLOWER_TABLE[256] = { 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,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,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, }; #define IMPL_CTYPE_FN(name) \ int EVUTIL_##name##_(char c) { \ ev_uint8_t u = c; \ return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \ } IMPL_CTYPE_FN(ISALPHA) IMPL_CTYPE_FN(ISALNUM) IMPL_CTYPE_FN(ISSPACE) IMPL_CTYPE_FN(ISDIGIT) IMPL_CTYPE_FN(ISXDIGIT) IMPL_CTYPE_FN(ISPRINT) IMPL_CTYPE_FN(ISLOWER) IMPL_CTYPE_FN(ISUPPER) char EVUTIL_TOLOWER_(char c) { return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]); } char EVUTIL_TOUPPER_(char c) { return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]); } int evutil_ascii_strcasecmp(const char *s1, const char *s2) { char c1, c2; while (1) { c1 = EVUTIL_TOLOWER_(*s1++); c2 = EVUTIL_TOLOWER_(*s2++); if (c1 < c2) return -1; else if (c1 > c2) return 1; else if (c1 == 0) return 0; } } int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n) { char c1, c2; while (n--) { c1 = EVUTIL_TOLOWER_(*s1++); c2 = EVUTIL_TOLOWER_(*s2++); if (c1 < c2) return -1; else if (c1 > c2) return 1; else if (c1 == 0) return 0; } return 0; } void evutil_rtrim_lws_(char *str) { char *cp; if (str == NULL) return; if ((cp = strchr(str, '\0')) == NULL || (cp == str)) return; --cp; while (*cp == ' ' || *cp == '\t') { *cp = '\0'; if (cp == str) break; --cp; } } static int evutil_issetugid(void) { #ifdef EVENT__HAVE_ISSETUGID return issetugid(); #else #ifdef EVENT__HAVE_GETEUID if (getuid() != geteuid()) return 1; #endif #ifdef EVENT__HAVE_GETEGID if (getgid() != getegid()) return 1; #endif return 0; #endif } const char * evutil_getenv_(const char *varname) { if (evutil_issetugid()) return NULL; return getenv(varname); } ev_uint32_t evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed) { if (seed == 0) { struct timeval tv; evutil_gettimeofday(&tv, NULL); seed = (ev_uint32_t)tv.tv_sec + (ev_uint32_t)tv.tv_usec; #ifdef _WIN32 seed += (ev_uint32_t) _getpid(); #else seed += (ev_uint32_t) getpid(); #endif } state->seed = seed; return seed; } ev_int32_t evutil_weakrand_(struct evutil_weakrand_state *state) { /* This RNG implementation is a linear congruential generator, with * modulus 2^31, multiplier 1103515245, and addend 12345. It's also * used by OpenBSD, and by Glibc's TYPE_0 RNG. * * The linear congruential generator is not an industrial-strength * RNG! It's fast, but it can have higher-order patterns. Notably, * the low bits tend to have periodicity. */ state->seed = ((state->seed) * 1103515245 + 12345) & 0x7fffffff; return (ev_int32_t)(state->seed); } ev_int32_t evutil_weakrand_range_(struct evutil_weakrand_state *state, ev_int32_t top) { ev_int32_t divisor, result; /* We can't just do weakrand() % top, since the low bits of the LCG * are less random than the high ones. (Specifically, since the LCG * modulus is 2^N, every 2^m for m<N will divide the modulus, and so * therefore the low m bits of the LCG will have period 2^m.) */ divisor = EVUTIL_WEAKRAND_MAX / top; do { result = evutil_weakrand_(state) / divisor; } while (result >= top); return result; } /** * Volatile pointer to memset: we use this to keep the compiler from * eliminating our call to memset. */ void * (*volatile evutil_memset_volatile_)(void *, int, size_t) = memset; void evutil_memclear_(void *mem, size_t len) { evutil_memset_volatile_(mem, 0, len); } int evutil_sockaddr_is_loopback_(const struct sockaddr *addr) { static const char LOOPBACK_S6[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1"; if (addr->sa_family == AF_INET) { struct sockaddr_in *sin = (struct sockaddr_in *)addr; return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000; } else if (addr->sa_family == AF_INET6) { struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr; return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16); } return 0; } int evutil_hex_char_to_int_(char c) { switch(c) { 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; } return -1; } #ifdef _WIN32 HMODULE evutil_load_windows_system_library_(const TCHAR *library_name) { TCHAR path[MAX_PATH]; unsigned n; n = GetSystemDirectory(path, MAX_PATH); if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH) return 0; _tcscat(path, TEXT("\\")); _tcscat(path, library_name); return LoadLibrary(path); } #endif /* Internal wrapper around 'socket' to provide Linux-style support for * syscall-saving methods where available. * * In addition to regular socket behavior, you can use a bitwise or to set the * flags EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'type' argument, * to make the socket nonblocking or close-on-exec with as few syscalls as * possible. */ evutil_socket_t evutil_socket_(int domain, int type, int protocol) { evutil_socket_t r; #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC) r = socket(domain, type, protocol); if (r >= 0) return r; else if ((type & (SOCK_NONBLOCK|SOCK_CLOEXEC)) == 0) return -1; #endif #define SOCKET_TYPE_MASK (~(EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC)) r = socket(domain, type & SOCKET_TYPE_MASK, protocol); if (r < 0) return -1; if (type & EVUTIL_SOCK_NONBLOCK) { if (evutil_fast_socket_nonblocking(r) < 0) { evutil_closesocket(r); return -1; } } if (type & EVUTIL_SOCK_CLOEXEC) { if (evutil_fast_socket_closeonexec(r) < 0) { evutil_closesocket(r); return -1; } } return r; } /* Internal wrapper around 'accept' or 'accept4' to provide Linux-style * support for syscall-saving methods where available. * * In addition to regular accept behavior, you can set one or more of flags * EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'flags' argument, to * make the socket nonblocking or close-on-exec with as few syscalls as * possible. */ evutil_socket_t evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr, ev_socklen_t *addrlen, int flags) { evutil_socket_t result; #if defined(EVENT__HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK) result = accept4(sockfd, addr, addrlen, flags); if (result >= 0 || (errno != EINVAL && errno != ENOSYS)) { /* A nonnegative result means that we succeeded, so return. * Failing with EINVAL means that an option wasn't supported, * and failing with ENOSYS means that the syscall wasn't * there: in those cases we want to fall back. Otherwise, we * got a real error, and we should return. */ return result; } #endif result = accept(sockfd, addr, addrlen); if (result < 0) return result; if (flags & EVUTIL_SOCK_CLOEXEC) { if (evutil_fast_socket_closeonexec(result) < 0) { evutil_closesocket(result); return -1; } } if (flags & EVUTIL_SOCK_NONBLOCK) { if (evutil_fast_socket_nonblocking(result) < 0) { evutil_closesocket(result); return -1; } } return result; } /* Internal function: Set fd[0] and fd[1] to a pair of fds such that writes on * fd[0] get read from fd[1]. Make both fds nonblocking and close-on-exec. * Return 0 on success, -1 on failure. */ int evutil_make_internal_pipe_(evutil_socket_t fd[2]) { /* Making the second socket nonblocking is a bit subtle, given that we ignore any EAGAIN returns when writing to it, and you don't usally do that for a nonblocking socket. But if the kernel gives us EAGAIN, then there's no need to add any more data to the buffer, since the main thread is already either about to wake up and drain it, or woken up and in the process of draining it. */ #if defined(EVENT__HAVE_PIPE2) if (pipe2(fd, O_NONBLOCK|O_CLOEXEC) == 0) return 0; #endif #if defined(EVENT__HAVE_PIPE) if (pipe(fd) == 0) { if (evutil_fast_socket_nonblocking(fd[0]) < 0 || evutil_fast_socket_nonblocking(fd[1]) < 0 || evutil_fast_socket_closeonexec(fd[0]) < 0 || evutil_fast_socket_closeonexec(fd[1]) < 0) { close(fd[0]); close(fd[1]); fd[0] = fd[1] = -1; return -1; } return 0; } else { event_warn("%s: pipe", __func__); } #endif #ifdef _WIN32 #define LOCAL_SOCKETPAIR_AF AF_INET #else #define LOCAL_SOCKETPAIR_AF AF_UNIX #endif if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, fd) == 0) { if (evutil_fast_socket_nonblocking(fd[0]) < 0 || evutil_fast_socket_nonblocking(fd[1]) < 0 || evutil_fast_socket_closeonexec(fd[0]) < 0 || evutil_fast_socket_closeonexec(fd[1]) < 0) { evutil_closesocket(fd[0]); evutil_closesocket(fd[1]); fd[0] = fd[1] = -1; return -1; } return 0; } fd[0] = fd[1] = -1; return -1; } /* Wrapper around eventfd on systems that provide it. Unlike the system * eventfd, it always supports EVUTIL_EFD_CLOEXEC and EVUTIL_EFD_NONBLOCK as * flags. Returns -1 on error or if eventfd is not supported. */ evutil_socket_t evutil_eventfd_(unsigned initval, int flags) { #if defined(EVENT__HAVE_EVENTFD) && defined(EVENT__HAVE_SYS_EVENTFD_H) int r; #if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK) r = eventfd(initval, flags); if (r >= 0 || flags == 0) return r; #endif r = eventfd(initval, 0); if (r < 0) return r; if (flags & EVUTIL_EFD_CLOEXEC) { if (evutil_fast_socket_closeonexec(r) < 0) { evutil_closesocket(r); return -1; } } if (flags & EVUTIL_EFD_NONBLOCK) { if (evutil_fast_socket_nonblocking(r) < 0) { evutil_closesocket(r); return -1; } } return r; #else return -1; #endif } void evutil_free_globals_(void) { evutil_free_secure_rng_globals_(); evutil_free_sock_err_globals(); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_4839_0
crossvul-cpp_data_bad_941_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC % % SS T A A T I SS T I C % % SSS T AAAAA T I SSS T I C % % SS T A A T I SS T I C % % SSSSS T A A T IIIII SSSSS T IIIII CCCC % % % % % % MagickCore Image Statistical Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/accelerate-private.h" #include "magick/animate.h" #include "magick/animate.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/cache-view.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/compress.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/display.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/image-private.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/semaphore.h" #include "magick/signature-private.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/timer.h" #include "magick/utility.h" #include "magick/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E v a l u a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EvaluateImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the EvaluateImageChannel method is: % % MagickBooleanType EvaluateImage(Image *image, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImages(Image *images, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImageChannel(Image *image, % const ChannelType channel,const MagickEvaluateOperator op, % const double value,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o op: A channel op. % % o value: A value value. % % o exception: return any errors or warnings in this structure. % */ static MagickPixelPacket **DestroyPixelThreadSet(MagickPixelPacket **pixels) { register ssize_t i; assert(pixels != (MagickPixelPacket **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (MagickPixelPacket *) NULL) pixels[i]=(MagickPixelPacket *) RelinquishMagickMemory(pixels[i]); pixels=(MagickPixelPacket **) RelinquishMagickMemory(pixels); return(pixels); } static MagickPixelPacket **AcquirePixelThreadSet(const Image *images) { const Image *next; MagickPixelPacket **pixels; register ssize_t i, j; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) GetMagickPixelPacket(images,&pixels[i][j]); } return(pixels); } static inline double EvaluateMax(const double x,const double y) { if (x > y) return(x); return(y); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { const MagickPixelPacket *color_1, *color_2; int intensity; color_1=(const MagickPixelPacket *) x; color_2=(const MagickPixelPacket *) y; intensity=(int) MagickPixelIntensity(color_2)-(int) MagickPixelIntensity(color_1); return(intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info, const Quantum pixel,const MagickEvaluateOperator op, const MagickRealType value) { MagickRealType result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(MagickRealType) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() which returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale* pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, ImpulseNoise,value); break; } case LaplacianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value* pixel+1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(MagickRealType) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MedianEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MinEvaluateOperator: { result=(MagickRealType) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(MagickRealType) (value*pixel); break; } case OrEvaluateOperator: { result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, PoissonNoise,value); break; } case PowEvaluateOperator: { result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel), (double) value)); break; } case RightShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(MagickRealType) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(MagickRealType) (pixel-value); break; } case SumEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, UniformNoise,value); break; } case XorEvaluateOperator: { result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5)); break; } } return(result); } static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception) { const Image *p, *q; size_t columns, number_channels, rows; q=images; columns=images->columns; rows=images->rows; number_channels=0; for (p=images; p != (Image *) NULL; p=p->next) { size_t channels; channels=3; if (p->matte != MagickFalse) channels+=1; if (p->colorspace == CMYKColorspace) channels+=1; if (channels > number_channels) { number_channels=channels; q=p; } if (p->columns > columns) columns=p->columns; if (p->rows > rows) rows=p->rows; } return(CloneImage(q,columns,rows,MagickTrue,exception)); } MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { MagickBooleanType status; status=EvaluateImageChannel(image,CompositeChannels,op,value,exception); return(status); } MagickExport Image *EvaluateImages(const Image *images, const MagickEvaluateOperator op,ExceptionInfo *exception) { #define EvaluateImageTag "Evaluate/Image" CacheView *evaluate_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict evaluate_pixels, zero; RandomInfo **magick_restrict random_info; size_t number_images; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } evaluate_pixels=AcquirePixelThreadSet(images); if (evaluate_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Evaluate image pixels. */ status=MagickTrue; progress=0; number_images=GetImageListLength(images); GetMagickPixelPacket(images,&zero); random_info=AcquireRandomInfoThreadSet(); evaluate_view=AcquireAuthenticCacheView(image,exception); if (op == MedianEvaluateOperator) { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) number_images; i++) evaluate_pixel[i]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); evaluate_pixel[i].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),op,evaluate_pixel[i].red); evaluate_pixel[i].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),op,evaluate_pixel[i].green); evaluate_pixel[i].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),op,evaluate_pixel[i].blue); evaluate_pixel[i].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),op,evaluate_pixel[i].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[i].index=ApplyEvaluateOperator(random_info[id], *indexes,op,evaluate_pixel[i].index); image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel), IntensityCompare); SetPixelRed(q,ClampToQuantum(evaluate_pixel[i/2].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[i/2].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[i/2].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[i/2].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+i,ClampToQuantum( evaluate_pixel[i/2].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,EvaluateImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } else { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register ssize_t i, x; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) evaluate_pixel[x]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].red); evaluate_pixel[x].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].green); evaluate_pixel[x].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].blue); evaluate_pixel[x].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[x].index=ApplyEvaluateOperator(random_info[id], GetPixelIndex(indexes+x),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].index); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } if (op == MeanEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red/=number_images; evaluate_pixel[x].green/=number_images; evaluate_pixel[x].blue/=number_images; evaluate_pixel[x].opacity/=number_images; evaluate_pixel[x].index/=number_images; } if (op == RootMeanSquareEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=sqrt((double) evaluate_pixel[x].red/ number_images); evaluate_pixel[x].green=sqrt((double) evaluate_pixel[x].green/ number_images); evaluate_pixel[x].blue=sqrt((double) evaluate_pixel[x].blue/ number_images); evaluate_pixel[x].opacity=sqrt((double) evaluate_pixel[x].opacity/ number_images); evaluate_pixel[x].index=sqrt((double) evaluate_pixel[x].index/ number_images); } if (op == MultiplyEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) (number_images-1); j++) { evaluate_pixel[x].red*=(MagickRealType) QuantumScale; evaluate_pixel[x].green*=(MagickRealType) QuantumScale; evaluate_pixel[x].blue*=(MagickRealType) QuantumScale; evaluate_pixel[x].opacity*=(MagickRealType) QuantumScale; evaluate_pixel[x].index*=(MagickRealType) QuantumScale; } } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(evaluate_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[x].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+x,ClampToQuantum( evaluate_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(images,EvaluateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } evaluate_view=DestroyCacheView(evaluate_view); evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) image=DestroyImage(image); return(image); } MagickExport MagickBooleanType EvaluateImageChannel(Image *image, const ChannelType channel,const MagickEvaluateOperator op,const double value, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType result; if ((channel & RedChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelRed(q),op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelRed(q,ClampToQuantum(result)); } if ((channel & GreenChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelGreen(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelGreen(q,ClampToQuantum(result)); } if ((channel & BlueChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelBlue(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelBlue(q,ClampToQuantum(result)); } if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) { result=ApplyEvaluateOperator(random_info[id],GetPixelOpacity(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelOpacity(q,ClampToQuantum(result)); } else { result=ApplyEvaluateOperator(random_info[id],GetPixelAlpha(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelAlpha(q,ClampToQuantum(result)); } } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) { result=ApplyEvaluateOperator(random_info[id],GetPixelIndex(indexes+x), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelIndex(indexes+x,ClampToQuantum(result)); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F u n c t i o n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FunctionImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the FunctionImageChannel method is: % % MagickBooleanType FunctionImage(Image *image, % const MagickFunction function,const ssize_t number_parameters, % const double *parameters,ExceptionInfo *exception) % MagickBooleanType FunctionImageChannel(Image *image, % const ChannelType channel,const MagickFunction function, % const ssize_t number_parameters,const double *argument, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o function: A channel function. % % o parameters: one or more parameters. % % o exception: return any errors or warnings in this structure. % */ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { MagickRealType result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* * Polynomial * Parameters: polynomial constants, highest to lowest order * For example: c0*x^3 + c1*x^2 + c2*x + c3 */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel + parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { /* Sinusoid Function * Parameters: Freq, Phase, Ampl, bias */ double freq,phase,ampl,bias; freq = ( number_parameters >= 1 ) ? parameters[0] : 1.0; phase = ( number_parameters >= 2 ) ? parameters[1] : 0.0; ampl = ( number_parameters >= 3 ) ? parameters[2] : 0.5; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (QuantumRange*(ampl*sin((double) (2.0*MagickPI* (freq*QuantumScale*pixel + phase/360.0) )) + bias ) ); break; } case ArcsinFunction: { /* Arcsin Function (peged at range limits for invalid results) * Parameters: Width, Center, Range, Bias */ double width,range,center,bias; width = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result = 2.0/width*(QuantumScale*pixel - center); if ( result <= -1.0 ) result = bias - range/2.0; else if ( result >= 1.0 ) result = bias + range/2.0; else result=(MagickRealType) (range/MagickPI*asin((double) result)+bias); result *= QuantumRange; break; } case ArctanFunction: { /* Arctan Function * Parameters: Slope, Center, Range, Bias */ double slope,range,center,bias; slope = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center)); result=(MagickRealType) (QuantumRange*(range/MagickPI*atan((double) result) + bias ) ); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } MagickExport MagickBooleanType FunctionImage(Image *image, const MagickFunction function,const size_t number_parameters, const double *parameters,ExceptionInfo *exception) { MagickBooleanType status; status=FunctionImageChannel(image,CompositeChannels,function, number_parameters,parameters,exception); return(status); } MagickExport MagickBooleanType FunctionImageChannel(Image *image, const ChannelType channel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { #define FunctionImageTag "Function/Image " CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) status=AccelerateFunctionImage(image,channel,function,number_parameters, parameters,exception); if (status != MagickFalse) return(status); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ApplyFunction(GetPixelRed(q),function, number_parameters,parameters,exception)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ApplyFunction(GetPixelGreen(q),function, number_parameters,parameters,exception)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ApplyFunction(GetPixelBlue(q),function, number_parameters,parameters,exception)); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,ApplyFunction(GetPixelOpacity(q),function, number_parameters,parameters,exception)); else SetPixelAlpha(q,ApplyFunction((Quantum) GetPixelAlpha(q),function, number_parameters,parameters,exception)); } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) SetPixelIndex(indexes+x,ApplyFunction(GetPixelIndex(indexes+x),function, number_parameters,parameters,exception)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,FunctionImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l E n t r o p y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelEntropy() returns the entropy of one or more image channels. % % The format of the GetImageChannelEntropy method is: % % MagickBooleanType GetImageChannelEntropy(const Image *image, % const ChannelType channel,double *entropy,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o entropy: the average entropy of the selected channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageEntropy(const Image *image, double *entropy,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelEntropy(image,CompositeChannels,entropy,exception); return(status); } MagickExport MagickBooleanType GetImageChannelEntropy(const Image *image, const ChannelType channel,double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].entropy=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[RedChannel].entropy; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[GreenChannel].entropy; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlueChannel].entropy; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[OpacityChannel].entropy; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlackChannel].entropy; channels++; } channel_statistics[CompositeChannels].entropy/=channels; *entropy=channel_statistics[CompositeChannels].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e C h a n n e l E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelExtrema() returns the extrema of one or more image channels. % % The format of the GetImageChannelExtrema method is: % % MagickBooleanType GetImageChannelExtrema(const Image *image, % const ChannelType channel,size_t *minima,size_t *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageExtrema(const Image *image, size_t *minima,size_t *maxima,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelExtrema(image,CompositeChannels,minima,maxima, exception); return(status); } MagickExport MagickBooleanType GetImageChannelExtrema(const Image *image, const ChannelType channel,size_t *minima,size_t *maxima, ExceptionInfo *exception) { double max, min; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageChannelRange(image,channel,&min,&max,exception); *minima=(size_t) ceil(min-0.5); *maxima=(size_t) floor(max+0.5); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l K u r t o s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelKurtosis() returns the kurtosis and skewness of one or more % image channels. % % The format of the GetImageChannelKurtosis method is: % % MagickBooleanType GetImageChannelKurtosis(const Image *image, % const ChannelType channel,double *kurtosis,double *skewness, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o kurtosis: the kurtosis of the channel. % % o skewness: the skewness of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageKurtosis(const Image *image, double *kurtosis,double *skewness,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelKurtosis(image,CompositeChannels,kurtosis,skewness, exception); return(status); } MagickExport MagickBooleanType GetImageChannelKurtosis(const Image *image, const ChannelType channel,double *kurtosis,double *skewness, ExceptionInfo *exception) { double area, mean, standard_deviation, sum_squares, sum_cubes, sum_fourth_power; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *kurtosis=0.0; *skewness=0.0; area=0.0; mean=0.0; standard_deviation=0.0; sum_squares=0.0; sum_cubes=0.0; sum_fourth_power=0.0; for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { mean+=GetPixelRed(p); sum_squares+=(double) GetPixelRed(p)*GetPixelRed(p); sum_cubes+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)* GetPixelRed(p)*GetPixelRed(p); area++; } if ((channel & GreenChannel) != 0) { mean+=GetPixelGreen(p); sum_squares+=(double) GetPixelGreen(p)*GetPixelGreen(p); sum_cubes+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p); sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); area++; } if ((channel & BlueChannel) != 0) { mean+=GetPixelBlue(p); sum_squares+=(double) GetPixelBlue(p)*GetPixelBlue(p); sum_cubes+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); area++; } if ((channel & OpacityChannel) != 0) { mean+=GetPixelAlpha(p); sum_squares+=(double) GetPixelOpacity(p)*GetPixelAlpha(p); sum_cubes+=(double) GetPixelOpacity(p)*GetPixelAlpha(p)* GetPixelAlpha(p); sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)* GetPixelAlpha(p)*GetPixelAlpha(p); area++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { double index; index=(double) GetPixelIndex(indexes+x); mean+=index; sum_squares+=index*index; sum_cubes+=index*index*index; sum_fourth_power+=index*index*index*index; area++; } p++; } } if (y < (ssize_t) image->rows) return(MagickFalse); if (area != 0.0) { mean/=area; sum_squares/=area; sum_cubes/=area; sum_fourth_power/=area; } standard_deviation=sqrt(sum_squares-(mean*mean)); if (standard_deviation != 0.0) { *kurtosis=sum_fourth_power-4.0*mean*sum_cubes+6.0*mean*mean*sum_squares- 3.0*mean*mean*mean*mean; *kurtosis/=standard_deviation*standard_deviation*standard_deviation* standard_deviation; *kurtosis-=3.0; *skewness=sum_cubes-3.0*mean*sum_squares+2.0*mean*mean*mean; *skewness/=standard_deviation*standard_deviation*standard_deviation; } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M e a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMean() returns the mean and standard deviation of one or more % image channels. % % The format of the GetImageChannelMean method is: % % MagickBooleanType GetImageChannelMean(const Image *image, % const ChannelType channel,double *mean,double *standard_deviation, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o mean: the average value in the channel. % % o standard_deviation: the standard deviation of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean, double *standard_deviation,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelMean(image,CompositeChannels,mean,standard_deviation, exception); return(status); } MagickExport MagickBooleanType GetImageChannelMean(const Image *image, const ChannelType channel,double *mean,double *standard_deviation, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[RedChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[RedChannel].standard_deviation; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[GreenChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[GreenChannel].standard_deviation; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlueChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[BlueChannel].standard_deviation; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].mean+= (QuantumRange-channel_statistics[OpacityChannel].mean); channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[OpacityChannel].standard_deviation; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlackChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[CompositeChannels].standard_deviation; channels++; } channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].standard_deviation/=channels; *mean=channel_statistics[CompositeChannels].mean; *standard_deviation=channel_statistics[CompositeChannels].standard_deviation; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M o m e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMoments() returns the normalized moments of one or more image % channels. % % The format of the GetImageChannelMoments method is: % % ChannelMoments *GetImageChannelMoments(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelMoments *GetImageChannelMoments(const Image *image, ExceptionInfo *exception) { #define MaxNumberImageMoments 8 ChannelMoments *channel_moments; double M00[CompositeChannels+1], M01[CompositeChannels+1], M02[CompositeChannels+1], M03[CompositeChannels+1], M10[CompositeChannels+1], M11[CompositeChannels+1], M12[CompositeChannels+1], M20[CompositeChannels+1], M21[CompositeChannels+1], M22[CompositeChannels+1], M30[CompositeChannels+1]; MagickPixelPacket pixel; PointInfo centroid[CompositeChannels+1]; ssize_t channel, channels, y; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_moments=(ChannelMoments *) AcquireQuantumMemory(length, sizeof(*channel_moments)); if (channel_moments == (ChannelMoments *) NULL) return(channel_moments); (void) memset(channel_moments,0,length*sizeof(*channel_moments)); (void) memset(centroid,0,sizeof(centroid)); (void) memset(M00,0,sizeof(M00)); (void) memset(M01,0,sizeof(M01)); (void) memset(M02,0,sizeof(M02)); (void) memset(M03,0,sizeof(M03)); (void) memset(M10,0,sizeof(M10)); (void) memset(M11,0,sizeof(M11)); (void) memset(M12,0,sizeof(M12)); (void) memset(M20,0,sizeof(M20)); (void) memset(M21,0,sizeof(M21)); (void) memset(M22,0,sizeof(M22)); (void) memset(M30,0,sizeof(M30)); GetMagickPixelPacket(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute center of mass (centroid). */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M00[RedChannel]+=QuantumScale*pixel.red; M10[RedChannel]+=x*QuantumScale*pixel.red; M01[RedChannel]+=y*QuantumScale*pixel.red; M00[GreenChannel]+=QuantumScale*pixel.green; M10[GreenChannel]+=x*QuantumScale*pixel.green; M01[GreenChannel]+=y*QuantumScale*pixel.green; M00[BlueChannel]+=QuantumScale*pixel.blue; M10[BlueChannel]+=x*QuantumScale*pixel.blue; M01[BlueChannel]+=y*QuantumScale*pixel.blue; if (image->matte != MagickFalse) { M00[OpacityChannel]+=QuantumScale*pixel.opacity; M10[OpacityChannel]+=x*QuantumScale*pixel.opacity; M01[OpacityChannel]+=y*QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M00[IndexChannel]+=QuantumScale*pixel.index; M10[IndexChannel]+=x*QuantumScale*pixel.index; M01[IndexChannel]+=y*QuantumScale*pixel.index; } p++; } } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute center of mass (centroid). */ if (M00[channel] < MagickEpsilon) { M00[channel]+=MagickEpsilon; centroid[channel].x=(double) image->columns/2.0; centroid[channel].y=(double) image->rows/2.0; continue; } M00[channel]+=MagickEpsilon; centroid[channel].x=M10[channel]/M00[channel]; centroid[channel].y=M01[channel]/M00[channel]; } for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute the image moments. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M11[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M20[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*QuantumScale*pixel.red; M02[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M21[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M12[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M22[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M30[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(x-centroid[RedChannel].x)*QuantumScale* pixel.red; M03[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M11[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M20[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*QuantumScale*pixel.green; M02[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M21[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M12[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M22[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M30[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(x-centroid[GreenChannel].x)*QuantumScale* pixel.green; M03[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M11[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M20[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*QuantumScale*pixel.blue; M02[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M21[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M12[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M22[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M30[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(x-centroid[BlueChannel].x)*QuantumScale* pixel.blue; M03[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; if (image->matte != MagickFalse) { M11[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M20[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*QuantumScale*pixel.opacity; M02[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M21[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M12[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M22[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M30[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(x-centroid[OpacityChannel].x)* QuantumScale*pixel.opacity; M03[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M11[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M20[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*QuantumScale*pixel.index; M02[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M21[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M12[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M22[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M30[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(x-centroid[IndexChannel].x)* QuantumScale*pixel.index; M03[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; } p++; } } channels=3; M00[CompositeChannels]+=(M00[RedChannel]+M00[GreenChannel]+M00[BlueChannel]); M01[CompositeChannels]+=(M01[RedChannel]+M01[GreenChannel]+M01[BlueChannel]); M02[CompositeChannels]+=(M02[RedChannel]+M02[GreenChannel]+M02[BlueChannel]); M03[CompositeChannels]+=(M03[RedChannel]+M03[GreenChannel]+M03[BlueChannel]); M10[CompositeChannels]+=(M10[RedChannel]+M10[GreenChannel]+M10[BlueChannel]); M11[CompositeChannels]+=(M11[RedChannel]+M11[GreenChannel]+M11[BlueChannel]); M12[CompositeChannels]+=(M12[RedChannel]+M12[GreenChannel]+M12[BlueChannel]); M20[CompositeChannels]+=(M20[RedChannel]+M20[GreenChannel]+M20[BlueChannel]); M21[CompositeChannels]+=(M21[RedChannel]+M21[GreenChannel]+M21[BlueChannel]); M22[CompositeChannels]+=(M22[RedChannel]+M22[GreenChannel]+M22[BlueChannel]); M30[CompositeChannels]+=(M30[RedChannel]+M30[GreenChannel]+M30[BlueChannel]); if (image->matte != MagickFalse) { channels+=1; M00[CompositeChannels]+=M00[OpacityChannel]; M01[CompositeChannels]+=M01[OpacityChannel]; M02[CompositeChannels]+=M02[OpacityChannel]; M03[CompositeChannels]+=M03[OpacityChannel]; M10[CompositeChannels]+=M10[OpacityChannel]; M11[CompositeChannels]+=M11[OpacityChannel]; M12[CompositeChannels]+=M12[OpacityChannel]; M20[CompositeChannels]+=M20[OpacityChannel]; M21[CompositeChannels]+=M21[OpacityChannel]; M22[CompositeChannels]+=M22[OpacityChannel]; M30[CompositeChannels]+=M30[OpacityChannel]; } if (image->colorspace == CMYKColorspace) { channels+=1; M00[CompositeChannels]+=M00[IndexChannel]; M01[CompositeChannels]+=M01[IndexChannel]; M02[CompositeChannels]+=M02[IndexChannel]; M03[CompositeChannels]+=M03[IndexChannel]; M10[CompositeChannels]+=M10[IndexChannel]; M11[CompositeChannels]+=M11[IndexChannel]; M12[CompositeChannels]+=M12[IndexChannel]; M20[CompositeChannels]+=M20[IndexChannel]; M21[CompositeChannels]+=M21[IndexChannel]; M22[CompositeChannels]+=M22[IndexChannel]; M30[CompositeChannels]+=M30[IndexChannel]; } M00[CompositeChannels]/=(double) channels; M01[CompositeChannels]/=(double) channels; M02[CompositeChannels]/=(double) channels; M03[CompositeChannels]/=(double) channels; M10[CompositeChannels]/=(double) channels; M11[CompositeChannels]/=(double) channels; M12[CompositeChannels]/=(double) channels; M20[CompositeChannels]/=(double) channels; M21[CompositeChannels]/=(double) channels; M22[CompositeChannels]/=(double) channels; M30[CompositeChannels]/=(double) channels; for (channel=0; channel <= CompositeChannels; channel++) { /* Compute elliptical angle, major and minor axes, eccentricity, & intensity. */ channel_moments[channel].centroid=centroid[channel]; channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0* M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon))); if (fabs(M11[channel]) < MagickEpsilon) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } else if (M11[channel] < 0.0) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=180.0; } else { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } channel_moments[channel].ellipse_eccentricity=sqrt(1.0-( channel_moments[channel].ellipse_axis.y/ (channel_moments[channel].ellipse_axis.x+MagickEpsilon))); channel_moments[channel].ellipse_intensity=M00[channel]/ (MagickPI*channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.y+MagickEpsilon); } for (channel=0; channel <= CompositeChannels; channel++) { /* Normalize image moments. */ M10[channel]=0.0; M01[channel]=0.0; M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0); M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0); M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0); M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0); M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0); M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0); M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0); M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0); M00[channel]=1.0; } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute Hu invariant moments. */ channel_moments[channel].I[0]=M20[channel]+M02[channel]; channel_moments[channel].I[1]=(M20[channel]-M02[channel])* (M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel]; channel_moments[channel].I[2]=(M30[channel]-3.0*M12[channel])* (M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])* (3.0*M21[channel]-M03[channel]); channel_moments[channel].I[3]=(M30[channel]+M12[channel])* (M30[channel]+M12[channel])+(M21[channel]+M03[channel])* (M21[channel]+M03[channel]); channel_moments[channel].I[4]=(M30[channel]-3.0*M12[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[5]=(M20[channel]-M02[channel])* ((M30[channel]+M12[channel])*(M30[channel]+M12[channel])- (M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+ 4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]); channel_moments[channel].I[6]=(3.0*M21[channel]-M03[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[7]=M11[channel]*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M03[channel]+M21[channel])* (M03[channel]+M21[channel]))-(M20[channel]-M02[channel])* (M30[channel]+M12[channel])*(M03[channel]+M21[channel]); } if (y < (ssize_t) image->rows) channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments); return(channel_moments); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelPerceptualHash() returns the perceptual hash of one or more % image channels. % % The format of the GetImageChannelPerceptualHash method is: % % ChannelPerceptualHash *GetImageChannelPerceptualHash(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelPerceptualHash *GetImageChannelPerceptualHash( const Image *image,ExceptionInfo *exception) { ChannelMoments *moments; ChannelPerceptualHash *perceptual_hash; Image *hash_image; MagickBooleanType status; register ssize_t i; ssize_t channel; /* Blur then transform to sRGB colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) return((ChannelPerceptualHash *) NULL); hash_image->depth=8; status=TransformImageColorspace(hash_image,sRGBColorspace); if (status == MagickFalse) return((ChannelPerceptualHash *) NULL); moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) return((ChannelPerceptualHash *) NULL); perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory( CompositeChannels+1UL,sizeof(*perceptual_hash)); if (perceptual_hash == (ChannelPerceptualHash *) NULL) return((ChannelPerceptualHash *) NULL); for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].P[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); /* Blur then transform to HCLp colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } hash_image->depth=8; status=TransformImageColorspace(hash_image,HCLpColorspace); if (status == MagickFalse) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].Q[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); return(perceptual_hash); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelRange() returns the range of one or more image channels. % % The format of the GetImageChannelRange method is: % % MagickBooleanType GetImageChannelRange(const Image *image, % const ChannelType channel,double *minima,double *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageRange(const Image *image, double *minima,double *maxima,ExceptionInfo *exception) { return(GetImageChannelRange(image,CompositeChannels,minima,maxima,exception)); } MagickExport MagickBooleanType GetImageChannelRange(const Image *image, const ChannelType channel,double *minima,double *maxima, ExceptionInfo *exception) { MagickPixelPacket pixel; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *maxima=(-MagickMaximumValue); *minima=MagickMaximumValue; GetMagickPixelPacket(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); if ((channel & RedChannel) != 0) { if (pixel.red < *minima) *minima=(double) pixel.red; if (pixel.red > *maxima) *maxima=(double) pixel.red; } if ((channel & GreenChannel) != 0) { if (pixel.green < *minima) *minima=(double) pixel.green; if (pixel.green > *maxima) *maxima=(double) pixel.green; } if ((channel & BlueChannel) != 0) { if (pixel.blue < *minima) *minima=(double) pixel.blue; if (pixel.blue > *maxima) *maxima=(double) pixel.blue; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { if ((QuantumRange-pixel.opacity) < *minima) *minima=(double) (QuantumRange-pixel.opacity); if ((QuantumRange-pixel.opacity) > *maxima) *maxima=(double) (QuantumRange-pixel.opacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((double) pixel.index < *minima) *minima=(double) pixel.index; if ((double) pixel.index > *maxima) *maxima=(double) pixel.index; } p++; } } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l S t a t i s t i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelStatistics() returns statistics for each channel in the % image. The statistics include the channel depth, its minima, maxima, mean, % standard deviation, kurtosis and skewness. You can access the red channel % mean, for example, like this: % % channel_statistics=GetImageChannelStatistics(image,exception); % red_mean=channel_statistics[RedChannel].mean; % % Use MagickRelinquishMemory() to free the statistics buffer. % % The format of the GetImageChannelStatistics method is: % % ChannelStatistics *GetImageChannelStatistics(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelStatistics *GetImageChannelStatistics(const Image *image, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; double area, standard_deviation; MagickPixelPacket number_bins, *histogram; QuantumAny range; register ssize_t i; size_t channels, depth, length; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(length, sizeof(*channel_statistics)); histogram=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1U, sizeof(*histogram)); if ((channel_statistics == (ChannelStatistics *) NULL) || (histogram == (MagickPixelPacket *) NULL)) { if (histogram != (MagickPixelPacket *) NULL) histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (channel_statistics != (ChannelStatistics *) NULL) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } (void) memset(channel_statistics,0,length* sizeof(*channel_statistics)); for (i=0; i <= (ssize_t) CompositeChannels; i++) { channel_statistics[i].depth=1; channel_statistics[i].maxima=(-MagickMaximumValue); channel_statistics[i].minima=MagickMaximumValue; } (void) memset(histogram,0,(MaxMap+1U)*sizeof(*histogram)); (void) memset(&number_bins,0,sizeof(number_bins)); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute pixel statistics. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; ) { if (channel_statistics[RedChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[RedChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelRed(p),range) == MagickFalse) { channel_statistics[RedChannel].depth++; continue; } } if (channel_statistics[GreenChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[GreenChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelGreen(p),range) == MagickFalse) { channel_statistics[GreenChannel].depth++; continue; } } if (channel_statistics[BlueChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlueChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelBlue(p),range) == MagickFalse) { channel_statistics[BlueChannel].depth++; continue; } } if (image->matte != MagickFalse) { if (channel_statistics[OpacityChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[OpacityChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelAlpha(p),range) == MagickFalse) { channel_statistics[OpacityChannel].depth++; continue; } } } if (image->colorspace == CMYKColorspace) { if (channel_statistics[BlackChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlackChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelIndex(indexes+x),range) == MagickFalse) { channel_statistics[BlackChannel].depth++; continue; } } } if ((double) GetPixelRed(p) < channel_statistics[RedChannel].minima) channel_statistics[RedChannel].minima=(double) GetPixelRed(p); if ((double) GetPixelRed(p) > channel_statistics[RedChannel].maxima) channel_statistics[RedChannel].maxima=(double) GetPixelRed(p); channel_statistics[RedChannel].sum+=GetPixelRed(p); channel_statistics[RedChannel].sum_squared+=(double) GetPixelRed(p)* GetPixelRed(p); channel_statistics[RedChannel].sum_cubed+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); channel_statistics[RedChannel].sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); if ((double) GetPixelGreen(p) < channel_statistics[GreenChannel].minima) channel_statistics[GreenChannel].minima=(double) GetPixelGreen(p); if ((double) GetPixelGreen(p) > channel_statistics[GreenChannel].maxima) channel_statistics[GreenChannel].maxima=(double) GetPixelGreen(p); channel_statistics[GreenChannel].sum+=GetPixelGreen(p); channel_statistics[GreenChannel].sum_squared+=(double) GetPixelGreen(p)* GetPixelGreen(p); channel_statistics[GreenChannel].sum_cubed+=(double) GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); channel_statistics[GreenChannel].sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p); if ((double) GetPixelBlue(p) < channel_statistics[BlueChannel].minima) channel_statistics[BlueChannel].minima=(double) GetPixelBlue(p); if ((double) GetPixelBlue(p) > channel_statistics[BlueChannel].maxima) channel_statistics[BlueChannel].maxima=(double) GetPixelBlue(p); channel_statistics[BlueChannel].sum+=GetPixelBlue(p); channel_statistics[BlueChannel].sum_squared+=(double) GetPixelBlue(p)* GetPixelBlue(p); channel_statistics[BlueChannel].sum_cubed+=(double) GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); channel_statistics[BlueChannel].sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); histogram[ScaleQuantumToMap(GetPixelRed(p))].red++; histogram[ScaleQuantumToMap(GetPixelGreen(p))].green++; histogram[ScaleQuantumToMap(GetPixelBlue(p))].blue++; if (image->matte != MagickFalse) { if ((double) GetPixelAlpha(p) < channel_statistics[OpacityChannel].minima) channel_statistics[OpacityChannel].minima=(double) GetPixelAlpha(p); if ((double) GetPixelAlpha(p) > channel_statistics[OpacityChannel].maxima) channel_statistics[OpacityChannel].maxima=(double) GetPixelAlpha(p); channel_statistics[OpacityChannel].sum+=GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_squared+=(double) GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_cubed+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); histogram[ScaleQuantumToMap(GetPixelAlpha(p))].opacity++; } if (image->colorspace == CMYKColorspace) { if ((double) GetPixelIndex(indexes+x) < channel_statistics[BlackChannel].minima) channel_statistics[BlackChannel].minima=(double) GetPixelIndex(indexes+x); if ((double) GetPixelIndex(indexes+x) > channel_statistics[BlackChannel].maxima) channel_statistics[BlackChannel].maxima=(double) GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum+=GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_squared+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_cubed+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_fourth_power+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); histogram[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index++; } x++; p++; } } for (i=0; i < (ssize_t) CompositeChannels; i++) { double area, mean, standard_deviation; /* Normalize pixel statistics. */ area=PerceptibleReciprocal((double) image->columns*image->rows); mean=channel_statistics[i].sum*area; channel_statistics[i].sum=mean; channel_statistics[i].sum_squared*=area; channel_statistics[i].sum_cubed*=area; channel_statistics[i].sum_fourth_power*=area; channel_statistics[i].mean=mean; channel_statistics[i].variance=channel_statistics[i].sum_squared; standard_deviation=sqrt(channel_statistics[i].variance-(mean*mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; } for (i=0; i < (ssize_t) (MaxMap+1U); i++) { if (histogram[i].red > 0.0) number_bins.red++; if (histogram[i].green > 0.0) number_bins.green++; if (histogram[i].blue > 0.0) number_bins.blue++; if ((image->matte != MagickFalse) && (histogram[i].opacity > 0.0)) number_bins.opacity++; if ((image->colorspace == CMYKColorspace) && (histogram[i].index > 0.0)) number_bins.index++; } area=PerceptibleReciprocal((double) image->columns*image->rows); for (i=0; i < (ssize_t) (MaxMap+1U); i++) { /* Compute pixel entropy. */ histogram[i].red*=area; channel_statistics[RedChannel].entropy+=-histogram[i].red* MagickLog10(histogram[i].red)* PerceptibleReciprocal(MagickLog10((double) number_bins.red)); histogram[i].green*=area; channel_statistics[GreenChannel].entropy+=-histogram[i].green* MagickLog10(histogram[i].green)* PerceptibleReciprocal(MagickLog10((double) number_bins.green)); histogram[i].blue*=area; channel_statistics[BlueChannel].entropy+=-histogram[i].blue* MagickLog10(histogram[i].blue)* PerceptibleReciprocal(MagickLog10((double) number_bins.blue)); if (image->matte != MagickFalse) { histogram[i].opacity*=area; channel_statistics[OpacityChannel].entropy+=-histogram[i].opacity* MagickLog10(histogram[i].opacity)* PerceptibleReciprocal(MagickLog10((double) number_bins.opacity)); } if (image->colorspace == CMYKColorspace) { histogram[i].index*=area; channel_statistics[IndexChannel].entropy+=-histogram[i].index* MagickLog10(histogram[i].index)* PerceptibleReciprocal(MagickLog10((double) number_bins.index)); } } /* Compute overall statistics. */ for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].depth=(size_t) EvaluateMax((double) channel_statistics[CompositeChannels].depth,(double) channel_statistics[i].depth); channel_statistics[CompositeChannels].minima=MagickMin( channel_statistics[CompositeChannels].minima, channel_statistics[i].minima); channel_statistics[CompositeChannels].maxima=EvaluateMax( channel_statistics[CompositeChannels].maxima, channel_statistics[i].maxima); channel_statistics[CompositeChannels].sum+=channel_statistics[i].sum; channel_statistics[CompositeChannels].sum_squared+= channel_statistics[i].sum_squared; channel_statistics[CompositeChannels].sum_cubed+= channel_statistics[i].sum_cubed; channel_statistics[CompositeChannels].sum_fourth_power+= channel_statistics[i].sum_fourth_power; channel_statistics[CompositeChannels].mean+=channel_statistics[i].mean; channel_statistics[CompositeChannels].variance+= channel_statistics[i].variance-channel_statistics[i].mean* channel_statistics[i].mean; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[CompositeChannels].standard_deviation=standard_deviation; channel_statistics[CompositeChannels].entropy+= channel_statistics[i].entropy; } channels=3; if (image->matte != MagickFalse) channels++; if (image->colorspace == CMYKColorspace) channels++; channel_statistics[CompositeChannels].sum/=channels; channel_statistics[CompositeChannels].sum_squared/=channels; channel_statistics[CompositeChannels].sum_cubed/=channels; channel_statistics[CompositeChannels].sum_fourth_power/=channels; channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].kurtosis/=channels; channel_statistics[CompositeChannels].skewness/=channels; channel_statistics[CompositeChannels].entropy/=channels; i=CompositeChannels; area=PerceptibleReciprocal((double) channels*image->columns*image->rows); channel_statistics[i].variance=channel_statistics[i].sum_squared; channel_statistics[i].mean=channel_statistics[i].sum; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); standard_deviation=sqrt(PerceptibleReciprocal((double) channels* image->columns*image->rows-1.0)*channels*image->columns*image->rows* standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; for (i=0; i <= (ssize_t) CompositeChannels; i++) { /* Compute kurtosis & skewness statistics. */ standard_deviation=PerceptibleReciprocal( channel_statistics[i].standard_deviation); channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0* channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation); channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0* channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean* channel_statistics[i].mean*1.0*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation*standard_deviation)-3.0; } channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].mean+= channel_statistics[i].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[i].standard_deviation; } channel_statistics[CompositeChannels].mean/=(double) channels; channel_statistics[CompositeChannels].standard_deviation/=(double) channels; histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (y < (ssize_t) image->rows) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l y n o m i a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolynomialImage() returns a new image where each pixel is the sum of the % pixels in the image sequence after applying its corresponding terms % (coefficient and degree pairs). % % The format of the PolynomialImage method is: % % Image *PolynomialImage(const Image *images,const size_t number_terms, % const double *terms,ExceptionInfo *exception) % Image *PolynomialImageChannel(const Image *images, % const size_t number_terms,const ChannelType channel, % const double *terms,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o channel: the channel. % % o number_terms: the number of terms in the list. The actual list length % is 2 x number_terms + 1 (the constant). % % o terms: the list of polynomial coefficients and degree pairs and a % constant. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolynomialImage(const Image *images, const size_t number_terms,const double *terms,ExceptionInfo *exception) { Image *polynomial_image; polynomial_image=PolynomialImageChannel(images,DefaultChannels,number_terms, terms,exception); return(polynomial_image); } MagickExport Image *PolynomialImageChannel(const Image *images, const ChannelType channel,const size_t number_terms,const double *terms, ExceptionInfo *exception) { #define PolynomialImageTag "Polynomial/Image" CacheView *polynomial_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict polynomial_pixels, zero; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } polynomial_pixels=AcquirePixelThreadSet(images); if (polynomial_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Polynomial image pixels. */ status=MagickTrue; progress=0; GetMagickPixelPacket(images,&zero); polynomial_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict polynomial_indexes; register MagickPixelPacket *polynomial_pixel; register PixelPacket *magick_restrict q; register ssize_t i, x; size_t number_images; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } polynomial_indexes=GetCacheViewAuthenticIndexQueue(polynomial_view); polynomial_pixel=polynomial_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) polynomial_pixel[x]=zero; next=images; number_images=GetImageListLength(images); for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; if (i >= (ssize_t) number_terms) break; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { double coefficient, degree; coefficient=terms[i << 1]; degree=terms[(i << 1)+1]; if ((channel & RedChannel) != 0) polynomial_pixel[x].red+=coefficient*pow(QuantumScale*p->red,degree); if ((channel & GreenChannel) != 0) polynomial_pixel[x].green+=coefficient*pow(QuantumScale*p->green, degree); if ((channel & BlueChannel) != 0) polynomial_pixel[x].blue+=coefficient*pow(QuantumScale*p->blue, degree); if ((channel & OpacityChannel) != 0) polynomial_pixel[x].opacity+=coefficient*pow(QuantumScale* (QuantumRange-p->opacity),degree); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) polynomial_pixel[x].index+=coefficient*pow(QuantumScale*indexes[x], degree); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].blue)); if (image->matte == MagickFalse) SetPixelOpacity(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); else SetPixelAlpha(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(polynomial_indexes+x,ClampToQuantum(QuantumRange* polynomial_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(images,PolynomialImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } polynomial_view=DestroyCacheView(polynomial_view); polynomial_pixels=DestroyPixelThreadSet(polynomial_pixels); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t a t i s t i c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StatisticImage() makes each pixel the min / max / median / mode / etc. of % the neighborhood of the specified width and height. % % The format of the StatisticImage method is: % % Image *StatisticImage(const Image *image,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % Image *StatisticImageChannel(const Image *image, % const ChannelType channel,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the image channel. % % o type: the statistic type (median, mode, etc.). % % o width: the width of the pixel neighborhood. % % o height: the height of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ #define ListChannels 5 typedef struct _ListNode { size_t next[9], count, signature; } ListNode; typedef struct _SkipList { ssize_t level; ListNode *nodes; } SkipList; typedef struct _PixelList { size_t length, seed, signature; SkipList lists[ListChannels]; } PixelList; static PixelList *DestroyPixelList(PixelList *pixel_list) { register ssize_t i; if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); for (i=0; i < ListChannels; i++) if (pixel_list->lists[i].nodes != (ListNode *) NULL) pixel_list->lists[i].nodes=(ListNode *) RelinquishAlignedMemory( pixel_list->lists[i].nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list) { register ssize_t i; assert(pixel_list != (PixelList **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_list[i] != (PixelList *) NULL) pixel_list[i]=DestroyPixelList(pixel_list[i]); pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList *AcquirePixelList(const size_t width,const size_t height) { PixelList *pixel_list; register ssize_t i; pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list)); if (pixel_list == (PixelList *) NULL) return(pixel_list); (void) memset((void *) pixel_list,0,sizeof(*pixel_list)); pixel_list->length=width*height; for (i=0; i < ListChannels; i++) { pixel_list->lists[i].nodes=(ListNode *) AcquireAlignedMemory(65537UL, sizeof(*pixel_list->lists[i].nodes)); if (pixel_list->lists[i].nodes == (ListNode *) NULL) return(DestroyPixelList(pixel_list)); (void) memset(pixel_list->lists[i].nodes,0,65537UL* sizeof(*pixel_list->lists[i].nodes)); } pixel_list->signature=MagickCoreSignature; return(pixel_list); } static PixelList **AcquirePixelListThreadSet(const size_t width, const size_t height) { PixelList **pixel_list; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixel_list=(PixelList **) AcquireQuantumMemory(number_threads, sizeof(*pixel_list)); if (pixel_list == (PixelList **) NULL) return((PixelList **) NULL); (void) memset(pixel_list,0,number_threads*sizeof(*pixel_list)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_list[i]=AcquirePixelList(width,height); if (pixel_list[i] == (PixelList *) NULL) return(DestroyPixelListThreadSet(pixel_list)); } return(pixel_list); } static void AddNodePixelList(PixelList *pixel_list,const ssize_t channel, const size_t color) { register SkipList *list; register ssize_t level; size_t search, update[9]; /* Initialize the node. */ list=pixel_list->lists+channel; list->nodes[color].signature=pixel_list->signature; list->nodes[color].count=1; /* Determine where it belongs in the list. */ search=65536UL; for (level=list->level; level >= 0; level--) { while (list->nodes[search].next[level] < color) search=list->nodes[search].next[level]; update[level]=search; } /* Generate a pseudo-random level for this node. */ for (level=0; ; level++) { pixel_list->seed=(pixel_list->seed*42893621L)+1L; if ((pixel_list->seed & 0x300) != 0x300) break; } if (level > 8) level=8; if (level > (list->level+2)) level=list->level+2; /* If we're raising the list's level, link back to the root node. */ while (level > list->level) { list->level++; update[list->level]=65536UL; } /* Link the node into the skip-list. */ do { list->nodes[color].next[level]=list->nodes[update[level]].next[level]; list->nodes[update[level]].next[level]=color; } while (level-- > 0); } static void GetMaximumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, maximum; ssize_t count; unsigned short channels[ListChannels]; /* Find the maximum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; maximum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color > maximum) maximum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) maximum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMeanPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the mean value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMedianPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the median value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; do { color=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); channels[channel]=(unsigned short) color; } GetMagickPixelPacket((const Image *) NULL,pixel); pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMinimumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, minimum; ssize_t count; unsigned short channels[ListChannels]; /* Find the minimum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; count=0; color=65536UL; minimum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color < minimum) minimum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) minimum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetModePixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, max_count, mode; ssize_t count; unsigned short channels[5]; /* Make each pixel the 'predominant color' of the specified neighborhood. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; mode=color; max_count=list->nodes[mode].count; count=0; do { color=list->nodes[color].next[0]; if (list->nodes[color].count > max_count) { mode=color; max_count=list->nodes[mode].count; } count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) mode; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetNonpeakPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, next, previous; ssize_t count; unsigned short channels[5]; /* Finds the non peak value for each of the colors. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; next=list->nodes[color].next[0]; count=0; do { previous=color; color=next; next=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); if ((previous == 65536UL) && (next != 65536UL)) color=next; else if ((previous != 65536UL) && (next == 65536UL)) color=previous; channels[channel]=(unsigned short) color; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetRootMeanSquarePixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the root mean square value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) (list->nodes[color].count*color*color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetStandardDeviationPixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum, sum_squared; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the standard-deviation value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; sum_squared=0.0; do { register ssize_t i; color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; for (i=0; i < (ssize_t) list->nodes[color].count; i++) sum_squared+=((MagickRealType) color)*((MagickRealType) color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; sum_squared/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum_squared-(sum*sum)); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static inline void InsertPixelList(const Image *image,const PixelPacket *pixel, const IndexPacket *indexes,PixelList *pixel_list) { size_t signature; unsigned short index; index=ScaleQuantumToShort(GetPixelRed(pixel)); signature=pixel_list->lists[0].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[0].nodes[index].count++; else AddNodePixelList(pixel_list,0,index); index=ScaleQuantumToShort(GetPixelGreen(pixel)); signature=pixel_list->lists[1].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[1].nodes[index].count++; else AddNodePixelList(pixel_list,1,index); index=ScaleQuantumToShort(GetPixelBlue(pixel)); signature=pixel_list->lists[2].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[2].nodes[index].count++; else AddNodePixelList(pixel_list,2,index); index=ScaleQuantumToShort(GetPixelOpacity(pixel)); signature=pixel_list->lists[3].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[3].nodes[index].count++; else AddNodePixelList(pixel_list,3,index); if (image->colorspace == CMYKColorspace) index=ScaleQuantumToShort(GetPixelIndex(indexes)); signature=pixel_list->lists[4].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[4].nodes[index].count++; else AddNodePixelList(pixel_list,4,index); } static void ResetPixelList(PixelList *pixel_list) { int level; register ListNode *root; register SkipList *list; register ssize_t channel; /* Reset the skip-list. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; root=list->nodes+65536UL; list->level=0; for (level=0; level < 9; level++) root->next[level]=65536UL; } pixel_list->seed=pixel_list->signature++; } MagickExport Image *StatisticImage(const Image *image,const StatisticType type, const size_t width,const size_t height,ExceptionInfo *exception) { Image *statistic_image; statistic_image=StatisticImageChannel(image,DefaultChannels,type,width, height,exception); return(statistic_image); } MagickExport Image *StatisticImageChannel(const Image *image, const ChannelType channel,const StatisticType type,const size_t width, const size_t height,ExceptionInfo *exception) { #define StatisticImageTag "Statistic/Image" CacheView *image_view, *statistic_view; Image *statistic_image; MagickBooleanType status; MagickOffsetType progress; PixelList **magick_restrict pixel_list; size_t neighbor_height, neighbor_width; ssize_t y; /* Initialize statistics image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); statistic_image=CloneImage(image,0,0,MagickTrue,exception); if (statistic_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(statistic_image,DirectClass) == MagickFalse) { InheritException(exception,&statistic_image->exception); statistic_image=DestroyImage(statistic_image); return((Image *) NULL); } neighbor_width=width == 0 ? GetOptimalKernelWidth2D((double) width,0.5) : width; neighbor_height=height == 0 ? GetOptimalKernelWidth2D((double) height,0.5) : height; pixel_list=AcquirePixelListThreadSet(neighbor_width,neighbor_height); if (pixel_list == (PixelList **) NULL) { statistic_image=DestroyImage(statistic_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Make each pixel the min / max / median / mode / etc. of the neighborhood. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); statistic_view=AcquireAuthenticCacheView(statistic_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,statistic_image,statistic_image->rows,1) #endif for (y=0; y < (ssize_t) statistic_image->rows; y++) { const int id = GetOpenMPThreadId(); register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict statistic_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) neighbor_width/2L),y- (ssize_t) (neighbor_height/2L),image->columns+neighbor_width, neighbor_height,exception); q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); statistic_indexes=GetCacheViewAuthenticIndexQueue(statistic_view); for (x=0; x < (ssize_t) statistic_image->columns; x++) { MagickPixelPacket pixel; register const IndexPacket *magick_restrict s; register const PixelPacket *magick_restrict r; register ssize_t u, v; r=p; s=indexes+x; ResetPixelList(pixel_list[id]); for (v=0; v < (ssize_t) neighbor_height; v++) { for (u=0; u < (ssize_t) neighbor_width; u++) InsertPixelList(image,r+u,s+u,pixel_list[id]); r+=image->columns+neighbor_width; s+=image->columns+neighbor_width; } GetMagickPixelPacket(image,&pixel); SetMagickPixelPacket(image,p+neighbor_width*neighbor_height/2,indexes+x+ neighbor_width*neighbor_height/2,&pixel); switch (type) { case GradientStatistic: { MagickPixelPacket maximum, minimum; GetMinimumPixelList(pixel_list[id],&pixel); minimum=pixel; GetMaximumPixelList(pixel_list[id],&pixel); maximum=pixel; pixel.red=MagickAbsoluteValue(maximum.red-minimum.red); pixel.green=MagickAbsoluteValue(maximum.green-minimum.green); pixel.blue=MagickAbsoluteValue(maximum.blue-minimum.blue); pixel.opacity=MagickAbsoluteValue(maximum.opacity-minimum.opacity); if (image->colorspace == CMYKColorspace) pixel.index=MagickAbsoluteValue(maximum.index-minimum.index); break; } case MaximumStatistic: { GetMaximumPixelList(pixel_list[id],&pixel); break; } case MeanStatistic: { GetMeanPixelList(pixel_list[id],&pixel); break; } case MedianStatistic: default: { GetMedianPixelList(pixel_list[id],&pixel); break; } case MinimumStatistic: { GetMinimumPixelList(pixel_list[id],&pixel); break; } case ModeStatistic: { GetModePixelList(pixel_list[id],&pixel); break; } case NonpeakStatistic: { GetNonpeakPixelList(pixel_list[id],&pixel); break; } case RootMeanSquareStatistic: { GetRootMeanSquarePixelList(pixel_list[id],&pixel); break; } case StandardDeviationStatistic: { GetStandardDeviationPixelList(pixel_list[id],&pixel); break; } } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(pixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(statistic_indexes+x,ClampToQuantum(pixel.index)); p++; q++; } if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,StatisticImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } statistic_view=DestroyCacheView(statistic_view); image_view=DestroyCacheView(image_view); pixel_list=DestroyPixelListThreadSet(pixel_list); if (status == MagickFalse) statistic_image=DestroyImage(statistic_image); return(statistic_image); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_941_0
crossvul-cpp_data_good_2036_0
/* * Fast Userspace Mutexes (which I call "Futexes!"). * (C) Rusty Russell, IBM 2002 * * Generalized futexes, futex requeueing, misc fixes by Ingo Molnar * (C) Copyright 2003 Red Hat Inc, All Rights Reserved * * Removed page pinning, fix privately mapped COW pages and other cleanups * (C) Copyright 2003, 2004 Jamie Lokier * * Robust futex support started by Ingo Molnar * (C) Copyright 2006 Red Hat Inc, All Rights Reserved * Thanks to Thomas Gleixner for suggestions, analysis and fixes. * * PI-futex support started by Ingo Molnar and Thomas Gleixner * Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com> * Copyright (C) 2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com> * * PRIVATE futexes by Eric Dumazet * Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com> * * Requeue-PI support by Darren Hart <dvhltc@us.ibm.com> * Copyright (C) IBM Corporation, 2009 * Thanks to Thomas Gleixner for conceptual design and careful reviews. * * Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly * enough at me, Linus for the original (flawed) idea, Matthew * Kirkwood for proof-of-concept implementation. * * "The futexes are also cursed." * "But they come in a choice of three flavours!" * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/slab.h> #include <linux/poll.h> #include <linux/fs.h> #include <linux/file.h> #include <linux/jhash.h> #include <linux/init.h> #include <linux/futex.h> #include <linux/mount.h> #include <linux/pagemap.h> #include <linux/syscalls.h> #include <linux/signal.h> #include <linux/module.h> #include <linux/magic.h> #include <linux/pid.h> #include <linux/nsproxy.h> #include <asm/futex.h> #include "rtmutex_common.h" int __read_mostly futex_cmpxchg_enabled; #define FUTEX_HASHBITS (CONFIG_BASE_SMALL ? 4 : 8) /* * Priority Inheritance state: */ struct futex_pi_state { /* * list of 'owned' pi_state instances - these have to be * cleaned up in do_exit() if the task exits prematurely: */ struct list_head list; /* * The PI object: */ struct rt_mutex pi_mutex; struct task_struct *owner; atomic_t refcount; union futex_key key; }; /** * struct futex_q - The hashed futex queue entry, one per waiting task * @task: the task waiting on the futex * @lock_ptr: the hash bucket lock * @key: the key the futex is hashed on * @pi_state: optional priority inheritance state * @rt_waiter: rt_waiter storage for use with requeue_pi * @requeue_pi_key: the requeue_pi target futex key * @bitset: bitset for the optional bitmasked wakeup * * We use this hashed waitqueue, instead of a normal wait_queue_t, so * we can wake only the relevant ones (hashed queues may be shared). * * A futex_q has a woken state, just like tasks have TASK_RUNNING. * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0. * The order of wakup is always to make the first condition true, then * the second. * * PI futexes are typically woken before they are removed from the hash list via * the rt_mutex code. See unqueue_me_pi(). */ struct futex_q { struct plist_node list; struct task_struct *task; spinlock_t *lock_ptr; union futex_key key; struct futex_pi_state *pi_state; struct rt_mutex_waiter *rt_waiter; union futex_key *requeue_pi_key; u32 bitset; }; /* * Hash buckets are shared by all the futex_keys that hash to the same * location. Each key may have multiple futex_q structures, one for each task * waiting on a futex. */ struct futex_hash_bucket { spinlock_t lock; struct plist_head chain; }; static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS]; /* * We hash on the keys returned from get_futex_key (see below). */ static struct futex_hash_bucket *hash_futex(union futex_key *key) { u32 hash = jhash2((u32*)&key->both.word, (sizeof(key->both.word)+sizeof(key->both.ptr))/4, key->both.offset); return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)]; } /* * Return 1 if two futex_keys are equal, 0 otherwise. */ static inline int match_futex(union futex_key *key1, union futex_key *key2) { return (key1 && key2 && key1->both.word == key2->both.word && key1->both.ptr == key2->both.ptr && key1->both.offset == key2->both.offset); } /* * Take a reference to the resource addressed by a key. * Can be called while holding spinlocks. * */ static void get_futex_key_refs(union futex_key *key) { if (!key->both.ptr) return; switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) { case FUT_OFF_INODE: atomic_inc(&key->shared.inode->i_count); break; case FUT_OFF_MMSHARED: atomic_inc(&key->private.mm->mm_count); break; } } /* * Drop a reference to the resource addressed by a key. * The hash bucket spinlock must not be held. */ static void drop_futex_key_refs(union futex_key *key) { if (!key->both.ptr) { /* If we're here then we tried to put a key we failed to get */ WARN_ON_ONCE(1); return; } switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) { case FUT_OFF_INODE: iput(key->shared.inode); break; case FUT_OFF_MMSHARED: mmdrop(key->private.mm); break; } } /** * get_futex_key() - Get parameters which are the keys for a futex * @uaddr: virtual address of the futex * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED * @key: address where result is stored. * * Returns a negative error code or 0 * The key words are stored in *key on success. * * For shared mappings, it's (page->index, vma->vm_file->f_path.dentry->d_inode, * offset_within_page). For private mappings, it's (uaddr, current->mm). * We can usually work out the index without swapping in the page. * * lock_page() might sleep, the caller should not hold a spinlock. */ static int get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key) { unsigned long address = (unsigned long)uaddr; struct mm_struct *mm = current->mm; struct page *page; int err; /* * The futex address must be "naturally" aligned. */ key->both.offset = address % PAGE_SIZE; if (unlikely((address % sizeof(u32)) != 0)) return -EINVAL; address -= key->both.offset; /* * PROCESS_PRIVATE futexes are fast. * As the mm cannot disappear under us and the 'key' only needs * virtual address, we dont even have to find the underlying vma. * Note : We do have to check 'uaddr' is a valid user address, * but access_ok() should be faster than find_vma() */ if (!fshared) { if (unlikely(!access_ok(VERIFY_WRITE, uaddr, sizeof(u32)))) return -EFAULT; key->private.mm = mm; key->private.address = address; get_futex_key_refs(key); return 0; } again: err = get_user_pages_fast(address, 1, 1, &page); if (err < 0) return err; page = compound_head(page); lock_page(page); if (!page->mapping) { unlock_page(page); put_page(page); goto again; } /* * Private mappings are handled in a simple way. * * NOTE: When userspace waits on a MAP_SHARED mapping, even if * it's a read-only handle, it's expected that futexes attach to * the object not the particular process. */ if (PageAnon(page)) { key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */ key->private.mm = mm; key->private.address = address; } else { key->both.offset |= FUT_OFF_INODE; /* inode-based key */ key->shared.inode = page->mapping->host; key->shared.pgoff = page->index; } get_futex_key_refs(key); unlock_page(page); put_page(page); return 0; } static inline void put_futex_key(int fshared, union futex_key *key) { drop_futex_key_refs(key); } /** * fault_in_user_writeable() - Fault in user address and verify RW access * @uaddr: pointer to faulting user space address * * Slow path to fixup the fault we just took in the atomic write * access to @uaddr. * * We have no generic implementation of a non destructive write to the * user address. We know that we faulted in the atomic pagefault * disabled section so we can as well avoid the #PF overhead by * calling get_user_pages() right away. */ static int fault_in_user_writeable(u32 __user *uaddr) { struct mm_struct *mm = current->mm; int ret; down_read(&mm->mmap_sem); ret = get_user_pages(current, mm, (unsigned long)uaddr, 1, 1, 0, NULL, NULL); up_read(&mm->mmap_sem); return ret < 0 ? ret : 0; } /** * futex_top_waiter() - Return the highest priority waiter on a futex * @hb: the hash bucket the futex_q's reside in * @key: the futex key (to distinguish it from other futex futex_q's) * * Must be called with the hb lock held. */ static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb, union futex_key *key) { struct futex_q *this; plist_for_each_entry(this, &hb->chain, list) { if (match_futex(&this->key, key)) return this; } return NULL; } static u32 cmpxchg_futex_value_locked(u32 __user *uaddr, u32 uval, u32 newval) { u32 curval; pagefault_disable(); curval = futex_atomic_cmpxchg_inatomic(uaddr, uval, newval); pagefault_enable(); return curval; } static int get_futex_value_locked(u32 *dest, u32 __user *from) { int ret; pagefault_disable(); ret = __copy_from_user_inatomic(dest, from, sizeof(u32)); pagefault_enable(); return ret ? -EFAULT : 0; } /* * PI code: */ static int refill_pi_state_cache(void) { struct futex_pi_state *pi_state; if (likely(current->pi_state_cache)) return 0; pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL); if (!pi_state) return -ENOMEM; INIT_LIST_HEAD(&pi_state->list); /* pi_mutex gets initialized later */ pi_state->owner = NULL; atomic_set(&pi_state->refcount, 1); pi_state->key = FUTEX_KEY_INIT; current->pi_state_cache = pi_state; return 0; } static struct futex_pi_state * alloc_pi_state(void) { struct futex_pi_state *pi_state = current->pi_state_cache; WARN_ON(!pi_state); current->pi_state_cache = NULL; return pi_state; } static void free_pi_state(struct futex_pi_state *pi_state) { if (!atomic_dec_and_test(&pi_state->refcount)) return; /* * If pi_state->owner is NULL, the owner is most probably dying * and has cleaned up the pi_state already */ if (pi_state->owner) { raw_spin_lock_irq(&pi_state->owner->pi_lock); list_del_init(&pi_state->list); raw_spin_unlock_irq(&pi_state->owner->pi_lock); rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner); } if (current->pi_state_cache) kfree(pi_state); else { /* * pi_state->list is already empty. * clear pi_state->owner. * refcount is at 0 - put it back to 1. */ pi_state->owner = NULL; atomic_set(&pi_state->refcount, 1); current->pi_state_cache = pi_state; } } /* * Look up the task based on what TID userspace gave us. * We dont trust it. */ static struct task_struct * futex_find_get_task(pid_t pid) { struct task_struct *p; rcu_read_lock(); p = find_task_by_vpid(pid); if (p) get_task_struct(p); rcu_read_unlock(); return p; } /* * This task is holding PI mutexes at exit time => bad. * Kernel cleans up PI-state, but userspace is likely hosed. * (Robust-futex cleanup is separate and might save the day for userspace.) */ void exit_pi_state_list(struct task_struct *curr) { struct list_head *next, *head = &curr->pi_state_list; struct futex_pi_state *pi_state; struct futex_hash_bucket *hb; union futex_key key = FUTEX_KEY_INIT; if (!futex_cmpxchg_enabled) return; /* * We are a ZOMBIE and nobody can enqueue itself on * pi_state_list anymore, but we have to be careful * versus waiters unqueueing themselves: */ raw_spin_lock_irq(&curr->pi_lock); while (!list_empty(head)) { next = head->next; pi_state = list_entry(next, struct futex_pi_state, list); key = pi_state->key; hb = hash_futex(&key); raw_spin_unlock_irq(&curr->pi_lock); spin_lock(&hb->lock); raw_spin_lock_irq(&curr->pi_lock); /* * We dropped the pi-lock, so re-check whether this * task still owns the PI-state: */ if (head->next != next) { spin_unlock(&hb->lock); continue; } WARN_ON(pi_state->owner != curr); WARN_ON(list_empty(&pi_state->list)); list_del_init(&pi_state->list); pi_state->owner = NULL; raw_spin_unlock_irq(&curr->pi_lock); rt_mutex_unlock(&pi_state->pi_mutex); spin_unlock(&hb->lock); raw_spin_lock_irq(&curr->pi_lock); } raw_spin_unlock_irq(&curr->pi_lock); } static int lookup_pi_state(u32 uval, struct futex_hash_bucket *hb, union futex_key *key, struct futex_pi_state **ps) { struct futex_pi_state *pi_state = NULL; struct futex_q *this, *next; struct plist_head *head; struct task_struct *p; pid_t pid = uval & FUTEX_TID_MASK; head = &hb->chain; plist_for_each_entry_safe(this, next, head, list) { if (match_futex(&this->key, key)) { /* * Another waiter already exists - bump up * the refcount and return its pi_state: */ pi_state = this->pi_state; /* * Userspace might have messed up non PI and PI futexes */ if (unlikely(!pi_state)) return -EINVAL; WARN_ON(!atomic_read(&pi_state->refcount)); /* * When pi_state->owner is NULL then the owner died * and another waiter is on the fly. pi_state->owner * is fixed up by the task which acquires * pi_state->rt_mutex. * * We do not check for pid == 0 which can happen when * the owner died and robust_list_exit() cleared the * TID. */ if (pid && pi_state->owner) { /* * Bail out if user space manipulated the * futex value. */ if (pid != task_pid_vnr(pi_state->owner)) return -EINVAL; } atomic_inc(&pi_state->refcount); *ps = pi_state; return 0; } } /* * We are the first waiter - try to look up the real owner and attach * the new pi_state to it, but bail out when TID = 0 */ if (!pid) return -ESRCH; p = futex_find_get_task(pid); if (!p) return -ESRCH; /* * We need to look at the task state flags to figure out, * whether the task is exiting. To protect against the do_exit * change of the task flags, we do this protected by * p->pi_lock: */ raw_spin_lock_irq(&p->pi_lock); if (unlikely(p->flags & PF_EXITING)) { /* * The task is on the way out. When PF_EXITPIDONE is * set, we know that the task has finished the * cleanup: */ int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN; raw_spin_unlock_irq(&p->pi_lock); put_task_struct(p); return ret; } pi_state = alloc_pi_state(); /* * Initialize the pi_mutex in locked state and make 'p' * the owner of it: */ rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p); /* Store the key for possible exit cleanups: */ pi_state->key = *key; WARN_ON(!list_empty(&pi_state->list)); list_add(&pi_state->list, &p->pi_state_list); pi_state->owner = p; raw_spin_unlock_irq(&p->pi_lock); put_task_struct(p); *ps = pi_state; return 0; } /** * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex * @uaddr: the pi futex user address * @hb: the pi futex hash bucket * @key: the futex key associated with uaddr and hb * @ps: the pi_state pointer where we store the result of the * lookup * @task: the task to perform the atomic lock work for. This will * be "current" except in the case of requeue pi. * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0) * * Returns: * 0 - ready to wait * 1 - acquired the lock * <0 - error * * The hb->lock and futex_key refs shall be held by the caller. */ static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb, union futex_key *key, struct futex_pi_state **ps, struct task_struct *task, int set_waiters) { int lock_taken, ret, ownerdied = 0; u32 uval, newval, curval; retry: ret = lock_taken = 0; /* * To avoid races, we attempt to take the lock here again * (by doing a 0 -> TID atomic cmpxchg), while holding all * the locks. It will most likely not succeed. */ newval = task_pid_vnr(task); if (set_waiters) newval |= FUTEX_WAITERS; curval = cmpxchg_futex_value_locked(uaddr, 0, newval); if (unlikely(curval == -EFAULT)) return -EFAULT; /* * Detect deadlocks. */ if ((unlikely((curval & FUTEX_TID_MASK) == task_pid_vnr(task)))) return -EDEADLK; /* * Surprise - we got the lock. Just return to userspace: */ if (unlikely(!curval)) return 1; uval = curval; /* * Set the FUTEX_WAITERS flag, so the owner will know it has someone * to wake at the next unlock. */ newval = curval | FUTEX_WAITERS; /* * There are two cases, where a futex might have no owner (the * owner TID is 0): OWNER_DIED. We take over the futex in this * case. We also do an unconditional take over, when the owner * of the futex died. * * This is safe as we are protected by the hash bucket lock ! */ if (unlikely(ownerdied || !(curval & FUTEX_TID_MASK))) { /* Keep the OWNER_DIED bit */ newval = (curval & ~FUTEX_TID_MASK) | task_pid_vnr(task); ownerdied = 0; lock_taken = 1; } curval = cmpxchg_futex_value_locked(uaddr, uval, newval); if (unlikely(curval == -EFAULT)) return -EFAULT; if (unlikely(curval != uval)) goto retry; /* * We took the lock due to owner died take over. */ if (unlikely(lock_taken)) return 1; /* * We dont have the lock. Look up the PI state (or create it if * we are the first waiter): */ ret = lookup_pi_state(uval, hb, key, ps); if (unlikely(ret)) { switch (ret) { case -ESRCH: /* * No owner found for this futex. Check if the * OWNER_DIED bit is set to figure out whether * this is a robust futex or not. */ if (get_futex_value_locked(&curval, uaddr)) return -EFAULT; /* * We simply start over in case of a robust * futex. The code above will take the futex * and return happy. */ if (curval & FUTEX_OWNER_DIED) { ownerdied = 1; goto retry; } default: break; } } return ret; } /* * The hash bucket lock must be held when this is called. * Afterwards, the futex_q must not be accessed. */ static void wake_futex(struct futex_q *q) { struct task_struct *p = q->task; /* * We set q->lock_ptr = NULL _before_ we wake up the task. If * a non futex wake up happens on another CPU then the task * might exit and p would dereference a non existing task * struct. Prevent this by holding a reference on p across the * wake up. */ get_task_struct(p); plist_del(&q->list, &q->list.plist); /* * The waiting task can free the futex_q as soon as * q->lock_ptr = NULL is written, without taking any locks. A * memory barrier is required here to prevent the following * store to lock_ptr from getting ahead of the plist_del. */ smp_wmb(); q->lock_ptr = NULL; wake_up_state(p, TASK_NORMAL); put_task_struct(p); } static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this) { struct task_struct *new_owner; struct futex_pi_state *pi_state = this->pi_state; u32 curval, newval; if (!pi_state) return -EINVAL; /* * If current does not own the pi_state then the futex is * inconsistent and user space fiddled with the futex value. */ if (pi_state->owner != current) return -EINVAL; raw_spin_lock(&pi_state->pi_mutex.wait_lock); new_owner = rt_mutex_next_owner(&pi_state->pi_mutex); /* * This happens when we have stolen the lock and the original * pending owner did not enqueue itself back on the rt_mutex. * Thats not a tragedy. We know that way, that a lock waiter * is on the fly. We make the futex_q waiter the pending owner. */ if (!new_owner) new_owner = this->task; /* * We pass it to the next owner. (The WAITERS bit is always * kept enabled while there is PI state around. We must also * preserve the owner died bit.) */ if (!(uval & FUTEX_OWNER_DIED)) { int ret = 0; newval = FUTEX_WAITERS | task_pid_vnr(new_owner); curval = cmpxchg_futex_value_locked(uaddr, uval, newval); if (curval == -EFAULT) ret = -EFAULT; else if (curval != uval) ret = -EINVAL; if (ret) { raw_spin_unlock(&pi_state->pi_mutex.wait_lock); return ret; } } raw_spin_lock_irq(&pi_state->owner->pi_lock); WARN_ON(list_empty(&pi_state->list)); list_del_init(&pi_state->list); raw_spin_unlock_irq(&pi_state->owner->pi_lock); raw_spin_lock_irq(&new_owner->pi_lock); WARN_ON(!list_empty(&pi_state->list)); list_add(&pi_state->list, &new_owner->pi_state_list); pi_state->owner = new_owner; raw_spin_unlock_irq(&new_owner->pi_lock); raw_spin_unlock(&pi_state->pi_mutex.wait_lock); rt_mutex_unlock(&pi_state->pi_mutex); return 0; } static int unlock_futex_pi(u32 __user *uaddr, u32 uval) { u32 oldval; /* * There is no waiter, so we unlock the futex. The owner died * bit has not to be preserved here. We are the owner: */ oldval = cmpxchg_futex_value_locked(uaddr, uval, 0); if (oldval == -EFAULT) return oldval; if (oldval != uval) return -EAGAIN; return 0; } /* * Express the locking dependencies for lockdep: */ static inline void double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2) { if (hb1 <= hb2) { spin_lock(&hb1->lock); if (hb1 < hb2) spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING); } else { /* hb1 > hb2 */ spin_lock(&hb2->lock); spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING); } } static inline void double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2) { spin_unlock(&hb1->lock); if (hb1 != hb2) spin_unlock(&hb2->lock); } /* * Wake up waiters matching bitset queued on this futex (uaddr). */ static int futex_wake(u32 __user *uaddr, int fshared, int nr_wake, u32 bitset) { struct futex_hash_bucket *hb; struct futex_q *this, *next; struct plist_head *head; union futex_key key = FUTEX_KEY_INIT; int ret; if (!bitset) return -EINVAL; ret = get_futex_key(uaddr, fshared, &key); if (unlikely(ret != 0)) goto out; hb = hash_futex(&key); spin_lock(&hb->lock); head = &hb->chain; plist_for_each_entry_safe(this, next, head, list) { if (match_futex (&this->key, &key)) { if (this->pi_state || this->rt_waiter) { ret = -EINVAL; break; } /* Check if one of the bits is set in both bitsets */ if (!(this->bitset & bitset)) continue; wake_futex(this); if (++ret >= nr_wake) break; } } spin_unlock(&hb->lock); put_futex_key(fshared, &key); out: return ret; } /* * Wake up all waiters hashed on the physical page that is mapped * to this virtual address: */ static int futex_wake_op(u32 __user *uaddr1, int fshared, u32 __user *uaddr2, int nr_wake, int nr_wake2, int op) { union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT; struct futex_hash_bucket *hb1, *hb2; struct plist_head *head; struct futex_q *this, *next; int ret, op_ret; retry: ret = get_futex_key(uaddr1, fshared, &key1); if (unlikely(ret != 0)) goto out; ret = get_futex_key(uaddr2, fshared, &key2); if (unlikely(ret != 0)) goto out_put_key1; hb1 = hash_futex(&key1); hb2 = hash_futex(&key2); retry_private: double_lock_hb(hb1, hb2); op_ret = futex_atomic_op_inuser(op, uaddr2); if (unlikely(op_ret < 0)) { double_unlock_hb(hb1, hb2); #ifndef CONFIG_MMU /* * we don't get EFAULT from MMU faults if we don't have an MMU, * but we might get them from range checking */ ret = op_ret; goto out_put_keys; #endif if (unlikely(op_ret != -EFAULT)) { ret = op_ret; goto out_put_keys; } ret = fault_in_user_writeable(uaddr2); if (ret) goto out_put_keys; if (!fshared) goto retry_private; put_futex_key(fshared, &key2); put_futex_key(fshared, &key1); goto retry; } head = &hb1->chain; plist_for_each_entry_safe(this, next, head, list) { if (match_futex (&this->key, &key1)) { wake_futex(this); if (++ret >= nr_wake) break; } } if (op_ret > 0) { head = &hb2->chain; op_ret = 0; plist_for_each_entry_safe(this, next, head, list) { if (match_futex (&this->key, &key2)) { wake_futex(this); if (++op_ret >= nr_wake2) break; } } ret += op_ret; } double_unlock_hb(hb1, hb2); out_put_keys: put_futex_key(fshared, &key2); out_put_key1: put_futex_key(fshared, &key1); out: return ret; } /** * requeue_futex() - Requeue a futex_q from one hb to another * @q: the futex_q to requeue * @hb1: the source hash_bucket * @hb2: the target hash_bucket * @key2: the new key for the requeued futex_q */ static inline void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2, union futex_key *key2) { /* * If key1 and key2 hash to the same bucket, no need to * requeue. */ if (likely(&hb1->chain != &hb2->chain)) { plist_del(&q->list, &hb1->chain); plist_add(&q->list, &hb2->chain); q->lock_ptr = &hb2->lock; #ifdef CONFIG_DEBUG_PI_LIST q->list.plist.spinlock = &hb2->lock; #endif } get_futex_key_refs(key2); q->key = *key2; } /** * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue * @q: the futex_q * @key: the key of the requeue target futex * @hb: the hash_bucket of the requeue target futex * * During futex_requeue, with requeue_pi=1, it is possible to acquire the * target futex if it is uncontended or via a lock steal. Set the futex_q key * to the requeue target futex so the waiter can detect the wakeup on the right * futex, but remove it from the hb and NULL the rt_waiter so it can detect * atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock * to protect access to the pi_state to fixup the owner later. Must be called * with both q->lock_ptr and hb->lock held. */ static inline void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key, struct futex_hash_bucket *hb) { get_futex_key_refs(key); q->key = *key; WARN_ON(plist_node_empty(&q->list)); plist_del(&q->list, &q->list.plist); WARN_ON(!q->rt_waiter); q->rt_waiter = NULL; q->lock_ptr = &hb->lock; #ifdef CONFIG_DEBUG_PI_LIST q->list.plist.spinlock = &hb->lock; #endif wake_up_state(q->task, TASK_NORMAL); } /** * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter * @pifutex: the user address of the to futex * @hb1: the from futex hash bucket, must be locked by the caller * @hb2: the to futex hash bucket, must be locked by the caller * @key1: the from futex key * @key2: the to futex key * @ps: address to store the pi_state pointer * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0) * * Try and get the lock on behalf of the top waiter if we can do it atomically. * Wake the top waiter if we succeed. If the caller specified set_waiters, * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit. * hb1 and hb2 must be held by the caller. * * Returns: * 0 - failed to acquire the lock atomicly * 1 - acquired the lock * <0 - error */ static int futex_proxy_trylock_atomic(u32 __user *pifutex, struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2, union futex_key *key1, union futex_key *key2, struct futex_pi_state **ps, int set_waiters) { struct futex_q *top_waiter = NULL; u32 curval; int ret; if (get_futex_value_locked(&curval, pifutex)) return -EFAULT; /* * Find the top_waiter and determine if there are additional waiters. * If the caller intends to requeue more than 1 waiter to pifutex, * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now, * as we have means to handle the possible fault. If not, don't set * the bit unecessarily as it will force the subsequent unlock to enter * the kernel. */ top_waiter = futex_top_waiter(hb1, key1); /* There are no waiters, nothing for us to do. */ if (!top_waiter) return 0; /* Ensure we requeue to the expected futex. */ if (!match_futex(top_waiter->requeue_pi_key, key2)) return -EINVAL; /* * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in * the contended case or if set_waiters is 1. The pi_state is returned * in ps in contended cases. */ ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task, set_waiters); if (ret == 1) requeue_pi_wake_futex(top_waiter, key2, hb2); return ret; } /** * futex_requeue() - Requeue waiters from uaddr1 to uaddr2 * uaddr1: source futex user address * uaddr2: target futex user address * nr_wake: number of waiters to wake (must be 1 for requeue_pi) * nr_requeue: number of waiters to requeue (0-INT_MAX) * requeue_pi: if we are attempting to requeue from a non-pi futex to a * pi futex (pi to pi requeue is not supported) * * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire * uaddr2 atomically on behalf of the top waiter. * * Returns: * >=0 - on success, the number of tasks requeued or woken * <0 - on error */ static int futex_requeue(u32 __user *uaddr1, int fshared, u32 __user *uaddr2, int nr_wake, int nr_requeue, u32 *cmpval, int requeue_pi) { union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT; int drop_count = 0, task_count = 0, ret; struct futex_pi_state *pi_state = NULL; struct futex_hash_bucket *hb1, *hb2; struct plist_head *head1; struct futex_q *this, *next; u32 curval2; if (requeue_pi) { /* * requeue_pi requires a pi_state, try to allocate it now * without any locks in case it fails. */ if (refill_pi_state_cache()) return -ENOMEM; /* * requeue_pi must wake as many tasks as it can, up to nr_wake * + nr_requeue, since it acquires the rt_mutex prior to * returning to userspace, so as to not leave the rt_mutex with * waiters and no owner. However, second and third wake-ups * cannot be predicted as they involve race conditions with the * first wake and a fault while looking up the pi_state. Both * pthread_cond_signal() and pthread_cond_broadcast() should * use nr_wake=1. */ if (nr_wake != 1) return -EINVAL; } retry: if (pi_state != NULL) { /* * We will have to lookup the pi_state again, so free this one * to keep the accounting correct. */ free_pi_state(pi_state); pi_state = NULL; } ret = get_futex_key(uaddr1, fshared, &key1); if (unlikely(ret != 0)) goto out; ret = get_futex_key(uaddr2, fshared, &key2); if (unlikely(ret != 0)) goto out_put_key1; hb1 = hash_futex(&key1); hb2 = hash_futex(&key2); retry_private: double_lock_hb(hb1, hb2); if (likely(cmpval != NULL)) { u32 curval; ret = get_futex_value_locked(&curval, uaddr1); if (unlikely(ret)) { double_unlock_hb(hb1, hb2); ret = get_user(curval, uaddr1); if (ret) goto out_put_keys; if (!fshared) goto retry_private; put_futex_key(fshared, &key2); put_futex_key(fshared, &key1); goto retry; } if (curval != *cmpval) { ret = -EAGAIN; goto out_unlock; } } if (requeue_pi && (task_count - nr_wake < nr_requeue)) { /* * Attempt to acquire uaddr2 and wake the top waiter. If we * intend to requeue waiters, force setting the FUTEX_WAITERS * bit. We force this here where we are able to easily handle * faults rather in the requeue loop below. */ ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1, &key2, &pi_state, nr_requeue); /* * At this point the top_waiter has either taken uaddr2 or is * waiting on it. If the former, then the pi_state will not * exist yet, look it up one more time to ensure we have a * reference to it. */ if (ret == 1) { WARN_ON(pi_state); drop_count++; task_count++; ret = get_futex_value_locked(&curval2, uaddr2); if (!ret) ret = lookup_pi_state(curval2, hb2, &key2, &pi_state); } switch (ret) { case 0: break; case -EFAULT: double_unlock_hb(hb1, hb2); put_futex_key(fshared, &key2); put_futex_key(fshared, &key1); ret = fault_in_user_writeable(uaddr2); if (!ret) goto retry; goto out; case -EAGAIN: /* The owner was exiting, try again. */ double_unlock_hb(hb1, hb2); put_futex_key(fshared, &key2); put_futex_key(fshared, &key1); cond_resched(); goto retry; default: goto out_unlock; } } head1 = &hb1->chain; plist_for_each_entry_safe(this, next, head1, list) { if (task_count - nr_wake >= nr_requeue) break; if (!match_futex(&this->key, &key1)) continue; /* * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always * be paired with each other and no other futex ops. */ if ((requeue_pi && !this->rt_waiter) || (!requeue_pi && this->rt_waiter)) { ret = -EINVAL; break; } /* * Wake nr_wake waiters. For requeue_pi, if we acquired the * lock, we already woke the top_waiter. If not, it will be * woken by futex_unlock_pi(). */ if (++task_count <= nr_wake && !requeue_pi) { wake_futex(this); continue; } /* Ensure we requeue to the expected futex for requeue_pi. */ if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) { ret = -EINVAL; break; } /* * Requeue nr_requeue waiters and possibly one more in the case * of requeue_pi if we couldn't acquire the lock atomically. */ if (requeue_pi) { /* Prepare the waiter to take the rt_mutex. */ atomic_inc(&pi_state->refcount); this->pi_state = pi_state; ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex, this->rt_waiter, this->task, 1); if (ret == 1) { /* We got the lock. */ requeue_pi_wake_futex(this, &key2, hb2); drop_count++; continue; } else if (ret) { /* -EDEADLK */ this->pi_state = NULL; free_pi_state(pi_state); goto out_unlock; } } requeue_futex(this, hb1, hb2, &key2); drop_count++; } out_unlock: double_unlock_hb(hb1, hb2); /* * drop_futex_key_refs() must be called outside the spinlocks. During * the requeue we moved futex_q's from the hash bucket at key1 to the * one at key2 and updated their key pointer. We no longer need to * hold the references to key1. */ while (--drop_count >= 0) drop_futex_key_refs(&key1); out_put_keys: put_futex_key(fshared, &key2); out_put_key1: put_futex_key(fshared, &key1); out: if (pi_state != NULL) free_pi_state(pi_state); return ret ? ret : task_count; } /* The key must be already stored in q->key. */ static inline struct futex_hash_bucket *queue_lock(struct futex_q *q) { struct futex_hash_bucket *hb; hb = hash_futex(&q->key); q->lock_ptr = &hb->lock; spin_lock(&hb->lock); return hb; } static inline void queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb) { spin_unlock(&hb->lock); } /** * queue_me() - Enqueue the futex_q on the futex_hash_bucket * @q: The futex_q to enqueue * @hb: The destination hash bucket * * The hb->lock must be held by the caller, and is released here. A call to * queue_me() is typically paired with exactly one call to unqueue_me(). The * exceptions involve the PI related operations, which may use unqueue_me_pi() * or nothing if the unqueue is done as part of the wake process and the unqueue * state is implicit in the state of woken task (see futex_wait_requeue_pi() for * an example). */ static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb) { int prio; /* * The priority used to register this element is * - either the real thread-priority for the real-time threads * (i.e. threads with a priority lower than MAX_RT_PRIO) * - or MAX_RT_PRIO for non-RT threads. * Thus, all RT-threads are woken first in priority order, and * the others are woken last, in FIFO order. */ prio = min(current->normal_prio, MAX_RT_PRIO); plist_node_init(&q->list, prio); #ifdef CONFIG_DEBUG_PI_LIST q->list.plist.spinlock = &hb->lock; #endif plist_add(&q->list, &hb->chain); q->task = current; spin_unlock(&hb->lock); } /** * unqueue_me() - Remove the futex_q from its futex_hash_bucket * @q: The futex_q to unqueue * * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must * be paired with exactly one earlier call to queue_me(). * * Returns: * 1 - if the futex_q was still queued (and we removed unqueued it) * 0 - if the futex_q was already removed by the waking thread */ static int unqueue_me(struct futex_q *q) { spinlock_t *lock_ptr; int ret = 0; /* In the common case we don't take the spinlock, which is nice. */ retry: lock_ptr = q->lock_ptr; barrier(); if (lock_ptr != NULL) { spin_lock(lock_ptr); /* * q->lock_ptr can change between reading it and * spin_lock(), causing us to take the wrong lock. This * corrects the race condition. * * Reasoning goes like this: if we have the wrong lock, * q->lock_ptr must have changed (maybe several times) * between reading it and the spin_lock(). It can * change again after the spin_lock() but only if it was * already changed before the spin_lock(). It cannot, * however, change back to the original value. Therefore * we can detect whether we acquired the correct lock. */ if (unlikely(lock_ptr != q->lock_ptr)) { spin_unlock(lock_ptr); goto retry; } WARN_ON(plist_node_empty(&q->list)); plist_del(&q->list, &q->list.plist); BUG_ON(q->pi_state); spin_unlock(lock_ptr); ret = 1; } drop_futex_key_refs(&q->key); return ret; } /* * PI futexes can not be requeued and must remove themself from the * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry * and dropped here. */ static void unqueue_me_pi(struct futex_q *q) { WARN_ON(plist_node_empty(&q->list)); plist_del(&q->list, &q->list.plist); BUG_ON(!q->pi_state); free_pi_state(q->pi_state); q->pi_state = NULL; spin_unlock(q->lock_ptr); } /* * Fixup the pi_state owner with the new owner. * * Must be called with hash bucket lock held and mm->sem held for non * private futexes. */ static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q, struct task_struct *newowner, int fshared) { u32 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS; struct futex_pi_state *pi_state = q->pi_state; struct task_struct *oldowner = pi_state->owner; u32 uval, curval, newval; int ret; /* Owner died? */ if (!pi_state->owner) newtid |= FUTEX_OWNER_DIED; /* * We are here either because we stole the rtmutex from the * pending owner or we are the pending owner which failed to * get the rtmutex. We have to replace the pending owner TID * in the user space variable. This must be atomic as we have * to preserve the owner died bit here. * * Note: We write the user space value _before_ changing the pi_state * because we can fault here. Imagine swapped out pages or a fork * that marked all the anonymous memory readonly for cow. * * Modifying pi_state _before_ the user space value would * leave the pi_state in an inconsistent state when we fault * here, because we need to drop the hash bucket lock to * handle the fault. This might be observed in the PID check * in lookup_pi_state. */ retry: if (get_futex_value_locked(&uval, uaddr)) goto handle_fault; while (1) { newval = (uval & FUTEX_OWNER_DIED) | newtid; curval = cmpxchg_futex_value_locked(uaddr, uval, newval); if (curval == -EFAULT) goto handle_fault; if (curval == uval) break; uval = curval; } /* * We fixed up user space. Now we need to fix the pi_state * itself. */ if (pi_state->owner != NULL) { raw_spin_lock_irq(&pi_state->owner->pi_lock); WARN_ON(list_empty(&pi_state->list)); list_del_init(&pi_state->list); raw_spin_unlock_irq(&pi_state->owner->pi_lock); } pi_state->owner = newowner; raw_spin_lock_irq(&newowner->pi_lock); WARN_ON(!list_empty(&pi_state->list)); list_add(&pi_state->list, &newowner->pi_state_list); raw_spin_unlock_irq(&newowner->pi_lock); return 0; /* * To handle the page fault we need to drop the hash bucket * lock here. That gives the other task (either the pending * owner itself or the task which stole the rtmutex) the * chance to try the fixup of the pi_state. So once we are * back from handling the fault we need to check the pi_state * after reacquiring the hash bucket lock and before trying to * do another fixup. When the fixup has been done already we * simply return. */ handle_fault: spin_unlock(q->lock_ptr); ret = fault_in_user_writeable(uaddr); spin_lock(q->lock_ptr); /* * Check if someone else fixed it for us: */ if (pi_state->owner != oldowner) return 0; if (ret) return ret; goto retry; } /* * In case we must use restart_block to restart a futex_wait, * we encode in the 'flags' shared capability */ #define FLAGS_SHARED 0x01 #define FLAGS_CLOCKRT 0x02 #define FLAGS_HAS_TIMEOUT 0x04 static long futex_wait_restart(struct restart_block *restart); /** * fixup_owner() - Post lock pi_state and corner case management * @uaddr: user address of the futex * @fshared: whether the futex is shared (1) or not (0) * @q: futex_q (contains pi_state and access to the rt_mutex) * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0) * * After attempting to lock an rt_mutex, this function is called to cleanup * the pi_state owner as well as handle race conditions that may allow us to * acquire the lock. Must be called with the hb lock held. * * Returns: * 1 - success, lock taken * 0 - success, lock not taken * <0 - on error (-EFAULT) */ static int fixup_owner(u32 __user *uaddr, int fshared, struct futex_q *q, int locked) { struct task_struct *owner; int ret = 0; if (locked) { /* * Got the lock. We might not be the anticipated owner if we * did a lock-steal - fix up the PI-state in that case: */ if (q->pi_state->owner != current) ret = fixup_pi_state_owner(uaddr, q, current, fshared); goto out; } /* * Catch the rare case, where the lock was released when we were on the * way back before we locked the hash bucket. */ if (q->pi_state->owner == current) { /* * Try to get the rt_mutex now. This might fail as some other * task acquired the rt_mutex after we removed ourself from the * rt_mutex waiters list. */ if (rt_mutex_trylock(&q->pi_state->pi_mutex)) { locked = 1; goto out; } /* * pi_state is incorrect, some other task did a lock steal and * we returned due to timeout or signal without taking the * rt_mutex. Too late. We can access the rt_mutex_owner without * locking, as the other task is now blocked on the hash bucket * lock. Fix the state up. */ owner = rt_mutex_owner(&q->pi_state->pi_mutex); ret = fixup_pi_state_owner(uaddr, q, owner, fshared); goto out; } /* * Paranoia check. If we did not take the lock, then we should not be * the owner, nor the pending owner, of the rt_mutex. */ if (rt_mutex_owner(&q->pi_state->pi_mutex) == current) printk(KERN_ERR "fixup_owner: ret = %d pi-mutex: %p " "pi-state %p\n", ret, q->pi_state->pi_mutex.owner, q->pi_state->owner); out: return ret ? ret : locked; } /** * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal * @hb: the futex hash bucket, must be locked by the caller * @q: the futex_q to queue up on * @timeout: the prepared hrtimer_sleeper, or null for no timeout */ static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q, struct hrtimer_sleeper *timeout) { /* * The task state is guaranteed to be set before another task can * wake it. set_current_state() is implemented using set_mb() and * queue_me() calls spin_unlock() upon completion, both serializing * access to the hash list and forcing another memory barrier. */ set_current_state(TASK_INTERRUPTIBLE); queue_me(q, hb); /* Arm the timer */ if (timeout) { hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS); if (!hrtimer_active(&timeout->timer)) timeout->task = NULL; } /* * If we have been removed from the hash list, then another task * has tried to wake us, and we can skip the call to schedule(). */ if (likely(!plist_node_empty(&q->list))) { /* * If the timer has already expired, current will already be * flagged for rescheduling. Only call schedule if there * is no timeout, or if it has yet to expire. */ if (!timeout || timeout->task) schedule(); } __set_current_state(TASK_RUNNING); } /** * futex_wait_setup() - Prepare to wait on a futex * @uaddr: the futex userspace address * @val: the expected value * @fshared: whether the futex is shared (1) or not (0) * @q: the associated futex_q * @hb: storage for hash_bucket pointer to be returned to caller * * Setup the futex_q and locate the hash_bucket. Get the futex value and * compare it with the expected value. Handle atomic faults internally. * Return with the hb lock held and a q.key reference on success, and unlocked * with no q.key reference on failure. * * Returns: * 0 - uaddr contains val and hb has been locked * <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlcoked */ static int futex_wait_setup(u32 __user *uaddr, u32 val, int fshared, struct futex_q *q, struct futex_hash_bucket **hb) { u32 uval; int ret; /* * Access the page AFTER the hash-bucket is locked. * Order is important: * * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val); * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); } * * The basic logical guarantee of a futex is that it blocks ONLY * if cond(var) is known to be true at the time of blocking, for * any cond. If we queued after testing *uaddr, that would open * a race condition where we could block indefinitely with * cond(var) false, which would violate the guarantee. * * A consequence is that futex_wait() can return zero and absorb * a wakeup when *uaddr != val on entry to the syscall. This is * rare, but normal. */ retry: q->key = FUTEX_KEY_INIT; ret = get_futex_key(uaddr, fshared, &q->key); if (unlikely(ret != 0)) return ret; retry_private: *hb = queue_lock(q); ret = get_futex_value_locked(&uval, uaddr); if (ret) { queue_unlock(q, *hb); ret = get_user(uval, uaddr); if (ret) goto out; if (!fshared) goto retry_private; put_futex_key(fshared, &q->key); goto retry; } if (uval != val) { queue_unlock(q, *hb); ret = -EWOULDBLOCK; } out: if (ret) put_futex_key(fshared, &q->key); return ret; } static int futex_wait(u32 __user *uaddr, int fshared, u32 val, ktime_t *abs_time, u32 bitset, int clockrt) { struct hrtimer_sleeper timeout, *to = NULL; struct restart_block *restart; struct futex_hash_bucket *hb; struct futex_q q; int ret; if (!bitset) return -EINVAL; q.pi_state = NULL; q.bitset = bitset; q.rt_waiter = NULL; q.requeue_pi_key = NULL; if (abs_time) { to = &timeout; hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME : CLOCK_MONOTONIC, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires_range_ns(&to->timer, *abs_time, current->timer_slack_ns); } retry: /* * Prepare to wait on uaddr. On success, holds hb lock and increments * q.key refs. */ ret = futex_wait_setup(uaddr, val, fshared, &q, &hb); if (ret) goto out; /* queue_me and wait for wakeup, timeout, or a signal. */ futex_wait_queue_me(hb, &q, to); /* If we were woken (and unqueued), we succeeded, whatever. */ ret = 0; /* unqueue_me() drops q.key ref */ if (!unqueue_me(&q)) goto out; ret = -ETIMEDOUT; if (to && !to->task) goto out; /* * We expect signal_pending(current), but we might be the * victim of a spurious wakeup as well. */ if (!signal_pending(current)) goto retry; ret = -ERESTARTSYS; if (!abs_time) goto out; restart = &current_thread_info()->restart_block; restart->fn = futex_wait_restart; restart->futex.uaddr = (u32 *)uaddr; restart->futex.val = val; restart->futex.time = abs_time->tv64; restart->futex.bitset = bitset; restart->futex.flags = FLAGS_HAS_TIMEOUT; if (fshared) restart->futex.flags |= FLAGS_SHARED; if (clockrt) restart->futex.flags |= FLAGS_CLOCKRT; ret = -ERESTART_RESTARTBLOCK; out: if (to) { hrtimer_cancel(&to->timer); destroy_hrtimer_on_stack(&to->timer); } return ret; } static long futex_wait_restart(struct restart_block *restart) { u32 __user *uaddr = (u32 __user *)restart->futex.uaddr; int fshared = 0; ktime_t t, *tp = NULL; if (restart->futex.flags & FLAGS_HAS_TIMEOUT) { t.tv64 = restart->futex.time; tp = &t; } restart->fn = do_no_restart_syscall; if (restart->futex.flags & FLAGS_SHARED) fshared = 1; return (long)futex_wait(uaddr, fshared, restart->futex.val, tp, restart->futex.bitset, restart->futex.flags & FLAGS_CLOCKRT); } /* * Userspace tried a 0 -> TID atomic transition of the futex value * and failed. The kernel side here does the whole locking operation: * if there are waiters then it will block, it does PI, etc. (Due to * races the kernel might see a 0 value of the futex too.) */ static int futex_lock_pi(u32 __user *uaddr, int fshared, int detect, ktime_t *time, int trylock) { struct hrtimer_sleeper timeout, *to = NULL; struct futex_hash_bucket *hb; struct futex_q q; int res, ret; if (refill_pi_state_cache()) return -ENOMEM; if (time) { to = &timeout; hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires(&to->timer, *time); } q.pi_state = NULL; q.rt_waiter = NULL; q.requeue_pi_key = NULL; retry: q.key = FUTEX_KEY_INIT; ret = get_futex_key(uaddr, fshared, &q.key); if (unlikely(ret != 0)) goto out; retry_private: hb = queue_lock(&q); ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current, 0); if (unlikely(ret)) { switch (ret) { case 1: /* We got the lock. */ ret = 0; goto out_unlock_put_key; case -EFAULT: goto uaddr_faulted; case -EAGAIN: /* * Task is exiting and we just wait for the * exit to complete. */ queue_unlock(&q, hb); put_futex_key(fshared, &q.key); cond_resched(); goto retry; default: goto out_unlock_put_key; } } /* * Only actually queue now that the atomic ops are done: */ queue_me(&q, hb); WARN_ON(!q.pi_state); /* * Block on the PI mutex: */ if (!trylock) ret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1); else { ret = rt_mutex_trylock(&q.pi_state->pi_mutex); /* Fixup the trylock return value: */ ret = ret ? 0 : -EWOULDBLOCK; } spin_lock(q.lock_ptr); /* * Fixup the pi_state owner and possibly acquire the lock if we * haven't already. */ res = fixup_owner(uaddr, fshared, &q, !ret); /* * If fixup_owner() returned an error, proprogate that. If it acquired * the lock, clear our -ETIMEDOUT or -EINTR. */ if (res) ret = (res < 0) ? res : 0; /* * If fixup_owner() faulted and was unable to handle the fault, unlock * it and return the fault to userspace. */ if (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current)) rt_mutex_unlock(&q.pi_state->pi_mutex); /* Unqueue and drop the lock */ unqueue_me_pi(&q); goto out_put_key; out_unlock_put_key: queue_unlock(&q, hb); out_put_key: put_futex_key(fshared, &q.key); out: if (to) destroy_hrtimer_on_stack(&to->timer); return ret != -EINTR ? ret : -ERESTARTNOINTR; uaddr_faulted: queue_unlock(&q, hb); ret = fault_in_user_writeable(uaddr); if (ret) goto out_put_key; if (!fshared) goto retry_private; put_futex_key(fshared, &q.key); goto retry; } /* * Userspace attempted a TID -> 0 atomic transition, and failed. * This is the in-kernel slowpath: we look up the PI state (if any), * and do the rt-mutex unlock. */ static int futex_unlock_pi(u32 __user *uaddr, int fshared) { struct futex_hash_bucket *hb; struct futex_q *this, *next; u32 uval; struct plist_head *head; union futex_key key = FUTEX_KEY_INIT; int ret; retry: if (get_user(uval, uaddr)) return -EFAULT; /* * We release only a lock we actually own: */ if ((uval & FUTEX_TID_MASK) != task_pid_vnr(current)) return -EPERM; ret = get_futex_key(uaddr, fshared, &key); if (unlikely(ret != 0)) goto out; hb = hash_futex(&key); spin_lock(&hb->lock); /* * To avoid races, try to do the TID -> 0 atomic transition * again. If it succeeds then we can return without waking * anyone else up: */ if (!(uval & FUTEX_OWNER_DIED)) uval = cmpxchg_futex_value_locked(uaddr, task_pid_vnr(current), 0); if (unlikely(uval == -EFAULT)) goto pi_faulted; /* * Rare case: we managed to release the lock atomically, * no need to wake anyone else up: */ if (unlikely(uval == task_pid_vnr(current))) goto out_unlock; /* * Ok, other tasks may need to be woken up - check waiters * and do the wakeup if necessary: */ head = &hb->chain; plist_for_each_entry_safe(this, next, head, list) { if (!match_futex (&this->key, &key)) continue; ret = wake_futex_pi(uaddr, uval, this); /* * The atomic access to the futex value * generated a pagefault, so retry the * user-access and the wakeup: */ if (ret == -EFAULT) goto pi_faulted; goto out_unlock; } /* * No waiters - kernel unlocks the futex: */ if (!(uval & FUTEX_OWNER_DIED)) { ret = unlock_futex_pi(uaddr, uval); if (ret == -EFAULT) goto pi_faulted; } out_unlock: spin_unlock(&hb->lock); put_futex_key(fshared, &key); out: return ret; pi_faulted: spin_unlock(&hb->lock); put_futex_key(fshared, &key); ret = fault_in_user_writeable(uaddr); if (!ret) goto retry; return ret; } /** * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex * @hb: the hash_bucket futex_q was original enqueued on * @q: the futex_q woken while waiting to be requeued * @key2: the futex_key of the requeue target futex * @timeout: the timeout associated with the wait (NULL if none) * * Detect if the task was woken on the initial futex as opposed to the requeue * target futex. If so, determine if it was a timeout or a signal that caused * the wakeup and return the appropriate error code to the caller. Must be * called with the hb lock held. * * Returns * 0 - no early wakeup detected * <0 - -ETIMEDOUT or -ERESTARTNOINTR */ static inline int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb, struct futex_q *q, union futex_key *key2, struct hrtimer_sleeper *timeout) { int ret = 0; /* * With the hb lock held, we avoid races while we process the wakeup. * We only need to hold hb (and not hb2) to ensure atomicity as the * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb. * It can't be requeued from uaddr2 to something else since we don't * support a PI aware source futex for requeue. */ if (!match_futex(&q->key, key2)) { WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr)); /* * We were woken prior to requeue by a timeout or a signal. * Unqueue the futex_q and determine which it was. */ plist_del(&q->list, &q->list.plist); /* Handle spurious wakeups gracefully */ ret = -EWOULDBLOCK; if (timeout && !timeout->task) ret = -ETIMEDOUT; else if (signal_pending(current)) ret = -ERESTARTNOINTR; } return ret; } /** * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2 * @uaddr: the futex we initially wait on (non-pi) * @fshared: whether the futexes are shared (1) or not (0). They must be * the same type, no requeueing from private to shared, etc. * @val: the expected value of uaddr * @abs_time: absolute timeout * @bitset: 32 bit wakeup bitset set by userspace, defaults to all * @clockrt: whether to use CLOCK_REALTIME (1) or CLOCK_MONOTONIC (0) * @uaddr2: the pi futex we will take prior to returning to user-space * * The caller will wait on uaddr and will be requeued by futex_requeue() to * uaddr2 which must be PI aware. Normal wakeup will wake on uaddr2 and * complete the acquisition of the rt_mutex prior to returning to userspace. * This ensures the rt_mutex maintains an owner when it has waiters; without * one, the pi logic wouldn't know which task to boost/deboost, if there was a * need to. * * We call schedule in futex_wait_queue_me() when we enqueue and return there * via the following: * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue() * 2) wakeup on uaddr2 after a requeue * 3) signal * 4) timeout * * If 3, cleanup and return -ERESTARTNOINTR. * * If 2, we may then block on trying to take the rt_mutex and return via: * 5) successful lock * 6) signal * 7) timeout * 8) other lock acquisition failure * * If 6, return -EWOULDBLOCK (restarting the syscall would do the same). * * If 4 or 7, we cleanup and return with -ETIMEDOUT. * * Returns: * 0 - On success * <0 - On error */ static int futex_wait_requeue_pi(u32 __user *uaddr, int fshared, u32 val, ktime_t *abs_time, u32 bitset, int clockrt, u32 __user *uaddr2) { struct hrtimer_sleeper timeout, *to = NULL; struct rt_mutex_waiter rt_waiter; struct rt_mutex *pi_mutex = NULL; struct futex_hash_bucket *hb; union futex_key key2; struct futex_q q; int res, ret; if (!bitset) return -EINVAL; if (abs_time) { to = &timeout; hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME : CLOCK_MONOTONIC, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires_range_ns(&to->timer, *abs_time, current->timer_slack_ns); } /* * The waiter is allocated on our stack, manipulated by the requeue * code while we sleep on uaddr. */ debug_rt_mutex_init_waiter(&rt_waiter); rt_waiter.task = NULL; key2 = FUTEX_KEY_INIT; ret = get_futex_key(uaddr2, fshared, &key2); if (unlikely(ret != 0)) goto out; q.pi_state = NULL; q.bitset = bitset; q.rt_waiter = &rt_waiter; q.requeue_pi_key = &key2; /* * Prepare to wait on uaddr. On success, increments q.key (key1) ref * count. */ ret = futex_wait_setup(uaddr, val, fshared, &q, &hb); if (ret) goto out_key2; /* Queue the futex_q, drop the hb lock, wait for wakeup. */ futex_wait_queue_me(hb, &q, to); spin_lock(&hb->lock); ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to); spin_unlock(&hb->lock); if (ret) goto out_put_keys; /* * In order for us to be here, we know our q.key == key2, and since * we took the hb->lock above, we also know that futex_requeue() has * completed and we no longer have to concern ourselves with a wakeup * race with the atomic proxy lock acquisition by the requeue code. The * futex_requeue dropped our key1 reference and incremented our key2 * reference count. */ /* Check if the requeue code acquired the second futex for us. */ if (!q.rt_waiter) { /* * Got the lock. We might not be the anticipated owner if we * did a lock-steal - fix up the PI-state in that case. */ if (q.pi_state && (q.pi_state->owner != current)) { spin_lock(q.lock_ptr); ret = fixup_pi_state_owner(uaddr2, &q, current, fshared); spin_unlock(q.lock_ptr); } } else { /* * We have been woken up by futex_unlock_pi(), a timeout, or a * signal. futex_unlock_pi() will not destroy the lock_ptr nor * the pi_state. */ WARN_ON(!&q.pi_state); pi_mutex = &q.pi_state->pi_mutex; ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1); debug_rt_mutex_free_waiter(&rt_waiter); spin_lock(q.lock_ptr); /* * Fixup the pi_state owner and possibly acquire the lock if we * haven't already. */ res = fixup_owner(uaddr2, fshared, &q, !ret); /* * If fixup_owner() returned an error, proprogate that. If it * acquired the lock, clear -ETIMEDOUT or -EINTR. */ if (res) ret = (res < 0) ? res : 0; /* Unqueue and drop the lock. */ unqueue_me_pi(&q); } /* * If fixup_pi_state_owner() faulted and was unable to handle the * fault, unlock the rt_mutex and return the fault to userspace. */ if (ret == -EFAULT) { if (rt_mutex_owner(pi_mutex) == current) rt_mutex_unlock(pi_mutex); } else if (ret == -EINTR) { /* * We've already been requeued, but cannot restart by calling * futex_lock_pi() directly. We could restart this syscall, but * it would detect that the user space "val" changed and return * -EWOULDBLOCK. Save the overhead of the restart and return * -EWOULDBLOCK directly. */ ret = -EWOULDBLOCK; } out_put_keys: put_futex_key(fshared, &q.key); out_key2: put_futex_key(fshared, &key2); out: if (to) { hrtimer_cancel(&to->timer); destroy_hrtimer_on_stack(&to->timer); } return ret; } /* * Support for robust futexes: the kernel cleans up held futexes at * thread exit time. * * Implementation: user-space maintains a per-thread list of locks it * is holding. Upon do_exit(), the kernel carefully walks this list, * and marks all locks that are owned by this thread with the * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is * always manipulated with the lock held, so the list is private and * per-thread. Userspace also maintains a per-thread 'list_op_pending' * field, to allow the kernel to clean up if the thread dies after * acquiring the lock, but just before it could have added itself to * the list. There can only be one such pending lock. */ /** * sys_set_robust_list() - Set the robust-futex list head of a task * @head: pointer to the list-head * @len: length of the list-head, as userspace expects */ SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head, size_t, len) { if (!futex_cmpxchg_enabled) return -ENOSYS; /* * The kernel knows only one size for now: */ if (unlikely(len != sizeof(*head))) return -EINVAL; current->robust_list = head; return 0; } /** * sys_get_robust_list() - Get the robust-futex list head of a task * @pid: pid of the process [zero for current task] * @head_ptr: pointer to a list-head pointer, the kernel fills it in * @len_ptr: pointer to a length field, the kernel fills in the header size */ SYSCALL_DEFINE3(get_robust_list, int, pid, struct robust_list_head __user * __user *, head_ptr, size_t __user *, len_ptr) { struct robust_list_head __user *head; unsigned long ret; const struct cred *cred = current_cred(), *pcred; if (!futex_cmpxchg_enabled) return -ENOSYS; if (!pid) head = current->robust_list; else { struct task_struct *p; ret = -ESRCH; rcu_read_lock(); p = find_task_by_vpid(pid); if (!p) goto err_unlock; ret = -EPERM; pcred = __task_cred(p); if (cred->euid != pcred->euid && cred->euid != pcred->uid && !capable(CAP_SYS_PTRACE)) goto err_unlock; head = p->robust_list; rcu_read_unlock(); } if (put_user(sizeof(*head), len_ptr)) return -EFAULT; return put_user(head, head_ptr); err_unlock: rcu_read_unlock(); return ret; } /* * Process a futex-list entry, check whether it's owned by the * dying task, and do notification if so: */ int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi) { u32 uval, nval, mval; retry: if (get_user(uval, uaddr)) return -1; if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) { /* * Ok, this dying thread is truly holding a futex * of interest. Set the OWNER_DIED bit atomically * via cmpxchg, and if the value had FUTEX_WAITERS * set, wake up a waiter (if any). (We have to do a * futex_wake() even if OWNER_DIED is already set - * to handle the rare but possible case of recursive * thread-death.) The rest of the cleanup is done in * userspace. */ mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED; nval = futex_atomic_cmpxchg_inatomic(uaddr, uval, mval); if (nval == -EFAULT) return -1; if (nval != uval) goto retry; /* * Wake robust non-PI futexes here. The wakeup of * PI futexes happens in exit_pi_state(): */ if (!pi && (uval & FUTEX_WAITERS)) futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY); } return 0; } /* * Fetch a robust-list pointer. Bit 0 signals PI futexes: */ static inline int fetch_robust_entry(struct robust_list __user **entry, struct robust_list __user * __user *head, int *pi) { unsigned long uentry; if (get_user(uentry, (unsigned long __user *)head)) return -EFAULT; *entry = (void __user *)(uentry & ~1UL); *pi = uentry & 1; return 0; } /* * Walk curr->robust_list (very carefully, it's a userspace list!) * and mark any locks found there dead, and notify any waiters. * * We silently return on any sign of list-walking problem. */ void exit_robust_list(struct task_struct *curr) { struct robust_list_head __user *head = curr->robust_list; struct robust_list __user *entry, *next_entry, *pending; unsigned int limit = ROBUST_LIST_LIMIT, pi, next_pi, pip; unsigned long futex_offset; int rc; if (!futex_cmpxchg_enabled) return; /* * Fetch the list head (which was registered earlier, via * sys_set_robust_list()): */ if (fetch_robust_entry(&entry, &head->list.next, &pi)) return; /* * Fetch the relative futex offset: */ if (get_user(futex_offset, &head->futex_offset)) return; /* * Fetch any possibly pending lock-add first, and handle it * if it exists: */ if (fetch_robust_entry(&pending, &head->list_op_pending, &pip)) return; next_entry = NULL; /* avoid warning with gcc */ while (entry != &head->list) { /* * Fetch the next entry in the list before calling * handle_futex_death: */ rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi); /* * A pending lock might already be on the list, so * don't process it twice: */ if (entry != pending) if (handle_futex_death((void __user *)entry + futex_offset, curr, pi)) return; if (rc) return; entry = next_entry; pi = next_pi; /* * Avoid excessively long or circular lists: */ if (!--limit) break; cond_resched(); } if (pending) handle_futex_death((void __user *)pending + futex_offset, curr, pip); } long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout, u32 __user *uaddr2, u32 val2, u32 val3) { int clockrt, ret = -ENOSYS; int cmd = op & FUTEX_CMD_MASK; int fshared = 0; if (!(op & FUTEX_PRIVATE_FLAG)) fshared = 1; clockrt = op & FUTEX_CLOCK_REALTIME; if (clockrt && cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI) return -ENOSYS; switch (cmd) { case FUTEX_WAIT: val3 = FUTEX_BITSET_MATCH_ANY; case FUTEX_WAIT_BITSET: ret = futex_wait(uaddr, fshared, val, timeout, val3, clockrt); break; case FUTEX_WAKE: val3 = FUTEX_BITSET_MATCH_ANY; case FUTEX_WAKE_BITSET: ret = futex_wake(uaddr, fshared, val, val3); break; case FUTEX_REQUEUE: ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, NULL, 0); break; case FUTEX_CMP_REQUEUE: ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, &val3, 0); break; case FUTEX_WAKE_OP: ret = futex_wake_op(uaddr, fshared, uaddr2, val, val2, val3); break; case FUTEX_LOCK_PI: if (futex_cmpxchg_enabled) ret = futex_lock_pi(uaddr, fshared, val, timeout, 0); break; case FUTEX_UNLOCK_PI: if (futex_cmpxchg_enabled) ret = futex_unlock_pi(uaddr, fshared); break; case FUTEX_TRYLOCK_PI: if (futex_cmpxchg_enabled) ret = futex_lock_pi(uaddr, fshared, 0, timeout, 1); break; case FUTEX_WAIT_REQUEUE_PI: val3 = FUTEX_BITSET_MATCH_ANY; ret = futex_wait_requeue_pi(uaddr, fshared, val, timeout, val3, clockrt, uaddr2); break; case FUTEX_CMP_REQUEUE_PI: ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, &val3, 1); break; default: ret = -ENOSYS; } return ret; } SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val, struct timespec __user *, utime, u32 __user *, uaddr2, u32, val3) { struct timespec ts; ktime_t t, *tp = NULL; u32 val2 = 0; int cmd = op & FUTEX_CMD_MASK; if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI || cmd == FUTEX_WAIT_BITSET || cmd == FUTEX_WAIT_REQUEUE_PI)) { if (copy_from_user(&ts, utime, sizeof(ts)) != 0) return -EFAULT; if (!timespec_valid(&ts)) return -EINVAL; t = timespec_to_ktime(ts); if (cmd == FUTEX_WAIT) t = ktime_add_safe(ktime_get(), t); tp = &t; } /* * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*. * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP. */ if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE || cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP) val2 = (u32) (unsigned long) utime; return do_futex(uaddr, op, val, tp, uaddr2, val2, val3); } static int __init futex_init(void) { u32 curval; int i; /* * This will fail and we want it. Some arch implementations do * runtime detection of the futex_atomic_cmpxchg_inatomic() * functionality. We want to know that before we call in any * of the complex code paths. Also we want to prevent * registration of robust lists in that case. NULL is * guaranteed to fault and we get -EFAULT on functional * implementation, the non functional ones will return * -ENOSYS. */ curval = cmpxchg_futex_value_locked(NULL, 0, 0); if (curval == -EFAULT) futex_cmpxchg_enabled = 1; for (i = 0; i < ARRAY_SIZE(futex_queues); i++) { plist_head_init(&futex_queues[i].chain, &futex_queues[i].lock); spin_lock_init(&futex_queues[i].lock); } return 0; } __initcall(futex_init);
./CrossVul/dataset_final_sorted/CWE-119/c/good_2036_0
crossvul-cpp_data_good_2213_0
/* * LZO1X Decompressor from LZO * * Copyright (C) 1996-2012 Markus F.X.J. Oberhumer <markus@oberhumer.com> * * The full LZO package can be found at: * http://www.oberhumer.com/opensource/lzo/ * * Changed for Linux kernel use by: * Nitin Gupta <nitingupta910@gmail.com> * Richard Purdie <rpurdie@openedhand.com> */ #ifndef STATIC #include <linux/module.h> #include <linux/kernel.h> #endif #include <asm/unaligned.h> #include <linux/lzo.h> #include "lzodefs.h" #define HAVE_IP(t, x) \ (((size_t)(ip_end - ip) >= (size_t)(t + x)) && \ (((t + x) >= t) && ((t + x) >= x))) #define HAVE_OP(t, x) \ (((size_t)(op_end - op) >= (size_t)(t + x)) && \ (((t + x) >= t) && ((t + x) >= x))) #define NEED_IP(t, x) \ do { \ if (!HAVE_IP(t, x)) \ goto input_overrun; \ } while (0) #define NEED_OP(t, x) \ do { \ if (!HAVE_OP(t, x)) \ goto output_overrun; \ } while (0) #define TEST_LB(m_pos) \ do { \ if ((m_pos) < out) \ goto lookbehind_overrun; \ } while (0) int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len) { unsigned char *op; const unsigned char *ip; size_t t, next; size_t state = 0; const unsigned char *m_pos; const unsigned char * const ip_end = in + in_len; unsigned char * const op_end = out + *out_len; op = out; ip = in; if (unlikely(in_len < 3)) goto input_overrun; if (*ip > 17) { t = *ip++ - 17; if (t < 4) { next = t; goto match_next; } goto copy_literal_run; } for (;;) { t = *ip++; if (t < 16) { if (likely(state == 0)) { if (unlikely(t == 0)) { while (unlikely(*ip == 0)) { t += 255; ip++; NEED_IP(1, 0); } t += 15 + *ip++; } t += 3; copy_literal_run: #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) if (likely(HAVE_IP(t, 15) && HAVE_OP(t, 15))) { const unsigned char *ie = ip + t; unsigned char *oe = op + t; do { COPY8(op, ip); op += 8; ip += 8; COPY8(op, ip); op += 8; ip += 8; } while (ip < ie); ip = ie; op = oe; } else #endif { NEED_OP(t, 0); NEED_IP(t, 3); do { *op++ = *ip++; } while (--t > 0); } state = 4; continue; } else if (state != 4) { next = t & 3; m_pos = op - 1; m_pos -= t >> 2; m_pos -= *ip++ << 2; TEST_LB(m_pos); NEED_OP(2, 0); op[0] = m_pos[0]; op[1] = m_pos[1]; op += 2; goto match_next; } else { next = t & 3; m_pos = op - (1 + M2_MAX_OFFSET); m_pos -= t >> 2; m_pos -= *ip++ << 2; t = 3; } } else if (t >= 64) { next = t & 3; m_pos = op - 1; m_pos -= (t >> 2) & 7; m_pos -= *ip++ << 3; t = (t >> 5) - 1 + (3 - 1); } else if (t >= 32) { t = (t & 31) + (3 - 1); if (unlikely(t == 2)) { while (unlikely(*ip == 0)) { t += 255; ip++; NEED_IP(1, 0); } t += 31 + *ip++; NEED_IP(2, 0); } m_pos = op - 1; next = get_unaligned_le16(ip); ip += 2; m_pos -= next >> 2; next &= 3; } else { m_pos = op; m_pos -= (t & 8) << 11; t = (t & 7) + (3 - 1); if (unlikely(t == 2)) { while (unlikely(*ip == 0)) { t += 255; ip++; NEED_IP(1, 0); } t += 7 + *ip++; NEED_IP(2, 0); } next = get_unaligned_le16(ip); ip += 2; m_pos -= next >> 2; next &= 3; if (m_pos == op) goto eof_found; m_pos -= 0x4000; } TEST_LB(m_pos); #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) if (op - m_pos >= 8) { unsigned char *oe = op + t; if (likely(HAVE_OP(t, 15))) { do { COPY8(op, m_pos); op += 8; m_pos += 8; COPY8(op, m_pos); op += 8; m_pos += 8; } while (op < oe); op = oe; if (HAVE_IP(6, 0)) { state = next; COPY4(op, ip); op += next; ip += next; continue; } } else { NEED_OP(t, 0); do { *op++ = *m_pos++; } while (op < oe); } } else #endif { unsigned char *oe = op + t; NEED_OP(t, 0); op[0] = m_pos[0]; op[1] = m_pos[1]; op += 2; m_pos += 2; do { *op++ = *m_pos++; } while (op < oe); } match_next: state = next; t = next; #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) if (likely(HAVE_IP(6, 0) && HAVE_OP(4, 0))) { COPY4(op, ip); op += t; ip += t; } else #endif { NEED_IP(t, 3); NEED_OP(t, 0); while (t > 0) { *op++ = *ip++; t--; } } } eof_found: *out_len = op - out; return (t != 3 ? LZO_E_ERROR : ip == ip_end ? LZO_E_OK : ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN); input_overrun: *out_len = op - out; return LZO_E_INPUT_OVERRUN; output_overrun: *out_len = op - out; return LZO_E_OUTPUT_OVERRUN; lookbehind_overrun: *out_len = op - out; return LZO_E_LOOKBEHIND_OVERRUN; } #ifndef STATIC EXPORT_SYMBOL_GPL(lzo1x_decompress_safe); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("LZO1X Decompressor"); #endif
./CrossVul/dataset_final_sorted/CWE-119/c/good_2213_0
crossvul-cpp_data_good_1030_0
/* ** FAAD2 - Freeware Advanced Audio (AAC) Decoder including SBR decoding ** Copyright (C) 2003-2005 M. Bakker, Nero AG, http://www.nero.com ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ** ** Any non-GPL usage of this software or parts of this software is strictly ** forbidden. ** ** The "appropriate copyright message" mentioned in section 2c of the GPLv2 ** must read: "Code from FAAD2 is copyright (c) Nero AG, www.nero.com" ** ** Commercial non-GPL licensing of this software is possible. ** For more info contact Nero AG through Mpeg4AAClicense@nero.com. ** ** $Id: bits.c,v 1.44 2007/11/01 12:33:29 menno Exp $ **/ #include "common.h" #include "structs.h" #include <stdlib.h> #include "bits.h" /* initialize buffer, call once before first getbits or showbits */ void faad_initbits(bitfile *ld, const void *_buffer, const uint32_t buffer_size) { uint32_t tmp; if (ld == NULL) return; // useless //memset(ld, 0, sizeof(bitfile)); if (buffer_size == 0 || _buffer == NULL) { ld->error = 1; return; } ld->buffer = _buffer; ld->buffer_size = buffer_size; ld->bytes_left = buffer_size; if (ld->bytes_left >= 4) { tmp = getdword((uint32_t*)ld->buffer); ld->bytes_left -= 4; } else { tmp = getdword_n((uint32_t*)ld->buffer, ld->bytes_left); ld->bytes_left = 0; } ld->bufa = tmp; if (ld->bytes_left >= 4) { tmp = getdword((uint32_t*)ld->buffer + 1); ld->bytes_left -= 4; } else { tmp = getdword_n((uint32_t*)ld->buffer + 1, ld->bytes_left); ld->bytes_left = 0; } ld->bufb = tmp; ld->start = (uint32_t*)ld->buffer; ld->tail = ((uint32_t*)ld->buffer + 2); ld->bits_left = 32; ld->error = 0; } void faad_endbits(bitfile *ld) { // void } uint32_t faad_get_processed_bits(bitfile *ld) { return (uint32_t)(8 * (4*(ld->tail - ld->start) - 4) - (ld->bits_left)); } uint8_t faad_byte_align(bitfile *ld) { int remainder = (32 - ld->bits_left) & 0x7; if (remainder) { faad_flushbits(ld, 8 - remainder); return (uint8_t)(8 - remainder); } return 0; } void faad_flushbits_ex(bitfile *ld, uint32_t bits) { uint32_t tmp; ld->bufa = ld->bufb; if (ld->bytes_left >= 4) { tmp = getdword(ld->tail); ld->bytes_left -= 4; } else { tmp = getdword_n(ld->tail, ld->bytes_left); ld->bytes_left = 0; } ld->bufb = tmp; ld->tail++; ld->bits_left += (32 - bits); //ld->bytes_left -= 4; // if (ld->bytes_left == 0) // ld->no_more_reading = 1; // if (ld->bytes_left < 0) // ld->error = 1; } /* rewind to beginning */ void faad_rewindbits(bitfile *ld) { uint32_t tmp; ld->bytes_left = ld->buffer_size; if (ld->bytes_left >= 4) { tmp = getdword((uint32_t*)&ld->start[0]); ld->bytes_left -= 4; } else { tmp = getdword_n((uint32_t*)&ld->start[0], ld->bytes_left); ld->bytes_left = 0; } ld->bufa = tmp; if (ld->bytes_left >= 4) { tmp = getdword((uint32_t*)&ld->start[1]); ld->bytes_left -= 4; } else { tmp = getdword_n((uint32_t*)&ld->start[1], ld->bytes_left); ld->bytes_left = 0; } ld->bufb = tmp; ld->bits_left = 32; ld->tail = &ld->start[2]; } /* reset to a certain point */ void faad_resetbits(bitfile *ld, int bits) { uint32_t tmp; int words = bits >> 5; int remainder = bits & 0x1F; if (ld->buffer_size < words * 4) ld->bytes_left = 0; else ld->bytes_left = ld->buffer_size - words*4; if (ld->bytes_left >= 4) { tmp = getdword(&ld->start[words]); ld->bytes_left -= 4; } else { tmp = getdword_n(&ld->start[words], ld->bytes_left); ld->bytes_left = 0; } ld->bufa = tmp; if (ld->bytes_left >= 4) { tmp = getdword(&ld->start[words+1]); ld->bytes_left -= 4; } else { tmp = getdword_n(&ld->start[words+1], ld->bytes_left); ld->bytes_left = 0; } ld->bufb = tmp; ld->bits_left = 32 - remainder; ld->tail = &ld->start[words+2]; /* recheck for reading too many bytes */ ld->error = 0; // if (ld->bytes_left == 0) // ld->no_more_reading = 1; // if (ld->bytes_left < 0) // ld->error = 1; } uint8_t *faad_getbitbuffer(bitfile *ld, uint32_t bits DEBUGDEC) { int i; unsigned int temp; int bytes = bits >> 3; int remainder = bits & 0x7; uint8_t *buffer = (uint8_t*)faad_malloc((bytes+1)*sizeof(uint8_t)); for (i = 0; i < bytes; i++) { buffer[i] = (uint8_t)faad_getbits(ld, 8 DEBUGVAR(print,var,dbg)); } if (remainder) { temp = faad_getbits(ld, remainder DEBUGVAR(print,var,dbg)) << (8-remainder); buffer[bytes] = (uint8_t)temp; } return buffer; } #ifdef DRM /* return the original data buffer */ void *faad_origbitbuffer(bitfile *ld) { return (void*)ld->start; } /* return the original data buffer size */ uint32_t faad_origbitbuffer_size(bitfile *ld) { return ld->buffer_size; } #endif /* reversed bit reading routines, used for RVLC and HCR */ void faad_initbits_rev(bitfile *ld, void *buffer, uint32_t bits_in_buffer) { uint32_t tmp; int32_t index; ld->buffer_size = bit2byte(bits_in_buffer); index = (bits_in_buffer+31)/32 - 1; ld->start = (uint32_t*)buffer + index - 2; tmp = getdword((uint32_t*)buffer + index); ld->bufa = tmp; tmp = getdword((uint32_t*)buffer + index - 1); ld->bufb = tmp; ld->tail = (uint32_t*)buffer + index; ld->bits_left = bits_in_buffer % 32; if (ld->bits_left == 0) ld->bits_left = 32; ld->bytes_left = ld->buffer_size; ld->error = 0; } /* EOF */
./CrossVul/dataset_final_sorted/CWE-119/c/good_1030_0
crossvul-cpp_data_good_3540_0
/* * Copyright (C) 2007-2011 B.A.T.M.A.N. contributors: * * Marek Lindner * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA * */ #include "main.h" #include <linux/debugfs.h> #include <linux/slab.h> #include "icmp_socket.h" #include "send.h" #include "hash.h" #include "originator.h" #include "hard-interface.h" static struct socket_client *socket_client_hash[256]; static void bat_socket_add_packet(struct socket_client *socket_client, struct icmp_packet_rr *icmp_packet, size_t icmp_len); void bat_socket_init(void) { memset(socket_client_hash, 0, sizeof(socket_client_hash)); } static int bat_socket_open(struct inode *inode, struct file *file) { unsigned int i; struct socket_client *socket_client; nonseekable_open(inode, file); socket_client = kmalloc(sizeof(*socket_client), GFP_KERNEL); if (!socket_client) return -ENOMEM; for (i = 0; i < ARRAY_SIZE(socket_client_hash); i++) { if (!socket_client_hash[i]) { socket_client_hash[i] = socket_client; break; } } if (i == ARRAY_SIZE(socket_client_hash)) { pr_err("Error - can't add another packet client: " "maximum number of clients reached\n"); kfree(socket_client); return -EXFULL; } INIT_LIST_HEAD(&socket_client->queue_list); socket_client->queue_len = 0; socket_client->index = i; socket_client->bat_priv = inode->i_private; spin_lock_init(&socket_client->lock); init_waitqueue_head(&socket_client->queue_wait); file->private_data = socket_client; inc_module_count(); return 0; } static int bat_socket_release(struct inode *inode, struct file *file) { struct socket_client *socket_client = file->private_data; struct socket_packet *socket_packet; struct list_head *list_pos, *list_pos_tmp; spin_lock_bh(&socket_client->lock); /* for all packets in the queue ... */ list_for_each_safe(list_pos, list_pos_tmp, &socket_client->queue_list) { socket_packet = list_entry(list_pos, struct socket_packet, list); list_del(list_pos); kfree(socket_packet); } socket_client_hash[socket_client->index] = NULL; spin_unlock_bh(&socket_client->lock); kfree(socket_client); dec_module_count(); return 0; } static ssize_t bat_socket_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct socket_client *socket_client = file->private_data; struct socket_packet *socket_packet; size_t packet_len; int error; if ((file->f_flags & O_NONBLOCK) && (socket_client->queue_len == 0)) return -EAGAIN; if ((!buf) || (count < sizeof(struct icmp_packet))) return -EINVAL; if (!access_ok(VERIFY_WRITE, buf, count)) return -EFAULT; error = wait_event_interruptible(socket_client->queue_wait, socket_client->queue_len); if (error) return error; spin_lock_bh(&socket_client->lock); socket_packet = list_first_entry(&socket_client->queue_list, struct socket_packet, list); list_del(&socket_packet->list); socket_client->queue_len--; spin_unlock_bh(&socket_client->lock); packet_len = min(count, socket_packet->icmp_len); error = copy_to_user(buf, &socket_packet->icmp_packet, packet_len); kfree(socket_packet); if (error) return -EFAULT; return packet_len; } static ssize_t bat_socket_write(struct file *file, const char __user *buff, size_t len, loff_t *off) { struct socket_client *socket_client = file->private_data; struct bat_priv *bat_priv = socket_client->bat_priv; struct hard_iface *primary_if = NULL; struct sk_buff *skb; struct icmp_packet_rr *icmp_packet; struct orig_node *orig_node = NULL; struct neigh_node *neigh_node = NULL; size_t packet_len = sizeof(struct icmp_packet); if (len < sizeof(struct icmp_packet)) { bat_dbg(DBG_BATMAN, bat_priv, "Error - can't send packet from char device: " "invalid packet size\n"); return -EINVAL; } primary_if = primary_if_get_selected(bat_priv); if (!primary_if) { len = -EFAULT; goto out; } if (len >= sizeof(struct icmp_packet_rr)) packet_len = sizeof(struct icmp_packet_rr); skb = dev_alloc_skb(packet_len + sizeof(struct ethhdr)); if (!skb) { len = -ENOMEM; goto out; } skb_reserve(skb, sizeof(struct ethhdr)); icmp_packet = (struct icmp_packet_rr *)skb_put(skb, packet_len); if (copy_from_user(icmp_packet, buff, packet_len)) { len = -EFAULT; goto free_skb; } if (icmp_packet->packet_type != BAT_ICMP) { bat_dbg(DBG_BATMAN, bat_priv, "Error - can't send packet from char device: " "got bogus packet type (expected: BAT_ICMP)\n"); len = -EINVAL; goto free_skb; } if (icmp_packet->msg_type != ECHO_REQUEST) { bat_dbg(DBG_BATMAN, bat_priv, "Error - can't send packet from char device: " "got bogus message type (expected: ECHO_REQUEST)\n"); len = -EINVAL; goto free_skb; } icmp_packet->uid = socket_client->index; if (icmp_packet->version != COMPAT_VERSION) { icmp_packet->msg_type = PARAMETER_PROBLEM; icmp_packet->version = COMPAT_VERSION; bat_socket_add_packet(socket_client, icmp_packet, packet_len); goto free_skb; } if (atomic_read(&bat_priv->mesh_state) != MESH_ACTIVE) goto dst_unreach; orig_node = orig_hash_find(bat_priv, icmp_packet->dst); if (!orig_node) goto dst_unreach; neigh_node = orig_node_get_router(orig_node); if (!neigh_node) goto dst_unreach; if (!neigh_node->if_incoming) goto dst_unreach; if (neigh_node->if_incoming->if_status != IF_ACTIVE) goto dst_unreach; memcpy(icmp_packet->orig, primary_if->net_dev->dev_addr, ETH_ALEN); if (packet_len == sizeof(struct icmp_packet_rr)) memcpy(icmp_packet->rr, neigh_node->if_incoming->net_dev->dev_addr, ETH_ALEN); send_skb_packet(skb, neigh_node->if_incoming, neigh_node->addr); goto out; dst_unreach: icmp_packet->msg_type = DESTINATION_UNREACHABLE; bat_socket_add_packet(socket_client, icmp_packet, packet_len); free_skb: kfree_skb(skb); out: if (primary_if) hardif_free_ref(primary_if); if (neigh_node) neigh_node_free_ref(neigh_node); if (orig_node) orig_node_free_ref(orig_node); return len; } static unsigned int bat_socket_poll(struct file *file, poll_table *wait) { struct socket_client *socket_client = file->private_data; poll_wait(file, &socket_client->queue_wait, wait); if (socket_client->queue_len > 0) return POLLIN | POLLRDNORM; return 0; } static const struct file_operations fops = { .owner = THIS_MODULE, .open = bat_socket_open, .release = bat_socket_release, .read = bat_socket_read, .write = bat_socket_write, .poll = bat_socket_poll, .llseek = no_llseek, }; int bat_socket_setup(struct bat_priv *bat_priv) { struct dentry *d; if (!bat_priv->debug_dir) goto err; d = debugfs_create_file(ICMP_SOCKET, S_IFREG | S_IWUSR | S_IRUSR, bat_priv->debug_dir, bat_priv, &fops); if (d) goto err; return 0; err: return 1; } static void bat_socket_add_packet(struct socket_client *socket_client, struct icmp_packet_rr *icmp_packet, size_t icmp_len) { struct socket_packet *socket_packet; socket_packet = kmalloc(sizeof(*socket_packet), GFP_ATOMIC); if (!socket_packet) return; INIT_LIST_HEAD(&socket_packet->list); memcpy(&socket_packet->icmp_packet, icmp_packet, icmp_len); socket_packet->icmp_len = icmp_len; spin_lock_bh(&socket_client->lock); /* while waiting for the lock the socket_client could have been * deleted */ if (!socket_client_hash[icmp_packet->uid]) { spin_unlock_bh(&socket_client->lock); kfree(socket_packet); return; } list_add_tail(&socket_packet->list, &socket_client->queue_list); socket_client->queue_len++; if (socket_client->queue_len > 100) { socket_packet = list_first_entry(&socket_client->queue_list, struct socket_packet, list); list_del(&socket_packet->list); kfree(socket_packet); socket_client->queue_len--; } spin_unlock_bh(&socket_client->lock); wake_up(&socket_client->queue_wait); } void bat_socket_receive_packet(struct icmp_packet_rr *icmp_packet, size_t icmp_len) { struct socket_client *hash = socket_client_hash[icmp_packet->uid]; if (hash) bat_socket_add_packet(hash, icmp_packet, icmp_len); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_3540_0
crossvul-cpp_data_good_1828_0
/* * Copyright (c) Christos Zoulas 2003. * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice immediately at the beginning of the file, without modification, * this list of conditions, and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: funcs.c,v 1.81 2015/05/28 19:26:59 christos Exp $") #endif /* lint */ #include "magic.h" #include <assert.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #if defined(HAVE_WCHAR_H) #include <wchar.h> #endif #if defined(HAVE_WCTYPE_H) #include <wctype.h> #endif #if defined(HAVE_LIMITS_H) #include <limits.h> #endif #ifndef SIZE_MAX #define SIZE_MAX ((size_t)~0) #endif /* * Like printf, only we append to a buffer. */ protected int file_vprintf(struct magic_set *ms, const char *fmt, va_list ap) { int len; char *buf, *newstr; if (ms->event_flags & EVENT_HAD_ERR) return 0; len = vasprintf(&buf, fmt, ap); if (len < 0) goto out; if (ms->o.buf != NULL) { len = asprintf(&newstr, "%s%s", ms->o.buf, buf); free(buf); if (len < 0) goto out; free(ms->o.buf); buf = newstr; } ms->o.buf = buf; return 0; out: file_error(ms, errno, "vasprintf failed"); return -1; } protected int file_printf(struct magic_set *ms, const char *fmt, ...) { int rv; va_list ap; va_start(ap, fmt); rv = file_vprintf(ms, fmt, ap); va_end(ap); return rv; } /* * error - print best error message possible */ /*VARARGS*/ __attribute__((__format__(__printf__, 3, 0))) private void file_error_core(struct magic_set *ms, int error, const char *f, va_list va, size_t lineno) { /* Only the first error is ok */ if (ms->event_flags & EVENT_HAD_ERR) return; if (lineno != 0) { free(ms->o.buf); ms->o.buf = NULL; file_printf(ms, "line %" SIZE_T_FORMAT "u: ", lineno); } file_vprintf(ms, f, va); if (error > 0) file_printf(ms, " (%s)", strerror(error)); ms->event_flags |= EVENT_HAD_ERR; ms->error = error; } /*VARARGS*/ protected void file_error(struct magic_set *ms, int error, const char *f, ...) { va_list va; va_start(va, f); file_error_core(ms, error, f, va, 0); va_end(va); } /* * Print an error with magic line number. */ /*VARARGS*/ protected void file_magerror(struct magic_set *ms, const char *f, ...) { va_list va; va_start(va, f); file_error_core(ms, 0, f, va, ms->line); va_end(va); } protected void file_oomem(struct magic_set *ms, size_t len) { file_error(ms, errno, "cannot allocate %" SIZE_T_FORMAT "u bytes", len); } protected void file_badseek(struct magic_set *ms) { file_error(ms, errno, "error seeking"); } protected void file_badread(struct magic_set *ms) { file_error(ms, errno, "error reading"); } #ifndef COMPILE_ONLY static int checkdone(struct magic_set *ms, int *rv) { if ((ms->flags & MAGIC_CONTINUE) == 0) return 1; if (file_printf(ms, "\n- ") == -1) *rv = -1; return 0; } /*ARGSUSED*/ protected int file_buffer(struct magic_set *ms, int fd, const char *inname __attribute__ ((__unused__)), const void *buf, size_t nb) { int m = 0, rv = 0, looks_text = 0; int mime = ms->flags & MAGIC_MIME; const unsigned char *ubuf = CAST(const unsigned char *, buf); unichar *u8buf = NULL; size_t ulen; const char *code = NULL; const char *code_mime = "binary"; const char *type = "application/octet-stream"; const char *def = "data"; const char *ftype = NULL; if (nb == 0) { def = "empty"; type = "application/x-empty"; goto simple; } else if (nb == 1) { def = "very short file (no magic)"; goto simple; } if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) { looks_text = file_encoding(ms, ubuf, nb, &u8buf, &ulen, &code, &code_mime, &ftype); } #ifdef __EMX__ if ((ms->flags & MAGIC_NO_CHECK_APPTYPE) == 0 && inname) { switch (file_os2_apptype(ms, inname, buf, nb)) { case -1: return -1; case 0: break; default: return 1; } } #endif #if HAVE_FORK /* try compression stuff */ if ((ms->flags & MAGIC_NO_CHECK_COMPRESS) == 0) if ((m = file_zmagic(ms, fd, inname, ubuf, nb)) != 0) { if ((ms->flags & MAGIC_DEBUG) != 0) (void)fprintf(stderr, "zmagic %d\n", m); goto done_encoding; } #endif /* Check if we have a tar file */ if ((ms->flags & MAGIC_NO_CHECK_TAR) == 0) if ((m = file_is_tar(ms, ubuf, nb)) != 0) { if ((ms->flags & MAGIC_DEBUG) != 0) (void)fprintf(stderr, "tar %d\n", m); if (checkdone(ms, &rv)) goto done; } /* Check if we have a CDF file */ if ((ms->flags & MAGIC_NO_CHECK_CDF) == 0) if ((m = file_trycdf(ms, fd, ubuf, nb)) != 0) { if ((ms->flags & MAGIC_DEBUG) != 0) (void)fprintf(stderr, "cdf %d\n", m); if (checkdone(ms, &rv)) goto done; } /* try soft magic tests */ if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0) if ((m = file_softmagic(ms, ubuf, nb, 0, NULL, BINTEST, looks_text)) != 0) { if ((ms->flags & MAGIC_DEBUG) != 0) (void)fprintf(stderr, "softmagic %d\n", m); #ifdef BUILTIN_ELF if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && m == 1 && nb > 5 && fd != -1) { /* * We matched something in the file, so this * *might* be an ELF file, and the file is at * least 5 bytes long, so if it's an ELF file * it has at least one byte past the ELF magic * number - try extracting information from the * ELF headers that cannot easily * be * extracted with rules in the magic file. */ if ((m = file_tryelf(ms, fd, ubuf, nb)) != 0) if ((ms->flags & MAGIC_DEBUG) != 0) (void)fprintf(stderr, "elf %d\n", m); } #endif if (checkdone(ms, &rv)) goto done; } /* try text properties */ if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) { if ((m = file_ascmagic(ms, ubuf, nb, looks_text)) != 0) { if ((ms->flags & MAGIC_DEBUG) != 0) (void)fprintf(stderr, "ascmagic %d\n", m); if (checkdone(ms, &rv)) goto done; } } simple: /* give up */ m = 1; if ((!mime || (mime & MAGIC_MIME_TYPE)) && file_printf(ms, "%s", mime ? type : def) == -1) { rv = -1; } done: if ((ms->flags & MAGIC_MIME_ENCODING) != 0) { if (ms->flags & MAGIC_MIME_TYPE) if (file_printf(ms, "; charset=") == -1) rv = -1; if (file_printf(ms, "%s", code_mime) == -1) rv = -1; } #if HAVE_FORK done_encoding: #endif free(u8buf); if (rv) return rv; return m; } #endif protected int file_reset(struct magic_set *ms) { if (ms->mlist[0] == NULL) { file_error(ms, 0, "no magic files loaded"); return -1; } if (ms->o.buf) { free(ms->o.buf); ms->o.buf = NULL; } if (ms->o.pbuf) { free(ms->o.pbuf); ms->o.pbuf = NULL; } ms->event_flags &= ~EVENT_HAD_ERR; ms->error = -1; return 0; } #define OCTALIFY(n, o) \ /*LINTED*/ \ (void)(*(n)++ = '\\', \ *(n)++ = (((uint32_t)*(o) >> 6) & 3) + '0', \ *(n)++ = (((uint32_t)*(o) >> 3) & 7) + '0', \ *(n)++ = (((uint32_t)*(o) >> 0) & 7) + '0', \ (o)++) protected const char * file_getbuffer(struct magic_set *ms) { char *pbuf, *op, *np; size_t psize, len; if (ms->event_flags & EVENT_HAD_ERR) return NULL; if (ms->flags & MAGIC_RAW) return ms->o.buf; if (ms->o.buf == NULL) return NULL; /* * 4 is for octal representation, + 1 is for NUL */ len = strlen(ms->o.buf); if (len > (SIZE_MAX - 1) / 4) { file_oomem(ms, len); return NULL; } psize = len * 4 + 1; if ((pbuf = CAST(char *, realloc(ms->o.pbuf, psize))) == NULL) { file_oomem(ms, psize); return NULL; } ms->o.pbuf = pbuf; #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH) { mbstate_t state; wchar_t nextchar; int mb_conv = 1; size_t bytesconsumed; char *eop; (void)memset(&state, 0, sizeof(mbstate_t)); np = ms->o.pbuf; op = ms->o.buf; eop = op + len; while (op < eop) { bytesconsumed = mbrtowc(&nextchar, op, (size_t)(eop - op), &state); if (bytesconsumed == (size_t)(-1) || bytesconsumed == (size_t)(-2)) { mb_conv = 0; break; } if (iswprint(nextchar)) { (void)memcpy(np, op, bytesconsumed); op += bytesconsumed; np += bytesconsumed; } else { while (bytesconsumed-- > 0) OCTALIFY(np, op); } } *np = '\0'; /* Parsing succeeded as a multi-byte sequence */ if (mb_conv != 0) return ms->o.pbuf; } #endif for (np = ms->o.pbuf, op = ms->o.buf; *op;) { if (isprint((unsigned char)*op)) { *np++ = *op++; } else { OCTALIFY(np, op); } } *np = '\0'; return ms->o.pbuf; } protected int file_check_mem(struct magic_set *ms, unsigned int level) { size_t len; if (level >= ms->c.len) { len = (ms->c.len = 20 + level) * sizeof(*ms->c.li); ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ? malloc(len) : realloc(ms->c.li, len)); if (ms->c.li == NULL) { file_oomem(ms, len); return -1; } } ms->c.li[level].got_match = 0; #ifdef ENABLE_CONDITIONALS ms->c.li[level].last_match = 0; ms->c.li[level].last_cond = COND_NONE; #endif /* ENABLE_CONDITIONALS */ return 0; } protected size_t file_printedlen(const struct magic_set *ms) { return ms->o.buf == NULL ? 0 : strlen(ms->o.buf); } protected int file_replace(struct magic_set *ms, const char *pat, const char *rep) { file_regex_t rx; int rc, rv = -1; rc = file_regcomp(&rx, pat, REG_EXTENDED); if (rc) { file_regerror(&rx, rc, ms); } else { regmatch_t rm; int nm = 0; while (file_regexec(&rx, ms->o.buf, 1, &rm, 0) == 0) { ms->o.buf[rm.rm_so] = '\0'; if (file_printf(ms, "%s%s", rep, rm.rm_eo != 0 ? ms->o.buf + rm.rm_eo : "") == -1) goto out; nm++; } rv = nm; } out: file_regfree(&rx); return rv; } protected int file_regcomp(file_regex_t *rx, const char *pat, int flags) { #ifdef USE_C_LOCALE rx->c_lc_ctype = newlocale(LC_CTYPE_MASK, "C", 0); assert(rx->c_lc_ctype != NULL); rx->old_lc_ctype = uselocale(rx->c_lc_ctype); assert(rx->old_lc_ctype != NULL); #endif rx->pat = pat; return rx->rc = regcomp(&rx->rx, pat, flags); } protected int file_regexec(file_regex_t *rx, const char *str, size_t nmatch, regmatch_t* pmatch, int eflags) { assert(rx->rc == 0); return regexec(&rx->rx, str, nmatch, pmatch, eflags); } protected void file_regfree(file_regex_t *rx) { if (rx->rc == 0) regfree(&rx->rx); #ifdef USE_C_LOCALE (void)uselocale(rx->old_lc_ctype); freelocale(rx->c_lc_ctype); #endif } protected void file_regerror(file_regex_t *rx, int rc, struct magic_set *ms) { char errmsg[512]; (void)regerror(rc, &rx->rx, errmsg, sizeof(errmsg)); file_magerror(ms, "regex error %d for `%s', (%s)", rc, rx->pat, errmsg); } protected file_pushbuf_t * file_push_buffer(struct magic_set *ms) { file_pushbuf_t *pb; if (ms->event_flags & EVENT_HAD_ERR) return NULL; if ((pb = (CAST(file_pushbuf_t *, malloc(sizeof(*pb))))) == NULL) return NULL; pb->buf = ms->o.buf; pb->offset = ms->offset; ms->o.buf = NULL; ms->offset = 0; return pb; } protected char * file_pop_buffer(struct magic_set *ms, file_pushbuf_t *pb) { char *rbuf; if (ms->event_flags & EVENT_HAD_ERR) { free(pb->buf); free(pb); return NULL; } rbuf = ms->o.buf; ms->o.buf = pb->buf; ms->offset = pb->offset; free(pb); return rbuf; } /* * convert string to ascii printable format. */ protected char * file_printable(char *buf, size_t bufsiz, const char *str) { char *ptr, *eptr; const unsigned char *s = (const unsigned char *)str; for (ptr = buf, eptr = ptr + bufsiz - 1; ptr < eptr && *s; s++) { if (isprint(*s)) { *ptr++ = *s; continue; } if (ptr >= eptr - 3) break; *ptr++ = '\\'; *ptr++ = ((CAST(unsigned int, *s) >> 6) & 7) + '0'; *ptr++ = ((CAST(unsigned int, *s) >> 3) & 7) + '0'; *ptr++ = ((CAST(unsigned int, *s) >> 0) & 7) + '0'; } *ptr = '\0'; return buf; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1828_0
crossvul-cpp_data_bad_634_3
/********************************************************************* * * This is based on code created by Peter Harvey, * (pharvey@codebydesign.com). * * Modified and extended by Nick Gorham * (nick@lurcher.org). * * Any bugs or problems should be considered the fault of Nick and not * Peter. * * copyright (c) 1999 Nick Gorham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ********************************************************************** * * $Id: SQLSetDescFieldW.c,v 1.8 2009/02/18 17:59:08 lurcher Exp $ * * $Log: SQLSetDescFieldW.c,v $ * Revision 1.8 2009/02/18 17:59:08 lurcher * Shift to using config.h, the compile lines were making it hard to spot warnings * * Revision 1.7 2008/08/29 08:01:39 lurcher * Alter the way W functions are passed to the driver * * Revision 1.6 2007/03/05 09:49:24 lurcher * Get it to build on VMS again * * Revision 1.5 2007/02/28 15:37:48 lurcher * deal with drivers that call internal W functions and end up in the driver manager. controlled by the --enable-handlemap configure arg * * Revision 1.4 2006/04/18 10:24:47 lurcher * Add a couple of changes from Mark Vanderwiel * * Revision 1.3 2003/10/30 18:20:46 lurcher * * Fix broken thread protection * Remove SQLNumResultCols after execute, lease S4/S% to driver * Fix string overrun in SQLDriverConnect * Add initial support for Interix * * Revision 1.2 2002/12/05 17:44:31 lurcher * * Display unknown return values in return logging * * Revision 1.1.1.1 2001/10/17 16:40:07 lurcher * * First upload to SourceForge * * Revision 1.4 2001/07/03 09:30:41 nick * * Add ability to alter size of displayed message in the log * * Revision 1.3 2001/04/17 16:29:39 nick * * More checks and autotest fixes * * Revision 1.2 2001/04/12 17:43:36 nick * * Change logging and added autotest to odbctest * * Revision 1.1 2000/12/31 20:30:54 nick * * Add UNICODE support * * * **********************************************************************/ #include <config.h> #include "drivermanager.h" static char const rcsid[]= "$RCSfile: SQLSetDescFieldW.c,v $"; SQLRETURN SQLSetDescFieldW( SQLHDESC descriptor_handle, SQLSMALLINT rec_number, SQLSMALLINT field_identifier, SQLPOINTER value, SQLINTEGER buffer_length ) { /* * not quite sure how the descriptor can be * allocated to a statement, all the documentation talks * about state transitions on statement states, but the * descriptor may be allocated with more than one statement * at one time. Which one should I check ? */ DMHDESC descriptor = (DMHDESC) descriptor_handle; SQLRETURN ret; SQLCHAR s1[ 100 + LOG_MESSAGE_LEN ]; int isStrField = 0; /* * check descriptor */ if ( !__validate_desc( descriptor )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: SQL_INVALID_HANDLE" ); #ifdef WITH_HANDLE_REDIRECT { DMHDESC parent_desc; parent_desc = find_parent_handle( descriptor, SQL_HANDLE_DESC ); if ( parent_desc ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Info: found parent handle" ); if ( CHECK_SQLSETDESCFIELDW( parent_desc -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Info: calling redirected driver function" ); return SQLSETDESCFIELDW( parent_desc -> connection, descriptor, rec_number, field_identifier, value, buffer_length ); } } } #endif return SQL_INVALID_HANDLE; } function_entry( descriptor ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tEntry:\ \n\t\t\tDescriptor = %p\ \n\t\t\tRec Number = %d\ \n\t\t\tField Ident = %s\ \n\t\t\tValue = %p\ \n\t\t\tBuffer Length = %d", descriptor, rec_number, __desc_attr_as_string( s1, field_identifier ), value, (int)buffer_length ); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } thread_protect( SQL_HANDLE_DESC, descriptor ); if ( descriptor -> connection -> state < STATE_C4 ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * check status of statements associated with this descriptor */ if( __check_stmt_from_desc( descriptor, STATE_S8 ) || __check_stmt_from_desc( descriptor, STATE_S9 ) || __check_stmt_from_desc( descriptor, STATE_S10 ) || __check_stmt_from_desc( descriptor, STATE_S11 ) || __check_stmt_from_desc( descriptor, STATE_S12 ) || __check_stmt_from_desc( descriptor, STATE_S13 ) || __check_stmt_from_desc( descriptor, STATE_S14 ) || __check_stmt_from_desc( descriptor, STATE_S15 )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( rec_number < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } switch ( field_identifier ) { /* Fixed-length fields: buffer_length is ignored */ case SQL_DESC_ALLOC_TYPE: case SQL_DESC_ARRAY_SIZE: case SQL_DESC_ARRAY_STATUS_PTR: case SQL_DESC_BIND_OFFSET_PTR: case SQL_DESC_BIND_TYPE: case SQL_DESC_COUNT: case SQL_DESC_ROWS_PROCESSED_PTR: case SQL_DESC_AUTO_UNIQUE_VALUE: case SQL_DESC_CASE_SENSITIVE: case SQL_DESC_CONCISE_TYPE: case SQL_DESC_DATA_PTR: case SQL_DESC_DATETIME_INTERVAL_CODE: case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_DISPLAY_SIZE: case SQL_DESC_FIXED_PREC_SCALE: case SQL_DESC_INDICATOR_PTR: case SQL_DESC_LENGTH: case SQL_DESC_NULLABLE: case SQL_DESC_NUM_PREC_RADIX: case SQL_DESC_OCTET_LENGTH: case SQL_DESC_OCTET_LENGTH_PTR: case SQL_DESC_PARAMETER_TYPE: case SQL_DESC_PRECISION: case SQL_DESC_ROWVER: case SQL_DESC_SCALE: case SQL_DESC_SEARCHABLE: case SQL_DESC_TYPE: case SQL_DESC_UNNAMED: case SQL_DESC_UNSIGNED: case SQL_DESC_UPDATABLE: isStrField = 0; break; /* Pointer to data: buffer_length must be valid */ case SQL_DESC_BASE_COLUMN_NAME: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_CATALOG_NAME: case SQL_DESC_LABEL: case SQL_DESC_LITERAL_PREFIX: case SQL_DESC_LITERAL_SUFFIX: case SQL_DESC_LOCAL_TYPE_NAME: case SQL_DESC_NAME: case SQL_DESC_SCHEMA_NAME: case SQL_DESC_TABLE_NAME: case SQL_DESC_TYPE_NAME: isStrField = 1; break; default: isStrField = buffer_length != SQL_IS_POINTER && buffer_length != SQL_IS_INTEGER && buffer_length != SQL_IS_UINTEGER && buffer_length != SQL_IS_SMALLINT && buffer_length != SQL_IS_USMALLINT; } if ( isStrField && buffer_length < 0 && buffer_length != SQL_NTS) { __post_internal_error( &descriptor -> error, ERROR_HY090, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_COUNT && (SQLINTEGER)value < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_PARAMETER_TYPE && value != SQL_PARAM_INPUT && value != SQL_PARAM_OUTPUT && value != SQL_PARAM_INPUT_OUTPUT && value != SQL_PARAM_INPUT_OUTPUT_STREAM && value != SQL_PARAM_OUTPUT_STREAM ) { __post_internal_error( &descriptor -> error, ERROR_HY105, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( descriptor -> connection -> unicode_driver || CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { if ( !CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: IM001" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } ret = SQLSETDESCFIELDW( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tExit:[%s]", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } } else { SQLCHAR *ascii_str = NULL; if ( !CHECK_SQLSETDESCFIELD( descriptor -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: IM001" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * is it a char arg... */ switch ( field_identifier ) { case SQL_DESC_NAME: /* This is the only R/W SQLCHAR* type */ ascii_str = (SQLCHAR*) unicode_to_ansi_alloc( value, buffer_length, descriptor -> connection, NULL ); value = ascii_str; buffer_length = strlen((char*) ascii_str ); break; default: break; } ret = SQLSETDESCFIELD( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tExit:[%s]", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } if ( ascii_str ) { free( ascii_str ); } } return function_return( SQL_HANDLE_DESC, descriptor, ret ); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_634_3
crossvul-cpp_data_good_2984_0
/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com * Copyright (c) 2016 Facebook * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * 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. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/bpf.h> #include <linux/bpf_verifier.h> #include <linux/filter.h> #include <net/netlink.h> #include <linux/file.h> #include <linux/vmalloc.h> #include <linux/stringify.h> #include "disasm.h" static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { #define BPF_PROG_TYPE(_id, _name) \ [_id] = & _name ## _verifier_ops, #define BPF_MAP_TYPE(_id, _ops) #include <linux/bpf_types.h> #undef BPF_PROG_TYPE #undef BPF_MAP_TYPE }; /* bpf_check() is a static code analyzer that walks eBPF program * instruction by instruction and updates register/stack state. * All paths of conditional branches are analyzed until 'bpf_exit' insn. * * The first pass is depth-first-search to check that the program is a DAG. * It rejects the following programs: * - larger than BPF_MAXINSNS insns * - if loop is present (detected via back-edge) * - unreachable insns exist (shouldn't be a forest. program = one function) * - out of bounds or malformed jumps * The second pass is all possible path descent from the 1st insn. * Since it's analyzing all pathes through the program, the length of the * analysis is limited to 64k insn, which may be hit even if total number of * insn is less then 4K, but there are too many branches that change stack/regs. * Number of 'branches to be analyzed' is limited to 1k * * On entry to each instruction, each register has a type, and the instruction * changes the types of the registers depending on instruction semantics. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is * copied to R1. * * All registers are 64-bit. * R0 - return register * R1-R5 argument passing registers * R6-R9 callee saved registers * R10 - frame pointer read-only * * At the start of BPF program the register R1 contains a pointer to bpf_context * and has type PTR_TO_CTX. * * Verifier tracks arithmetic operations on pointers in case: * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), * 1st insn copies R10 (which has FRAME_PTR) type into R1 * and 2nd arithmetic instruction is pattern matched to recognize * that it wants to construct a pointer to some element within stack. * So after 2nd insn, the register R1 has type PTR_TO_STACK * (and -20 constant is saved for further stack bounds checking). * Meaning that this reg is a pointer to stack plus known immediate constant. * * Most of the time the registers have SCALAR_VALUE type, which * means the register has some value, but it's not a valid pointer. * (like pointer plus pointer becomes SCALAR_VALUE type) * * When verifier sees load or store instructions the type of base register * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer * types recognized by check_mem_access() function. * * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' * and the range of [ptr, ptr + map's value_size) is accessible. * * registers used to pass values to function calls are checked against * function argument constraints. * * ARG_PTR_TO_MAP_KEY is one of such argument constraints. * It means that the register type passed to this function must be * PTR_TO_STACK and it will be used inside the function as * 'pointer to map element key' * * For example the argument constraints for bpf_map_lookup_elem(): * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, * .arg1_type = ARG_CONST_MAP_PTR, * .arg2_type = ARG_PTR_TO_MAP_KEY, * * ret_type says that this function returns 'pointer to map elem value or null' * function expects 1st argument to be a const pointer to 'struct bpf_map' and * 2nd argument should be a pointer to stack, which will be used inside * the helper function as a pointer to map element key. * * On the kernel side the helper function looks like: * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) * { * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; * void *key = (void *) (unsigned long) r2; * void *value; * * here kernel can access 'key' and 'map' pointers safely, knowing that * [key, key + map->key_size) bytes are valid and were initialized on * the stack of eBPF program. * } * * Corresponding eBPF program may look like: * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), * here verifier looks at prototype of map_lookup_elem() and sees: * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, * Now verifier knows that this map has key of R1->map_ptr->key_size bytes * * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, * Now verifier checks that [R2, R2 + map's key_size) are within stack limits * and were initialized prior to this call. * If it's ok, then verifier allows this BPF_CALL insn and looks at * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function * returns ether pointer to map value or NULL. * * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' * insn, the register holding that pointer in the true branch changes state to * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false * branch. See check_cond_jmp_op(). * * After the call R0 is set to return type of the function and registers R1-R5 * are set to NOT_INIT to indicate that they are no longer readable. */ /* verifier_state + insn_idx are pushed to stack when branch is encountered */ struct bpf_verifier_stack_elem { /* verifer state is 'st' * before processing instruction 'insn_idx' * and after processing instruction 'prev_insn_idx' */ struct bpf_verifier_state st; int insn_idx; int prev_insn_idx; struct bpf_verifier_stack_elem *next; }; #define BPF_COMPLEXITY_LIMIT_INSNS 131072 #define BPF_COMPLEXITY_LIMIT_STACK 1024 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA) struct bpf_call_arg_meta { struct bpf_map *map_ptr; bool raw_mode; bool pkt_access; int regno; int access_size; }; static DEFINE_MUTEX(bpf_verifier_lock); /* log_level controls verbosity level of eBPF verifier. * verbose() is used to dump the verification trace to the log, so the user * can figure out what's wrong with the program */ static __printf(2, 3) void verbose(struct bpf_verifier_env *env, const char *fmt, ...) { struct bpf_verifer_log *log = &env->log; unsigned int n; va_list args; if (!log->level || !log->ubuf || bpf_verifier_log_full(log)) return; va_start(args, fmt); n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); va_end(args); WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, "verifier log line truncated - local buffer too short\n"); n = min(log->len_total - log->len_used - 1, n); log->kbuf[n] = '\0'; if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) log->len_used += n; else log->ubuf = NULL; } static bool type_is_pkt_pointer(enum bpf_reg_type type) { return type == PTR_TO_PACKET || type == PTR_TO_PACKET_META; } /* string representation of 'enum bpf_reg_type' */ static const char * const reg_type_str[] = { [NOT_INIT] = "?", [SCALAR_VALUE] = "inv", [PTR_TO_CTX] = "ctx", [CONST_PTR_TO_MAP] = "map_ptr", [PTR_TO_MAP_VALUE] = "map_value", [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null", [PTR_TO_STACK] = "fp", [PTR_TO_PACKET] = "pkt", [PTR_TO_PACKET_META] = "pkt_meta", [PTR_TO_PACKET_END] = "pkt_end", }; static void print_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *state) { struct bpf_reg_state *reg; enum bpf_reg_type t; int i; for (i = 0; i < MAX_BPF_REG; i++) { reg = &state->regs[i]; t = reg->type; if (t == NOT_INIT) continue; verbose(env, " R%d=%s", i, reg_type_str[t]); if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && tnum_is_const(reg->var_off)) { /* reg->off should be 0 for SCALAR_VALUE */ verbose(env, "%lld", reg->var_off.value + reg->off); } else { verbose(env, "(id=%d", reg->id); if (t != SCALAR_VALUE) verbose(env, ",off=%d", reg->off); if (type_is_pkt_pointer(t)) verbose(env, ",r=%d", reg->range); else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE || t == PTR_TO_MAP_VALUE_OR_NULL) verbose(env, ",ks=%d,vs=%d", reg->map_ptr->key_size, reg->map_ptr->value_size); if (tnum_is_const(reg->var_off)) { /* Typically an immediate SCALAR_VALUE, but * could be a pointer whose offset is too big * for reg->off */ verbose(env, ",imm=%llx", reg->var_off.value); } else { if (reg->smin_value != reg->umin_value && reg->smin_value != S64_MIN) verbose(env, ",smin_value=%lld", (long long)reg->smin_value); if (reg->smax_value != reg->umax_value && reg->smax_value != S64_MAX) verbose(env, ",smax_value=%lld", (long long)reg->smax_value); if (reg->umin_value != 0) verbose(env, ",umin_value=%llu", (unsigned long long)reg->umin_value); if (reg->umax_value != U64_MAX) verbose(env, ",umax_value=%llu", (unsigned long long)reg->umax_value); if (!tnum_is_unknown(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, ",var_off=%s", tn_buf); } } verbose(env, ")"); } } for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] == STACK_SPILL) verbose(env, " fp%d=%s", -MAX_BPF_STACK + i * BPF_REG_SIZE, reg_type_str[state->stack[i].spilled_ptr.type]); } verbose(env, "\n"); } static int copy_stack_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) { if (!src->stack) return 0; if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) { /* internal bug, make state invalid to reject the program */ memset(dst, 0, sizeof(*dst)); return -EFAULT; } memcpy(dst->stack, src->stack, sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE)); return 0; } /* do_check() starts with zero-sized stack in struct bpf_verifier_state to * make it consume minimal amount of memory. check_stack_write() access from * the program calls into realloc_verifier_state() to grow the stack size. * Note there is a non-zero 'parent' pointer inside bpf_verifier_state * which this function copies over. It points to previous bpf_verifier_state * which is never reallocated */ static int realloc_verifier_state(struct bpf_verifier_state *state, int size, bool copy_old) { u32 old_size = state->allocated_stack; struct bpf_stack_state *new_stack; int slot = size / BPF_REG_SIZE; if (size <= old_size || !size) { if (copy_old) return 0; state->allocated_stack = slot * BPF_REG_SIZE; if (!size && old_size) { kfree(state->stack); state->stack = NULL; } return 0; } new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state), GFP_KERNEL); if (!new_stack) return -ENOMEM; if (copy_old) { if (state->stack) memcpy(new_stack, state->stack, sizeof(*new_stack) * (old_size / BPF_REG_SIZE)); memset(new_stack + old_size / BPF_REG_SIZE, 0, sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE); } state->allocated_stack = slot * BPF_REG_SIZE; kfree(state->stack); state->stack = new_stack; return 0; } static void free_verifier_state(struct bpf_verifier_state *state, bool free_self) { kfree(state->stack); if (free_self) kfree(state); } /* copy verifier state from src to dst growing dst stack space * when necessary to accommodate larger src stack */ static int copy_verifier_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) { int err; err = realloc_verifier_state(dst, src->allocated_stack, false); if (err) return err; memcpy(dst, src, offsetof(struct bpf_verifier_state, allocated_stack)); return copy_stack_state(dst, src); } static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, int *insn_idx) { struct bpf_verifier_state *cur = env->cur_state; struct bpf_verifier_stack_elem *elem, *head = env->head; int err; if (env->head == NULL) return -ENOENT; if (cur) { err = copy_verifier_state(cur, &head->st); if (err) return err; } if (insn_idx) *insn_idx = head->insn_idx; if (prev_insn_idx) *prev_insn_idx = head->prev_insn_idx; elem = head->next; free_verifier_state(&head->st, false); kfree(head); env->head = elem; env->stack_size--; return 0; } static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { struct bpf_verifier_state *cur = env->cur_state; struct bpf_verifier_stack_elem *elem; int err; elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); if (!elem) goto err; elem->insn_idx = insn_idx; elem->prev_insn_idx = prev_insn_idx; elem->next = env->head; env->head = elem; env->stack_size++; err = copy_verifier_state(&elem->st, cur); if (err) goto err; if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) { verbose(env, "BPF program is too complex\n"); goto err; } return &elem->st; err: /* pop all elements and return */ while (!pop_stack(env, NULL, NULL)); return NULL; } #define CALLER_SAVED_REGS 6 static const int caller_saved[CALLER_SAVED_REGS] = { BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 }; static void __mark_reg_not_init(struct bpf_reg_state *reg); /* Mark the unknown part of a register (variable offset or scalar value) as * known to have the value @imm. */ static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) { reg->id = 0; reg->var_off = tnum_const(imm); reg->smin_value = (s64)imm; reg->smax_value = (s64)imm; reg->umin_value = imm; reg->umax_value = imm; } /* Mark the 'variable offset' part of a register as zero. This should be * used only on registers holding a pointer type. */ static void __mark_reg_known_zero(struct bpf_reg_state *reg) { __mark_reg_known(reg, 0); } static void mark_reg_known_zero(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_known_zero(regs + regno); } static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) { return type_is_pkt_pointer(reg->type); } static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) { return reg_is_pkt_pointer(reg) || reg->type == PTR_TO_PACKET_END; } /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, enum bpf_reg_type which) { /* The register can already have a range from prior markings. * This is fine as long as it hasn't been advanced from its * origin. */ return reg->type == which && reg->id == 0 && reg->off == 0 && tnum_equals_const(reg->var_off, 0); } /* Attempts to improve min/max values based on var_off information */ static void __update_reg_bounds(struct bpf_reg_state *reg) { /* min signed is max(sign bit) | min(other bits) */ reg->smin_value = max_t(s64, reg->smin_value, reg->var_off.value | (reg->var_off.mask & S64_MIN)); /* max signed is min(sign bit) | max(other bits) */ reg->smax_value = min_t(s64, reg->smax_value, reg->var_off.value | (reg->var_off.mask & S64_MAX)); reg->umin_value = max(reg->umin_value, reg->var_off.value); reg->umax_value = min(reg->umax_value, reg->var_off.value | reg->var_off.mask); } /* Uses signed min/max values to inform unsigned, and vice-versa */ static void __reg_deduce_bounds(struct bpf_reg_state *reg) { /* Learn sign from signed bounds. * If we cannot cross the sign boundary, then signed and unsigned bounds * are the same, so combine. This works even in the negative case, e.g. * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. */ if (reg->smin_value >= 0 || reg->smax_value < 0) { reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); return; } /* Learn sign from unsigned bounds. Signed bounds cross the sign * boundary, so we must be careful. */ if ((s64)reg->umax_value >= 0) { /* Positive. We can't learn anything from the smin, but smax * is positive, hence safe. */ reg->smin_value = reg->umin_value; reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); } else if ((s64)reg->umin_value < 0) { /* Negative. We can't learn anything from the smax, but smin * is negative, hence safe. */ reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); reg->smax_value = reg->umax_value; } } /* Attempts to improve var_off based on unsigned min/max information */ static void __reg_bound_offset(struct bpf_reg_state *reg) { reg->var_off = tnum_intersect(reg->var_off, tnum_range(reg->umin_value, reg->umax_value)); } /* Reset the min/max bounds of a register */ static void __mark_reg_unbounded(struct bpf_reg_state *reg) { reg->smin_value = S64_MIN; reg->smax_value = S64_MAX; reg->umin_value = 0; reg->umax_value = U64_MAX; } /* Mark a register as having a completely unknown (scalar) value. */ static void __mark_reg_unknown(struct bpf_reg_state *reg) { reg->type = SCALAR_VALUE; reg->id = 0; reg->off = 0; reg->var_off = tnum_unknown; __mark_reg_unbounded(reg); } static void mark_reg_unknown(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_unknown(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_unknown(regs + regno); } static void __mark_reg_not_init(struct bpf_reg_state *reg) { __mark_reg_unknown(reg); reg->type = NOT_INIT; } static void mark_reg_not_init(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_not_init(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_not_init(regs + regno); } static void init_reg_state(struct bpf_verifier_env *env, struct bpf_reg_state *regs) { int i; for (i = 0; i < MAX_BPF_REG; i++) { mark_reg_not_init(env, regs, i); regs[i].live = REG_LIVE_NONE; } /* frame pointer */ regs[BPF_REG_FP].type = PTR_TO_STACK; mark_reg_known_zero(env, regs, BPF_REG_FP); /* 1st arg to a function */ regs[BPF_REG_1].type = PTR_TO_CTX; mark_reg_known_zero(env, regs, BPF_REG_1); } enum reg_arg_type { SRC_OP, /* register is used as source operand */ DST_OP, /* register is used as destination operand */ DST_OP_NO_MARK /* same as above, check only, don't mark */ }; static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno) { struct bpf_verifier_state *parent = state->parent; if (regno == BPF_REG_FP) /* We don't need to worry about FP liveness because it's read-only */ return; while (parent) { /* if read wasn't screened by an earlier write ... */ if (state->regs[regno].live & REG_LIVE_WRITTEN) break; /* ... then we depend on parent's value */ parent->regs[regno].live |= REG_LIVE_READ; state = parent; parent = state->parent; } } static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, enum reg_arg_type t) { struct bpf_reg_state *regs = env->cur_state->regs; if (regno >= MAX_BPF_REG) { verbose(env, "R%d is invalid\n", regno); return -EINVAL; } if (t == SRC_OP) { /* check whether register used as source operand can be read */ if (regs[regno].type == NOT_INIT) { verbose(env, "R%d !read_ok\n", regno); return -EACCES; } mark_reg_read(env->cur_state, regno); } else { /* check whether register used as dest operand can be written to */ if (regno == BPF_REG_FP) { verbose(env, "frame pointer is read only\n"); return -EACCES; } regs[regno].live |= REG_LIVE_WRITTEN; if (t == DST_OP) mark_reg_unknown(env, regs, regno); } return 0; } static bool is_spillable_regtype(enum bpf_reg_type type) { switch (type) { case PTR_TO_MAP_VALUE: case PTR_TO_MAP_VALUE_OR_NULL: case PTR_TO_STACK: case PTR_TO_CTX: case PTR_TO_PACKET: case PTR_TO_PACKET_META: case PTR_TO_PACKET_END: case CONST_PTR_TO_MAP: return true; default: return false; } } /* check_stack_read/write functions track spill/fill of registers, * stack boundary and alignment are checked in check_mem_access() */ static int check_stack_write(struct bpf_verifier_env *env, struct bpf_verifier_state *state, int off, int size, int value_regno) { int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; err = realloc_verifier_state(state, round_up(slot + 1, BPF_REG_SIZE), true); if (err) return err; /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, * so it's aligned access and [off, off + size) are within stack limits */ if (!env->allow_ptr_leaks && state->stack[spi].slot_type[0] == STACK_SPILL && size != BPF_REG_SIZE) { verbose(env, "attempt to corrupt spilled pointer on stack\n"); return -EACCES; } if (value_regno >= 0 && is_spillable_regtype(state->regs[value_regno].type)) { /* register containing pointer is being spilled into stack */ if (size != BPF_REG_SIZE) { verbose(env, "invalid size of register spill\n"); return -EACCES; } /* save register state */ state->stack[spi].spilled_ptr = state->regs[value_regno]; state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; for (i = 0; i < BPF_REG_SIZE; i++) state->stack[spi].slot_type[i] = STACK_SPILL; } else { /* regular write of data into stack */ state->stack[spi].spilled_ptr = (struct bpf_reg_state) {}; for (i = 0; i < size; i++) state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = STACK_MISC; } return 0; } static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot) { struct bpf_verifier_state *parent = state->parent; while (parent) { /* if read wasn't screened by an earlier write ... */ if (state->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN) break; /* ... then we depend on parent's value */ parent->stack[slot].spilled_ptr.live |= REG_LIVE_READ; state = parent; parent = state->parent; } } static int check_stack_read(struct bpf_verifier_env *env, struct bpf_verifier_state *state, int off, int size, int value_regno) { int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; u8 *stype; if (state->allocated_stack <= slot) { verbose(env, "invalid read from stack off %d+0 size %d\n", off, size); return -EACCES; } stype = state->stack[spi].slot_type; if (stype[0] == STACK_SPILL) { if (size != BPF_REG_SIZE) { verbose(env, "invalid size of register spill\n"); return -EACCES; } for (i = 1; i < BPF_REG_SIZE; i++) { if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) { verbose(env, "corrupted spill memory\n"); return -EACCES; } } if (value_regno >= 0) { /* restore register state from stack */ state->regs[value_regno] = state->stack[spi].spilled_ptr; mark_stack_slot_read(state, spi); } return 0; } else { for (i = 0; i < size; i++) { if (stype[(slot - i) % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid read from stack off %d+%d size %d\n", off, i, size); return -EACCES; } } if (value_regno >= 0) /* have read misc data from the stack */ mark_reg_unknown(env, state->regs, value_regno); return 0; } } /* check read/write into map element returned by bpf_map_lookup_elem() */ static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_map *map = regs[regno].map_ptr; if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || off + size > map->value_size) { verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", map->value_size, off, size); return -EACCES; } return 0; } /* check read/write into a map element with possible variable offset */ static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *reg = &state->regs[regno]; int err; /* We may have adjusted the register to this map value, so we * need to try adding each of min_value and max_value to off * to make sure our theoretical access will be safe. */ if (env->log.level) print_verifier_state(env, state); /* The minimum value is only important with signed * comparisons where we can't assume the floor of a * value is 0. If we are using signed variables for our * index'es we need to make sure that whatever we use * will have a set floor within our range. */ if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", regno); return -EACCES; } err = __check_map_access(env, regno, reg->smin_value + off, size, zero_size_allowed); if (err) { verbose(env, "R%d min value is outside of the array range\n", regno); return err; } /* If we haven't set a max value then we need to bail since we can't be * sure we won't do bad things. * If reg->umax_value + off could overflow, treat that as unbounded too. */ if (reg->umax_value >= BPF_MAX_VAR_OFF) { verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n", regno); return -EACCES; } err = __check_map_access(env, regno, reg->umax_value + off, size, zero_size_allowed); if (err) verbose(env, "R%d max value is outside of the array range\n", regno); return err; } #define MAX_PACKET_OFF 0xffff static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, const struct bpf_call_arg_meta *meta, enum bpf_access_type t) { switch (env->prog->type) { case BPF_PROG_TYPE_LWT_IN: case BPF_PROG_TYPE_LWT_OUT: /* dst_input() and dst_output() can't write for now */ if (t == BPF_WRITE) return false; /* fallthrough */ case BPF_PROG_TYPE_SCHED_CLS: case BPF_PROG_TYPE_SCHED_ACT: case BPF_PROG_TYPE_XDP: case BPF_PROG_TYPE_LWT_XMIT: case BPF_PROG_TYPE_SK_SKB: if (meta) return meta->pkt_access; env->seen_direct_write = true; return true; default: return false; } } static int __check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = &regs[regno]; if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || (u64)off + size > reg->range) { verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", off, size, regno, reg->id, reg->off, reg->range); return -EACCES; } return 0; } static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = &regs[regno]; int err; /* We may have added a variable offset to the packet pointer; but any * reg->range we have comes after that. We are only checking the fixed * offset. */ /* We don't allow negative numbers, because we aren't tracking enough * detail to prove they're safe. */ if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", regno); return -EACCES; } err = __check_packet_access(env, regno, off, size, zero_size_allowed); if (err) { verbose(env, "R%d offset is outside of the packet\n", regno); return err; } return err; } /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, enum bpf_access_type t, enum bpf_reg_type *reg_type) { struct bpf_insn_access_aux info = { .reg_type = *reg_type, }; if (env->ops->is_valid_access && env->ops->is_valid_access(off, size, t, &info)) { /* A non zero info.ctx_field_size indicates that this field is a * candidate for later verifier transformation to load the whole * field and then apply a mask when accessed with a narrower * access than actual ctx access size. A zero info.ctx_field_size * will only allow for whole field access and rejects any other * type of narrower access. */ *reg_type = info.reg_type; env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; /* remember the offset of last byte accessed in ctx */ if (env->prog->aux->max_ctx_offset < off + size) env->prog->aux->max_ctx_offset = off + size; return 0; } verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); return -EACCES; } static bool __is_pointer_value(bool allow_ptr_leaks, const struct bpf_reg_state *reg) { if (allow_ptr_leaks) return false; return reg->type != SCALAR_VALUE; } static bool is_pointer_value(struct bpf_verifier_env *env, int regno) { return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno); } static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size, bool strict) { struct tnum reg_off; int ip_align; /* Byte size accesses are always allowed. */ if (!strict || size == 1) return 0; /* For platforms that do not have a Kconfig enabling * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of * NET_IP_ALIGN is universally set to '2'. And on platforms * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get * to this code only in strict mode where we want to emulate * the NET_IP_ALIGN==2 checking. Therefore use an * unconditional IP align value of '2'. */ ip_align = 2; reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); if (!tnum_is_aligned(reg_off, size)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "misaligned packet access off %d+%s+%d+%d size %d\n", ip_align, tn_buf, reg->off, off, size); return -EACCES; } return 0; } static int check_generic_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, const char *pointer_desc, int off, int size, bool strict) { struct tnum reg_off; /* Byte size accesses are always allowed. */ if (!strict || size == 1) return 0; reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); if (!tnum_is_aligned(reg_off, size)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", pointer_desc, tn_buf, reg->off, off, size); return -EACCES; } return 0; } static int check_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size) { bool strict = env->strict_alignment; const char *pointer_desc = ""; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: /* Special case, because of NET_IP_ALIGN. Given metadata sits * right in front, treat it the very same way. */ return check_pkt_ptr_alignment(env, reg, off, size, strict); case PTR_TO_MAP_VALUE: pointer_desc = "value "; break; case PTR_TO_CTX: pointer_desc = "context "; break; case PTR_TO_STACK: pointer_desc = "stack "; break; default: break; } return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, strict); } /* check whether memory at (regno + off) is accessible for t = (read | write) * if t==write, value_regno is a register which value is stored into memory * if t==read, value_regno is a register which will receive the value from memory * if t==write && value_regno==-1, some unknown value is stored into memory * if t==read && value_regno==-1, don't care what we read from memory */ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off, int bpf_size, enum bpf_access_type t, int value_regno) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = regs + regno; int size, err = 0; size = bpf_size_to_bytes(bpf_size); if (size < 0) return size; /* alignment checks will add in reg->off themselves */ err = check_ptr_alignment(env, reg, off, size); if (err) return err; /* for access checks, reg->off is just part of off */ off += reg->off; if (reg->type == PTR_TO_MAP_VALUE) { if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into map\n", value_regno); return -EACCES; } err = check_map_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else if (reg->type == PTR_TO_CTX) { enum bpf_reg_type reg_type = SCALAR_VALUE; if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into ctx\n", value_regno); return -EACCES; } /* ctx accesses must be at a fixed offset, so that we can * determine what type of data were returned. */ if (reg->off) { verbose(env, "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n", regno, reg->off, off - reg->off); return -EACCES; } if (!tnum_is_const(reg->var_off) || reg->var_off.value) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable ctx access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } err = check_ctx_access(env, insn_idx, off, size, t, &reg_type); if (!err && t == BPF_READ && value_regno >= 0) { /* ctx access returns either a scalar, or a * PTR_TO_PACKET[_META,_END]. In the latter * case, we know the offset is zero. */ if (reg_type == SCALAR_VALUE) mark_reg_unknown(env, regs, value_regno); else mark_reg_known_zero(env, regs, value_regno); regs[value_regno].id = 0; regs[value_regno].off = 0; regs[value_regno].range = 0; regs[value_regno].type = reg_type; } } else if (reg->type == PTR_TO_STACK) { /* stack accesses must be at a fixed offset, so that we can * determine what type of data were returned. * See check_stack_read(). */ if (!tnum_is_const(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable stack access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } off += reg->var_off.value; if (off >= 0 || off < -MAX_BPF_STACK) { verbose(env, "invalid stack off=%d size=%d\n", off, size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (t == BPF_WRITE) err = check_stack_write(env, state, off, size, value_regno); else err = check_stack_read(env, state, off, size, value_regno); } else if (reg_is_pkt_pointer(reg)) { if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { verbose(env, "cannot write into packet\n"); return -EACCES; } if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into packet\n", value_regno); return -EACCES; } err = check_packet_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else { verbose(env, "R%d invalid mem access '%s'\n", regno, reg_type_str[reg->type]); return -EACCES; } if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && regs[value_regno].type == SCALAR_VALUE) { /* b/h/w load zero-extends, mark upper bits as known 0 */ regs[value_regno].var_off = tnum_cast(regs[value_regno].var_off, size); __update_reg_bounds(&regs[value_regno]); } return err; } static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) { int err; if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) || insn->imm != 0) { verbose(env, "BPF_XADD uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d leaks addr into mem\n", insn->src_reg); return -EACCES; } /* check whether atomic_add can read the memory */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, -1); if (err) return err; /* check whether atomic_add can write into the same memory */ return check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); } /* Does this register contain a constant zero? */ static bool register_is_null(struct bpf_reg_state reg) { return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0); } /* when register 'regno' is passed into function that will read 'access_size' * bytes from that pointer, make sure that it's within stack boundary * and all elements of stack are initialized. * Unlike most pointer bounds-checking functions, this one doesn't take an * 'off' argument, so it has to add in reg->off itself. */ static int check_stack_boundary(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs; int off, i, slot, spi; if (regs[regno].type != PTR_TO_STACK) { /* Allow zero-byte read from NULL, regardless of pointer type */ if (zero_size_allowed && access_size == 0 && register_is_null(regs[regno])) return 0; verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[regs[regno].type], reg_type_str[PTR_TO_STACK]); return -EACCES; } /* Only allow fixed-offset stack reads */ if (!tnum_is_const(regs[regno].var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off); verbose(env, "invalid variable stack read R%d var_off=%s\n", regno, tn_buf); } off = regs[regno].off + regs[regno].var_off.value; if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || access_size < 0 || (access_size == 0 && !zero_size_allowed)) { verbose(env, "invalid stack type R%d off=%d access_size=%d\n", regno, off, access_size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (meta && meta->raw_mode) { meta->access_size = access_size; meta->regno = regno; return 0; } for (i = 0; i < access_size; i++) { slot = -(off + i) - 1; spi = slot / BPF_REG_SIZE; if (state->allocated_stack <= slot || state->stack[spi].slot_type[slot % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid indirect read from stack off %d+%d size %d\n", off, i, access_size); return -EACCES; } } return 0; } static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno]; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: return check_packet_access(env, regno, reg->off, access_size, zero_size_allowed); case PTR_TO_MAP_VALUE: return check_map_access(env, regno, reg->off, access_size, zero_size_allowed); default: /* scalar_value|ptr_to_stack or invalid ptr */ return check_stack_boundary(env, regno, access_size, zero_size_allowed, meta); } } static int check_func_arg(struct bpf_verifier_env *env, u32 regno, enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta) { struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno]; enum bpf_reg_type expected_type, type = reg->type; int err = 0; if (arg_type == ARG_DONTCARE) return 0; err = check_reg_arg(env, regno, SRC_OP); if (err) return err; if (arg_type == ARG_ANYTHING) { if (is_pointer_value(env, regno)) { verbose(env, "R%d leaks addr into helper function\n", regno); return -EACCES; } return 0; } if (type_is_pkt_pointer(type) && !may_access_direct_pkt_data(env, meta, BPF_READ)) { verbose(env, "helper access to the packet is not allowed\n"); return -EACCES; } if (arg_type == ARG_PTR_TO_MAP_KEY || arg_type == ARG_PTR_TO_MAP_VALUE) { expected_type = PTR_TO_STACK; if (!type_is_pkt_pointer(type) && type != expected_type) goto err_type; } else if (arg_type == ARG_CONST_SIZE || arg_type == ARG_CONST_SIZE_OR_ZERO) { expected_type = SCALAR_VALUE; if (type != expected_type) goto err_type; } else if (arg_type == ARG_CONST_MAP_PTR) { expected_type = CONST_PTR_TO_MAP; if (type != expected_type) goto err_type; } else if (arg_type == ARG_PTR_TO_CTX) { expected_type = PTR_TO_CTX; if (type != expected_type) goto err_type; } else if (arg_type == ARG_PTR_TO_MEM || arg_type == ARG_PTR_TO_MEM_OR_NULL || arg_type == ARG_PTR_TO_UNINIT_MEM) { expected_type = PTR_TO_STACK; /* One exception here. In case function allows for NULL to be * passed in as argument, it's a SCALAR_VALUE type. Final test * happens during stack boundary checking. */ if (register_is_null(*reg) && arg_type == ARG_PTR_TO_MEM_OR_NULL) /* final test in check_stack_boundary() */; else if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE && type != expected_type) goto err_type; meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM; } else { verbose(env, "unsupported arg_type %d\n", arg_type); return -EFAULT; } if (arg_type == ARG_CONST_MAP_PTR) { /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ meta->map_ptr = reg->map_ptr; } else if (arg_type == ARG_PTR_TO_MAP_KEY) { /* bpf_map_xxx(..., map_ptr, ..., key) call: * check that [key, key + map->key_size) are within * stack limits and initialized */ if (!meta->map_ptr) { /* in function declaration map_ptr must come before * map_key, so that it's verified and known before * we have to check map_key here. Otherwise it means * that kernel subsystem misconfigured verifier */ verbose(env, "invalid map_ptr to access map->key\n"); return -EACCES; } if (type_is_pkt_pointer(type)) err = check_packet_access(env, regno, reg->off, meta->map_ptr->key_size, false); else err = check_stack_boundary(env, regno, meta->map_ptr->key_size, false, NULL); } else if (arg_type == ARG_PTR_TO_MAP_VALUE) { /* bpf_map_xxx(..., map_ptr, ..., value) call: * check [value, value + map->value_size) validity */ if (!meta->map_ptr) { /* kernel subsystem misconfigured verifier */ verbose(env, "invalid map_ptr to access map->value\n"); return -EACCES; } if (type_is_pkt_pointer(type)) err = check_packet_access(env, regno, reg->off, meta->map_ptr->value_size, false); else err = check_stack_boundary(env, regno, meta->map_ptr->value_size, false, NULL); } else if (arg_type == ARG_CONST_SIZE || arg_type == ARG_CONST_SIZE_OR_ZERO) { bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); /* bpf_xxx(..., buf, len) call will access 'len' bytes * from stack pointer 'buf'. Check it * note: regno == len, regno - 1 == buf */ if (regno == 0) { /* kernel subsystem misconfigured verifier */ verbose(env, "ARG_CONST_SIZE cannot be first argument\n"); return -EACCES; } /* The register is SCALAR_VALUE; the access check * happens using its boundaries. */ if (!tnum_is_const(reg->var_off)) /* For unprivileged variable accesses, disable raw * mode so that the program is required to * initialize all the memory that the helper could * just partially fill up. */ meta = NULL; if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", regno); return -EACCES; } if (reg->umin_value == 0) { err = check_helper_mem_access(env, regno - 1, 0, zero_size_allowed, meta); if (err) return err; } if (reg->umax_value >= BPF_MAX_VAR_SIZ) { verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", regno); return -EACCES; } err = check_helper_mem_access(env, regno - 1, reg->umax_value, zero_size_allowed, meta); } return err; err_type: verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[type], reg_type_str[expected_type]); return -EACCES; } static int check_map_func_compatibility(struct bpf_verifier_env *env, struct bpf_map *map, int func_id) { if (!map) return 0; /* We need a two way check, first is from map perspective ... */ switch (map->map_type) { case BPF_MAP_TYPE_PROG_ARRAY: if (func_id != BPF_FUNC_tail_call) goto error; break; case BPF_MAP_TYPE_PERF_EVENT_ARRAY: if (func_id != BPF_FUNC_perf_event_read && func_id != BPF_FUNC_perf_event_output && func_id != BPF_FUNC_perf_event_read_value) goto error; break; case BPF_MAP_TYPE_STACK_TRACE: if (func_id != BPF_FUNC_get_stackid) goto error; break; case BPF_MAP_TYPE_CGROUP_ARRAY: if (func_id != BPF_FUNC_skb_under_cgroup && func_id != BPF_FUNC_current_task_under_cgroup) goto error; break; /* devmap returns a pointer to a live net_device ifindex that we cannot * allow to be modified from bpf side. So do not allow lookup elements * for now. */ case BPF_MAP_TYPE_DEVMAP: if (func_id != BPF_FUNC_redirect_map) goto error; break; /* Restrict bpf side of cpumap, open when use-cases appear */ case BPF_MAP_TYPE_CPUMAP: if (func_id != BPF_FUNC_redirect_map) goto error; break; case BPF_MAP_TYPE_ARRAY_OF_MAPS: case BPF_MAP_TYPE_HASH_OF_MAPS: if (func_id != BPF_FUNC_map_lookup_elem) goto error; break; case BPF_MAP_TYPE_SOCKMAP: if (func_id != BPF_FUNC_sk_redirect_map && func_id != BPF_FUNC_sock_map_update && func_id != BPF_FUNC_map_delete_elem) goto error; break; default: break; } /* ... and second from the function itself. */ switch (func_id) { case BPF_FUNC_tail_call: if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) goto error; break; case BPF_FUNC_perf_event_read: case BPF_FUNC_perf_event_output: case BPF_FUNC_perf_event_read_value: if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) goto error; break; case BPF_FUNC_get_stackid: if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) goto error; break; case BPF_FUNC_current_task_under_cgroup: case BPF_FUNC_skb_under_cgroup: if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) goto error; break; case BPF_FUNC_redirect_map: if (map->map_type != BPF_MAP_TYPE_DEVMAP && map->map_type != BPF_MAP_TYPE_CPUMAP) goto error; break; case BPF_FUNC_sk_redirect_map: if (map->map_type != BPF_MAP_TYPE_SOCKMAP) goto error; break; case BPF_FUNC_sock_map_update: if (map->map_type != BPF_MAP_TYPE_SOCKMAP) goto error; break; default: break; } return 0; error: verbose(env, "cannot pass map_type %d into func %s#%d\n", map->map_type, func_id_name(func_id), func_id); return -EINVAL; } static int check_raw_mode(const struct bpf_func_proto *fn) { int count = 0; if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) count++; return count > 1 ? -EINVAL : 0; } /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] * are now invalid, so turn them into unknown SCALAR_VALUE. */ static void clear_all_pkt_pointers(struct bpf_verifier_env *env) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs, *reg; int i; for (i = 0; i < MAX_BPF_REG; i++) if (reg_is_pkt_pointer_any(&regs[i])) mark_reg_unknown(env, regs, i); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; reg = &state->stack[i].spilled_ptr; if (reg_is_pkt_pointer_any(reg)) __mark_reg_unknown(reg); } } static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx) { const struct bpf_func_proto *fn = NULL; struct bpf_reg_state *regs; struct bpf_call_arg_meta meta; bool changes_data; int i, err; /* find function prototype */ if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } if (env->ops->get_func_proto) fn = env->ops->get_func_proto(func_id); if (!fn) { verbose(env, "unknown func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } /* eBPF programs must be GPL compatible to use GPL-ed functions */ if (!env->prog->gpl_compatible && fn->gpl_only) { verbose(env, "cannot call GPL only function from proprietary program\n"); return -EINVAL; } /* With LD_ABS/IND some JITs save/restore skb from r1. */ changes_data = bpf_helper_changes_pkt_data(fn->func); if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", func_id_name(func_id), func_id); return -EINVAL; } memset(&meta, 0, sizeof(meta)); meta.pkt_access = fn->pkt_access; /* We only support one arg being in raw mode at the moment, which * is sufficient for the helper functions we have right now. */ err = check_raw_mode(fn); if (err) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(func_id), func_id); return err; } /* check args */ err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta); if (err) return err; /* Mark slots with STACK_MISC in case of raw mode, stack offset * is inferred from register state. */ for (i = 0; i < meta.access_size; i++) { err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1); if (err) return err; } regs = cur_regs(env); /* reset caller saved regs */ for (i = 0; i < CALLER_SAVED_REGS; i++) { mark_reg_not_init(env, regs, caller_saved[i]); check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); } /* update return register (already marked as written above) */ if (fn->ret_type == RET_INTEGER) { /* sets type to SCALAR_VALUE */ mark_reg_unknown(env, regs, BPF_REG_0); } else if (fn->ret_type == RET_VOID) { regs[BPF_REG_0].type = NOT_INIT; } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) { struct bpf_insn_aux_data *insn_aux; regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; /* There is no offset yet applied, variable or fixed */ mark_reg_known_zero(env, regs, BPF_REG_0); regs[BPF_REG_0].off = 0; /* remember map_ptr, so that check_map_access() * can check 'value_size' boundary of memory access * to map element returned from bpf_map_lookup_elem() */ if (meta.map_ptr == NULL) { verbose(env, "kernel subsystem misconfigured verifier\n"); return -EINVAL; } regs[BPF_REG_0].map_ptr = meta.map_ptr; regs[BPF_REG_0].id = ++env->id_gen; insn_aux = &env->insn_aux_data[insn_idx]; if (!insn_aux->map_ptr) insn_aux->map_ptr = meta.map_ptr; else if (insn_aux->map_ptr != meta.map_ptr) insn_aux->map_ptr = BPF_MAP_PTR_POISON; } else { verbose(env, "unknown return type %d of func %s#%d\n", fn->ret_type, func_id_name(func_id), func_id); return -EINVAL; } err = check_map_func_compatibility(env, meta.map_ptr, func_id); if (err) return err; if (changes_data) clear_all_pkt_pointers(env); return 0; } static void coerce_reg_to_32(struct bpf_reg_state *reg) { /* clear high 32 bits */ reg->var_off = tnum_cast(reg->var_off, 4); /* Update bounds */ __update_reg_bounds(reg); } static bool signed_add_overflows(s64 a, s64 b) { /* Do the add in u64, where overflow is well-defined */ s64 res = (s64)((u64)a + (u64)b); if (b < 0) return res > a; return res < a; } static bool signed_sub_overflows(s64 a, s64 b) { /* Do the sub in u64, where overflow is well-defined */ s64 res = (s64)((u64)a - (u64)b); if (b < 0) return res < a; return res > a; } /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. * Caller should also handle BPF_MOV case separately. * If we return -EACCES, caller may want to try again treating pointer as a * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. */ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg) { struct bpf_reg_state *regs = cur_regs(env), *dst_reg; bool known = tnum_is_const(off_reg->var_off); s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; u8 opcode = BPF_OP(insn->code); u32 dst = insn->dst_reg; dst_reg = &regs[dst]; if (WARN_ON_ONCE(known && (smin_val != smax_val))) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: known but bad sbounds\n"); return -EINVAL; } if (WARN_ON_ONCE(known && (umin_val != umax_val))) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: known but bad ubounds\n"); return -EINVAL; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops on pointers produce (meaningless) scalars */ if (!env->allow_ptr_leaks) verbose(env, "R%d 32-bit pointer arithmetic prohibited\n", dst); return -EACCES; } if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n", dst); return -EACCES; } if (ptr_reg->type == CONST_PTR_TO_MAP) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n", dst); return -EACCES; } if (ptr_reg->type == PTR_TO_PACKET_END) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n", dst); return -EACCES; } /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. * The id may be overwritten later if we create a new variable offset. */ dst_reg->type = ptr_reg->type; dst_reg->id = ptr_reg->id; switch (opcode) { case BPF_ADD: /* We can take a fixed offset as long as it doesn't overflow * the s32 'off' field */ if (known && (ptr_reg->off + smin_val == (s64)(s32)(ptr_reg->off + smin_val))) { /* pointer += K. Accumulate it into fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->off = ptr_reg->off + smin_val; dst_reg->range = ptr_reg->range; break; } /* A new variable offset is created. Note that off_reg->off * == 0, since it's a scalar. * dst_reg gets the pointer type and since some positive * integer value was added to the pointer, give it a new 'id' * if it's a PTR_TO_PACKET. * this creates a new 'base' pointer, off_reg (variable) gets * added into the variable offset, and we copy the fixed offset * from ptr_reg. */ if (signed_add_overflows(smin_ptr, smin_val) || signed_add_overflows(smax_ptr, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr + smin_val; dst_reg->smax_value = smax_ptr + smax_val; } if (umin_ptr + umin_val < umin_ptr || umax_ptr + umax_val < umax_ptr) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value = umin_ptr + umin_val; dst_reg->umax_value = umax_ptr + umax_val; } dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ dst_reg->range = 0; } break; case BPF_SUB: if (dst_reg == off_reg) { /* scalar -= pointer. Creates an unknown scalar */ if (!env->allow_ptr_leaks) verbose(env, "R%d tried to subtract pointer from scalar\n", dst); return -EACCES; } /* We don't allow subtraction from FP, because (according to * test_verifier.c test "invalid fp arithmetic", JITs might not * be able to deal with it. */ if (ptr_reg->type == PTR_TO_STACK) { if (!env->allow_ptr_leaks) verbose(env, "R%d subtraction from stack pointer prohibited\n", dst); return -EACCES; } if (known && (ptr_reg->off - smin_val == (s64)(s32)(ptr_reg->off - smin_val))) { /* pointer -= K. Subtract it from fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->id = ptr_reg->id; dst_reg->off = ptr_reg->off - smin_val; dst_reg->range = ptr_reg->range; break; } /* A new variable offset is created. If the subtrahend is known * nonnegative, then any reg->range we had before is still good. */ if (signed_sub_overflows(smin_ptr, smax_val) || signed_sub_overflows(smax_ptr, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr - smax_val; dst_reg->smax_value = smax_ptr - smin_val; } if (umin_ptr < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value = umin_ptr - umax_val; dst_reg->umax_value = umax_ptr - umin_val; } dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ if (smin_val < 0) dst_reg->range = 0; } break; case BPF_AND: case BPF_OR: case BPF_XOR: /* bitwise ops on pointers are troublesome, prohibit for now. * (However, in principle we could allow some cases, e.g. * ptr &= ~3 which would reduce min_value by 3.) */ if (!env->allow_ptr_leaks) verbose(env, "R%d bitwise operator %s on pointer prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; default: /* other operators (e.g. MUL,LSH) produce non-pointer results */ if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; } __update_reg_bounds(dst_reg); __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->64 */ coerce_reg_to_32(dst_reg); coerce_reg_to_32(&src_reg); } smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val > 63) { /* Shifts greater than 63 are undefined. This includes * shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } if (src_known) dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val > 63) { /* Shifts greater than 63 are undefined. This includes * shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; if (src_known) dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max * and var_off. */ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg; struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; u8 opcode = BPF_OP(insn->code); int rc; dst_reg = &regs[insn->dst_reg]; src_reg = NULL; if (dst_reg->type != SCALAR_VALUE) ptr_reg = dst_reg; if (BPF_SRC(insn->code) == BPF_X) { src_reg = &regs[insn->src_reg]; if (src_reg->type != SCALAR_VALUE) { if (dst_reg->type != SCALAR_VALUE) { /* Combining two pointers by any ALU op yields * an arbitrary scalar. */ if (!env->allow_ptr_leaks) { verbose(env, "R%d pointer %s pointer prohibited\n", insn->dst_reg, bpf_alu_string[opcode >> 4]); return -EACCES; } mark_reg_unknown(env, regs, insn->dst_reg); return 0; } else { /* scalar += pointer * This is legal, but we have to reverse our * src/dest handling in computing the range */ rc = adjust_ptr_min_max_vals(env, insn, src_reg, dst_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* scalar += unknown scalar */ __mark_reg_unknown(&off_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, off_reg); } return rc; } } else if (ptr_reg) { /* pointer += scalar */ rc = adjust_ptr_min_max_vals(env, insn, dst_reg, src_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* unknown scalar += scalar */ __mark_reg_unknown(dst_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, *src_reg); } return rc; } } else { /* Pretend the src is a reg with a known value, since we only * need to be able to read from this state. */ off_reg.type = SCALAR_VALUE; __mark_reg_known(&off_reg, insn->imm); src_reg = &off_reg; if (ptr_reg) { /* pointer += K */ rc = adjust_ptr_min_max_vals(env, insn, ptr_reg, src_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* unknown scalar += K */ __mark_reg_unknown(dst_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, off_reg); } return rc; } } /* Got here implies adding two SCALAR_VALUEs */ if (WARN_ON_ONCE(ptr_reg)) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: unexpected ptr_reg\n"); return -EINVAL; } if (WARN_ON(!src_reg)) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: no src_reg\n"); return -EINVAL; } return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); } /* check validity of 32-bit and 64-bit arithmetic operations */ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); int err; if (opcode == BPF_END || opcode == BPF_NEG) { if (opcode == BPF_NEG) { if (BPF_SRC(insn->code) != 0 || insn->src_reg != BPF_REG_0 || insn->off != 0 || insn->imm != 0) { verbose(env, "BPF_NEG uses reserved fields\n"); return -EINVAL; } } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0 || (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || BPF_CLASS(insn->code) == BPF_ALU64) { verbose(env, "BPF_END uses reserved fields\n"); return -EINVAL; } } /* check src operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer arithmetic prohibited\n", insn->dst_reg); return -EACCES; } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; } else if (opcode == BPF_MOV) { if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose(env, "BPF_MOV uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose(env, "BPF_MOV uses reserved fields\n"); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; if (BPF_SRC(insn->code) == BPF_X) { if (BPF_CLASS(insn->code) == BPF_ALU64) { /* case: R1 = R2 * copy register state to dest reg */ regs[insn->dst_reg] = regs[insn->src_reg]; regs[insn->dst_reg].live |= REG_LIVE_WRITTEN; } else { /* R1 = (u32) R2 */ if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d partial copy of pointer\n", insn->src_reg); return -EACCES; } mark_reg_unknown(env, regs, insn->dst_reg); /* high 32 bits are known zero. */ regs[insn->dst_reg].var_off = tnum_cast( regs[insn->dst_reg].var_off, 4); __update_reg_bounds(&regs[insn->dst_reg]); } } else { /* case: R = imm * remember the value we stored into this reg */ regs[insn->dst_reg].type = SCALAR_VALUE; __mark_reg_known(regs + insn->dst_reg, insn->imm); } } else if (opcode > BPF_END) { verbose(env, "invalid BPF_ALU opcode %x\n", opcode); return -EINVAL; } else { /* all other ALU ops: and, sub, xor, add, ... */ if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose(env, "BPF_ALU uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose(env, "BPF_ALU uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if ((opcode == BPF_MOD || opcode == BPF_DIV) && BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { verbose(env, "div by zero\n"); return -EINVAL; } if ((opcode == BPF_LSH || opcode == BPF_RSH || opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; if (insn->imm < 0 || insn->imm >= size) { verbose(env, "invalid shift %d\n", insn->imm); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; return adjust_reg_min_max_vals(env, insn); } return 0; } static void find_good_pkt_pointers(struct bpf_verifier_state *state, struct bpf_reg_state *dst_reg, enum bpf_reg_type type, bool range_right_open) { struct bpf_reg_state *regs = state->regs, *reg; u16 new_range; int i; if (dst_reg->off < 0 || (dst_reg->off == 0 && range_right_open)) /* This doesn't give us any range */ return; if (dst_reg->umax_value > MAX_PACKET_OFF || dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) /* Risk of overflow. For instance, ptr + (1<<63) may be less * than pkt_end, but that's because it's also less than pkt. */ return; new_range = dst_reg->off; if (range_right_open) new_range--; /* Examples for register markings: * * pkt_data in dst register: * * r2 = r3; * r2 += 8; * if (r2 > pkt_end) goto <handle exception> * <access okay> * * r2 = r3; * r2 += 8; * if (r2 < pkt_end) goto <access okay> * <handle exception> * * Where: * r2 == dst_reg, pkt_end == src_reg * r2=pkt(id=n,off=8,r=0) * r3=pkt(id=n,off=0,r=0) * * pkt_data in src register: * * r2 = r3; * r2 += 8; * if (pkt_end >= r2) goto <access okay> * <handle exception> * * r2 = r3; * r2 += 8; * if (pkt_end <= r2) goto <handle exception> * <access okay> * * Where: * pkt_end == dst_reg, r2 == src_reg * r2=pkt(id=n,off=8,r=0) * r3=pkt(id=n,off=0,r=0) * * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) * and [r3, r3 + 8-1) respectively is safe to access depending on * the check. */ /* If our ids match, then we must have the same max_value. And we * don't care about the other reg's fixed offset, since if it's too big * the range won't allow anything. * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. */ for (i = 0; i < MAX_BPF_REG; i++) if (regs[i].type == type && regs[i].id == dst_reg->id) /* keep the maximum range already checked */ regs[i].range = max(regs[i].range, new_range); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; reg = &state->stack[i].spilled_ptr; if (reg->type == type && reg->id == dst_reg->id) reg->range = max(reg->range, new_range); } } /* Adjusts the register min/max values in the case that the dst_reg is the * variable register that we are working on, and src_reg is a constant or we're * simply doing a BPF_K check. * In JEQ/JNE cases we also adjust the var_off values. */ static void reg_set_min_max(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { /* If the dst_reg is a pointer, we can't learn anything about its * variable offset from the compare (unless src_reg were a pointer into * the same object, but we don't bother with that. * Since false_reg and true_reg have the same type by construction, we * only need to check one of them for pointerness. */ if (__is_pointer_value(false, false_reg)) return; switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ __mark_reg_known(true_reg, val); break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ __mark_reg_known(false_reg, val); break; case BPF_JGT: false_reg->umax_value = min(false_reg->umax_value, val); true_reg->umin_value = max(true_reg->umin_value, val + 1); break; case BPF_JSGT: false_reg->smax_value = min_t(s64, false_reg->smax_value, val); true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); break; case BPF_JLT: false_reg->umin_value = max(false_reg->umin_value, val); true_reg->umax_value = min(true_reg->umax_value, val - 1); break; case BPF_JSLT: false_reg->smin_value = max_t(s64, false_reg->smin_value, val); true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); break; case BPF_JGE: false_reg->umax_value = min(false_reg->umax_value, val - 1); true_reg->umin_value = max(true_reg->umin_value, val); break; case BPF_JSGE: false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); true_reg->smin_value = max_t(s64, true_reg->smin_value, val); break; case BPF_JLE: false_reg->umin_value = max(false_reg->umin_value, val + 1); true_reg->umax_value = min(true_reg->umax_value, val); break; case BPF_JSLE: false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); true_reg->smax_value = min_t(s64, true_reg->smax_value, val); break; default: break; } __reg_deduce_bounds(false_reg); __reg_deduce_bounds(true_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(false_reg); __reg_bound_offset(true_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(false_reg); __update_reg_bounds(true_reg); } /* Same as above, but for the case that dst_reg holds a constant and src_reg is * the variable reg. */ static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { if (__is_pointer_value(false, false_reg)) return; switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ __mark_reg_known(true_reg, val); break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ __mark_reg_known(false_reg, val); break; case BPF_JGT: true_reg->umax_value = min(true_reg->umax_value, val - 1); false_reg->umin_value = max(false_reg->umin_value, val); break; case BPF_JSGT: true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); false_reg->smin_value = max_t(s64, false_reg->smin_value, val); break; case BPF_JLT: true_reg->umin_value = max(true_reg->umin_value, val + 1); false_reg->umax_value = min(false_reg->umax_value, val); break; case BPF_JSLT: true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); false_reg->smax_value = min_t(s64, false_reg->smax_value, val); break; case BPF_JGE: true_reg->umax_value = min(true_reg->umax_value, val); false_reg->umin_value = max(false_reg->umin_value, val + 1); break; case BPF_JSGE: true_reg->smax_value = min_t(s64, true_reg->smax_value, val); false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); break; case BPF_JLE: true_reg->umin_value = max(true_reg->umin_value, val); false_reg->umax_value = min(false_reg->umax_value, val - 1); break; case BPF_JSLE: true_reg->smin_value = max_t(s64, true_reg->smin_value, val); false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); break; default: break; } __reg_deduce_bounds(false_reg); __reg_deduce_bounds(true_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(false_reg); __reg_bound_offset(true_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(false_reg); __update_reg_bounds(true_reg); } /* Regs are known to be equal, so intersect their min/max/var_off */ static void __reg_combine_min_max(struct bpf_reg_state *src_reg, struct bpf_reg_state *dst_reg) { src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, dst_reg->umin_value); src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, dst_reg->umax_value); src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, dst_reg->smin_value); src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, dst_reg->smax_value); src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, dst_reg->var_off); /* We might have learned new bounds from the var_off. */ __update_reg_bounds(src_reg); __update_reg_bounds(dst_reg); /* We might have learned something about the sign bit. */ __reg_deduce_bounds(src_reg); __reg_deduce_bounds(dst_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(src_reg); __reg_bound_offset(dst_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(src_reg); __update_reg_bounds(dst_reg); } static void reg_combine_min_max(struct bpf_reg_state *true_src, struct bpf_reg_state *true_dst, struct bpf_reg_state *false_src, struct bpf_reg_state *false_dst, u8 opcode) { switch (opcode) { case BPF_JEQ: __reg_combine_min_max(true_src, true_dst); break; case BPF_JNE: __reg_combine_min_max(false_src, false_dst); break; } } static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id, bool is_null) { struct bpf_reg_state *reg = &regs[regno]; if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) { /* Old offset (both fixed and variable parts) should * have been known-zero, because we don't allow pointer * arithmetic on pointers that might be NULL. */ if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0) || reg->off)) { __mark_reg_known_zero(reg); reg->off = 0; } if (is_null) { reg->type = SCALAR_VALUE; } else if (reg->map_ptr->inner_map_meta) { reg->type = CONST_PTR_TO_MAP; reg->map_ptr = reg->map_ptr->inner_map_meta; } else { reg->type = PTR_TO_MAP_VALUE; } /* We don't need id from this point onwards anymore, thus we * should better reset it, so that state pruning has chances * to take effect. */ reg->id = 0; } } /* The logic is similar to find_good_pkt_pointers(), both could eventually * be folded together at some point. */ static void mark_map_regs(struct bpf_verifier_state *state, u32 regno, bool is_null) { struct bpf_reg_state *regs = state->regs; u32 id = regs[regno].id; int i; for (i = 0; i < MAX_BPF_REG; i++) mark_map_reg(regs, i, id, is_null); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null); } } static bool try_match_pkt_pointers(const struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg, struct bpf_verifier_state *this_branch, struct bpf_verifier_state *other_branch) { if (BPF_SRC(insn->code) != BPF_X) return false; switch (BPF_OP(insn->code)) { case BPF_JGT: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ find_good_pkt_pointers(this_branch, dst_reg, dst_reg->type, false); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end > pkt_data', pkt_data > pkt_meta' */ find_good_pkt_pointers(other_branch, src_reg, src_reg->type, true); } else { return false; } break; case BPF_JLT: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ find_good_pkt_pointers(other_branch, dst_reg, dst_reg->type, true); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end < pkt_data', pkt_data > pkt_meta' */ find_good_pkt_pointers(this_branch, src_reg, src_reg->type, false); } else { return false; } break; case BPF_JGE: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ find_good_pkt_pointers(this_branch, dst_reg, dst_reg->type, true); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ find_good_pkt_pointers(other_branch, src_reg, src_reg->type, false); } else { return false; } break; case BPF_JLE: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ find_good_pkt_pointers(other_branch, dst_reg, dst_reg->type, false); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ find_good_pkt_pointers(this_branch, src_reg, src_reg->type, true); } else { return false; } break; default: return false; } return true; } static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct bpf_verifier_state *other_branch, *this_branch = env->cur_state; struct bpf_reg_state *regs = this_branch->regs, *dst_reg; u8 opcode = BPF_OP(insn->code); int err; if (opcode > BPF_JSLE) { verbose(env, "invalid BPF_JMP opcode %x\n", opcode); return -EINVAL; } if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->src_reg); return -EACCES; } } else { if (insn->src_reg != BPF_REG_0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg = &regs[insn->dst_reg]; /* detect if R == 0 where R was initialized to zero earlier */ if (BPF_SRC(insn->code) == BPF_K && (opcode == BPF_JEQ || opcode == BPF_JNE) && dst_reg->type == SCALAR_VALUE && tnum_equals_const(dst_reg->var_off, insn->imm)) { if (opcode == BPF_JEQ) { /* if (imm == imm) goto pc+off; * only follow the goto, ignore fall-through */ *insn_idx += insn->off; return 0; } else { /* if (imm != imm) goto pc+off; * only follow fall-through branch, since * that's where the program will go */ return 0; } } other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx); if (!other_branch) return -EFAULT; /* detect if we are comparing against a constant value so we can adjust * our min/max values for our dst register. * this is only legit if both are scalars (or pointers to the same * object, I suppose, but we don't support that right now), because * otherwise the different base pointers mean the offsets aren't * comparable. */ if (BPF_SRC(insn->code) == BPF_X) { if (dst_reg->type == SCALAR_VALUE && regs[insn->src_reg].type == SCALAR_VALUE) { if (tnum_is_const(regs[insn->src_reg].var_off)) reg_set_min_max(&other_branch->regs[insn->dst_reg], dst_reg, regs[insn->src_reg].var_off.value, opcode); else if (tnum_is_const(dst_reg->var_off)) reg_set_min_max_inv(&other_branch->regs[insn->src_reg], &regs[insn->src_reg], dst_reg->var_off.value, opcode); else if (opcode == BPF_JEQ || opcode == BPF_JNE) /* Comparing for equality, we can combine knowledge */ reg_combine_min_max(&other_branch->regs[insn->src_reg], &other_branch->regs[insn->dst_reg], &regs[insn->src_reg], &regs[insn->dst_reg], opcode); } } else if (dst_reg->type == SCALAR_VALUE) { reg_set_min_max(&other_branch->regs[insn->dst_reg], dst_reg, insn->imm, opcode); } /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ if (BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { /* Mark all identical map registers in each branch as either * safe or unknown depending R == 0 or R != 0 conditional. */ mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg], this_branch, other_branch) && is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->dst_reg); return -EACCES; } if (env->log.level) print_verifier_state(env, this_branch); return 0; } /* return the map pointer stored inside BPF_LD_IMM64 instruction */ static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn) { u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32; return (struct bpf_map *) (unsigned long) imm64; } /* verify BPF_LD_IMM64 instruction */ static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); int err; if (BPF_SIZE(insn->code) != BPF_DW) { verbose(env, "invalid BPF_LD_IMM insn\n"); return -EINVAL; } if (insn->off != 0) { verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); return -EINVAL; } err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; if (insn->src_reg == 0) { u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; regs[insn->dst_reg].type = SCALAR_VALUE; __mark_reg_known(&regs[insn->dst_reg], imm); return 0; } /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */ BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD); regs[insn->dst_reg].type = CONST_PTR_TO_MAP; regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn); return 0; } static bool may_access_skb(enum bpf_prog_type type) { switch (type) { case BPF_PROG_TYPE_SOCKET_FILTER: case BPF_PROG_TYPE_SCHED_CLS: case BPF_PROG_TYPE_SCHED_ACT: return true; default: return false; } } /* verify safety of LD_ABS|LD_IND instructions: * - they can only appear in the programs where ctx == skb * - since they are wrappers of function calls, they scratch R1-R5 registers, * preserve R6-R9, and store return value into R0 * * Implicit input: * ctx == skb == R6 == CTX * * Explicit input: * SRC == any register * IMM == 32-bit immediate * * Output: * R0 - 8/16/32-bit skb data converted to cpu endianness */ static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); u8 mode = BPF_MODE(insn->code); int i, err; if (!may_access_skb(env->prog->type)) { verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); return -EINVAL; } if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || BPF_SIZE(insn->code) == BPF_DW || (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); return -EINVAL; } /* check whether implicit source operand (register R6) is readable */ err = check_reg_arg(env, BPF_REG_6, SRC_OP); if (err) return err; if (regs[BPF_REG_6].type != PTR_TO_CTX) { verbose(env, "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); return -EINVAL; } if (mode == BPF_IND) { /* check explicit source operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } /* reset caller saved regs to unreadable */ for (i = 0; i < CALLER_SAVED_REGS; i++) { mark_reg_not_init(env, regs, caller_saved[i]); check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); } /* mark destination R0 register as readable, since it contains * the value fetched from the packet. * Already marked as written above. */ mark_reg_unknown(env, regs, BPF_REG_0); return 0; } static int check_return_code(struct bpf_verifier_env *env) { struct bpf_reg_state *reg; struct tnum range = tnum_range(0, 1); switch (env->prog->type) { case BPF_PROG_TYPE_CGROUP_SKB: case BPF_PROG_TYPE_CGROUP_SOCK: case BPF_PROG_TYPE_SOCK_OPS: case BPF_PROG_TYPE_CGROUP_DEVICE: break; default: return 0; } reg = cur_regs(env) + BPF_REG_0; if (reg->type != SCALAR_VALUE) { verbose(env, "At program exit the register R0 is not a known value (%s)\n", reg_type_str[reg->type]); return -EINVAL; } if (!tnum_in(range, reg->var_off)) { verbose(env, "At program exit the register R0 "); if (!tnum_is_unknown(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "has value %s", tn_buf); } else { verbose(env, "has unknown scalar value"); } verbose(env, " should have been 0 or 1\n"); return -EINVAL; } return 0; } /* non-recursive DFS pseudo code * 1 procedure DFS-iterative(G,v): * 2 label v as discovered * 3 let S be a stack * 4 S.push(v) * 5 while S is not empty * 6 t <- S.pop() * 7 if t is what we're looking for: * 8 return t * 9 for all edges e in G.adjacentEdges(t) do * 10 if edge e is already labelled * 11 continue with the next edge * 12 w <- G.adjacentVertex(t,e) * 13 if vertex w is not discovered and not explored * 14 label e as tree-edge * 15 label w as discovered * 16 S.push(w) * 17 continue at 5 * 18 else if vertex w is discovered * 19 label e as back-edge * 20 else * 21 // vertex w is explored * 22 label e as forward- or cross-edge * 23 label t as explored * 24 S.pop() * * convention: * 0x10 - discovered * 0x11 - discovered and fall-through edge labelled * 0x12 - discovered and fall-through and branch edges labelled * 0x20 - explored */ enum { DISCOVERED = 0x10, EXPLORED = 0x20, FALLTHROUGH = 1, BRANCH = 2, }; #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L) static int *insn_stack; /* stack of insns to process */ static int cur_stack; /* current stack index */ static int *insn_state; /* t, w, e - match pseudo-code above: * t - index of current instruction * w - next instruction * e - edge */ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) { if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) return 0; if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) return 0; if (w < 0 || w >= env->prog->len) { verbose(env, "jump out of range from insn %d to %d\n", t, w); return -EINVAL; } if (e == BRANCH) /* mark branch target for state pruning */ env->explored_states[w] = STATE_LIST_MARK; if (insn_state[w] == 0) { /* tree-edge */ insn_state[t] = DISCOVERED | e; insn_state[w] = DISCOVERED; if (cur_stack >= env->prog->len) return -E2BIG; insn_stack[cur_stack++] = w; return 1; } else if ((insn_state[w] & 0xF0) == DISCOVERED) { verbose(env, "back-edge from insn %d to %d\n", t, w); return -EINVAL; } else if (insn_state[w] == EXPLORED) { /* forward- or cross-edge */ insn_state[t] = DISCOVERED | e; } else { verbose(env, "insn state internal bug\n"); return -EFAULT; } return 0; } /* non-recursive depth-first-search to detect loops in BPF program * loop == back-edge in directed graph */ static int check_cfg(struct bpf_verifier_env *env) { struct bpf_insn *insns = env->prog->insnsi; int insn_cnt = env->prog->len; int ret = 0; int i, t; insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); if (!insn_state) return -ENOMEM; insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); if (!insn_stack) { kfree(insn_state); return -ENOMEM; } insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ insn_stack[0] = 0; /* 0 is the first instruction */ cur_stack = 1; peek_stack: if (cur_stack == 0) goto check_state; t = insn_stack[cur_stack - 1]; if (BPF_CLASS(insns[t].code) == BPF_JMP) { u8 opcode = BPF_OP(insns[t].code); if (opcode == BPF_EXIT) { goto mark_explored; } else if (opcode == BPF_CALL) { ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; if (t + 1 < insn_cnt) env->explored_states[t + 1] = STATE_LIST_MARK; } else if (opcode == BPF_JA) { if (BPF_SRC(insns[t].code) != BPF_K) { ret = -EINVAL; goto err_free; } /* unconditional jump with single edge */ ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; /* tell verifier to check for equivalent states * after every call and jump */ if (t + 1 < insn_cnt) env->explored_states[t + 1] = STATE_LIST_MARK; } else { /* conditional jump with two edges */ env->explored_states[t] = STATE_LIST_MARK; ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; ret = push_insn(t, t + insns[t].off + 1, BRANCH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; } } else { /* all other non-branch instructions with single * fall-through edge */ ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; } mark_explored: insn_state[t] = EXPLORED; if (cur_stack-- <= 0) { verbose(env, "pop stack internal bug\n"); ret = -EFAULT; goto err_free; } goto peek_stack; check_state: for (i = 0; i < insn_cnt; i++) { if (insn_state[i] != EXPLORED) { verbose(env, "unreachable insn %d\n", i); ret = -EINVAL; goto err_free; } } ret = 0; /* cfg looks good */ err_free: kfree(insn_state); kfree(insn_stack); return ret; } /* check %cur's range satisfies %old's */ static bool range_within(struct bpf_reg_state *old, struct bpf_reg_state *cur) { return old->umin_value <= cur->umin_value && old->umax_value >= cur->umax_value && old->smin_value <= cur->smin_value && old->smax_value >= cur->smax_value; } /* Maximum number of register states that can exist at once */ #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) struct idpair { u32 old; u32 cur; }; /* If in the old state two registers had the same id, then they need to have * the same id in the new state as well. But that id could be different from * the old state, so we need to track the mapping from old to new ids. * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent * regs with old id 5 must also have new id 9 for the new state to be safe. But * regs with a different old id could still have new id 9, we don't care about * that. * So we look through our idmap to see if this old id has been seen before. If * so, we require the new id to match; otherwise, we add the id pair to the map. */ static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap) { unsigned int i; for (i = 0; i < ID_MAP_SIZE; i++) { if (!idmap[i].old) { /* Reached an empty slot; haven't seen this id before */ idmap[i].old = old_id; idmap[i].cur = cur_id; return true; } if (idmap[i].old == old_id) return idmap[i].cur == cur_id; } /* We ran out of idmap slots, which should be impossible */ WARN_ON_ONCE(1); return false; } /* Returns true if (rold safe implies rcur safe) */ static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, struct idpair *idmap) { if (!(rold->live & REG_LIVE_READ)) /* explored state didn't use this */ return true; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0) return true; if (rold->type == NOT_INIT) /* explored state can't have used this */ return true; if (rcur->type == NOT_INIT) return false; switch (rold->type) { case SCALAR_VALUE: if (rcur->type == SCALAR_VALUE) { /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); } else { /* if we knew anything about the old value, we're not * equal, because we can't know anything about the * scalar value of the pointer in the new value. */ return rold->umin_value == 0 && rold->umax_value == U64_MAX && rold->smin_value == S64_MIN && rold->smax_value == S64_MAX && tnum_is_unknown(rold->var_off); } case PTR_TO_MAP_VALUE: /* If the new min/max/var_off satisfy the old ones and * everything else matches, we are OK. * We don't care about the 'id' value, because nothing * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) */ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_MAP_VALUE_OR_NULL: /* a PTR_TO_MAP_VALUE could be safe to use as a * PTR_TO_MAP_VALUE_OR_NULL into the same map. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- * checked, doing so could have affected others with the same * id, and we can't check for that because we lost the id when * we converted to a PTR_TO_MAP_VALUE. */ if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) return false; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) return false; /* Check our ids match any regs they're supposed to */ return check_ids(rold->id, rcur->id, idmap); case PTR_TO_PACKET_META: case PTR_TO_PACKET: if (rcur->type != rold->type) return false; /* We must have at least as much range as the old ptr * did, so that any accesses which were safe before are * still safe. This is true even if old range < old off, * since someone could have accessed through (ptr - k), or * even done ptr -= k in a register, to get a safe access. */ if (rold->range > rcur->range) return false; /* If the offsets don't match, we can't trust our alignment; * nor can we be sure that we won't fall out of range. */ if (rold->off != rcur->off) return false; /* id relations must be preserved */ if (rold->id && !check_ids(rold->id, rcur->id, idmap)) return false; /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_CTX: case CONST_PTR_TO_MAP: case PTR_TO_STACK: case PTR_TO_PACKET_END: /* Only valid matches are exact, which memcmp() above * would have accepted */ default: /* Don't know what's going on, just say it's not safe */ return false; } /* Shouldn't get here; if we do, say it's not safe */ WARN_ON_ONCE(1); return false; } static bool stacksafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur, struct idpair *idmap) { int i, spi; /* if explored stack has more populated slots than current stack * such stacks are not equivalent */ if (old->allocated_stack > cur->allocated_stack) return false; /* walk slots of the explored stack and ignore any additional * slots in the current stack, since explored(safe) state * didn't use them */ for (i = 0; i < old->allocated_stack; i++) { spi = i / BPF_REG_SIZE; if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) continue; if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != cur->stack[spi].slot_type[i % BPF_REG_SIZE]) /* Ex: old explored (safe) state has STACK_SPILL in * this stack slot, but current has has STACK_MISC -> * this verifier states are not equivalent, * return false to continue verification of this path */ return false; if (i % BPF_REG_SIZE) continue; if (old->stack[spi].slot_type[0] != STACK_SPILL) continue; if (!regsafe(&old->stack[spi].spilled_ptr, &cur->stack[spi].spilled_ptr, idmap)) /* when explored and current stack slot are both storing * spilled registers, check that stored pointers types * are the same as well. * Ex: explored safe path could have stored * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} * but current path has stored: * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} * such verifier states are not equivalent. * return false to continue verification of this path */ return false; } return true; } /* compare two verifier states * * all states stored in state_list are known to be valid, since * verifier reached 'bpf_exit' instruction through them * * this function is called when verifier exploring different branches of * execution popped from the state stack. If it sees an old state that has * more strict register state and more strict stack state then this execution * branch doesn't need to be explored further, since verifier already * concluded that more strict state leads to valid finish. * * Therefore two states are equivalent if register state is more conservative * and explored stack state is more conservative than the current one. * Example: * explored current * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) * * In other words if current stack state (one being explored) has more * valid slots than old one that already passed validation, it means * the verifier can stop exploring and conclude that current state is valid too * * Similarly with registers. If explored state has register type as invalid * whereas register type in current state is meaningful, it means that * the current state will reach 'bpf_exit' instruction safely */ static bool states_equal(struct bpf_verifier_env *env, struct bpf_verifier_state *old, struct bpf_verifier_state *cur) { struct idpair *idmap; bool ret = false; int i; idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL); /* If we failed to allocate the idmap, just say it's not safe */ if (!idmap) return false; for (i = 0; i < MAX_BPF_REG; i++) { if (!regsafe(&old->regs[i], &cur->regs[i], idmap)) goto out_free; } if (!stacksafe(old, cur, idmap)) goto out_free; ret = true; out_free: kfree(idmap); return ret; } /* A write screens off any subsequent reads; but write marks come from the * straight-line code between a state and its parent. When we arrive at a * jump target (in the first iteration of the propagate_liveness() loop), * we didn't arrive by the straight-line code, so read marks in state must * propagate to parent regardless of state's write marks. */ static bool do_propagate_liveness(const struct bpf_verifier_state *state, struct bpf_verifier_state *parent) { bool writes = parent == state->parent; /* Observe write marks */ bool touched = false; /* any changes made? */ int i; if (!parent) return touched; /* Propagate read liveness of registers... */ BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); /* We don't need to worry about FP liveness because it's read-only */ for (i = 0; i < BPF_REG_FP; i++) { if (parent->regs[i].live & REG_LIVE_READ) continue; if (writes && (state->regs[i].live & REG_LIVE_WRITTEN)) continue; if (state->regs[i].live & REG_LIVE_READ) { parent->regs[i].live |= REG_LIVE_READ; touched = true; } } /* ... and stack slots */ for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && i < parent->allocated_stack / BPF_REG_SIZE; i++) { if (parent->stack[i].slot_type[0] != STACK_SPILL) continue; if (state->stack[i].slot_type[0] != STACK_SPILL) continue; if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ) continue; if (writes && (state->stack[i].spilled_ptr.live & REG_LIVE_WRITTEN)) continue; if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) { parent->stack[i].spilled_ptr.live |= REG_LIVE_READ; touched = true; } } return touched; } /* "parent" is "a state from which we reach the current state", but initially * it is not the state->parent (i.e. "the state whose straight-line code leads * to the current state"), instead it is the state that happened to arrive at * a (prunable) equivalent of the current state. See comment above * do_propagate_liveness() for consequences of this. * This function is just a more efficient way of calling mark_reg_read() or * mark_stack_slot_read() on each reg in "parent" that is read in "state", * though it requires that parent != state->parent in the call arguments. */ static void propagate_liveness(const struct bpf_verifier_state *state, struct bpf_verifier_state *parent) { while (do_propagate_liveness(state, parent)) { /* Something changed, so we need to feed those changes onward */ state = parent; parent = state->parent; } } static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) { struct bpf_verifier_state_list *new_sl; struct bpf_verifier_state_list *sl; struct bpf_verifier_state *cur = env->cur_state; int i, err; sl = env->explored_states[insn_idx]; if (!sl) /* this 'insn_idx' instruction wasn't marked, so we will not * be doing state search here */ return 0; while (sl != STATE_LIST_MARK) { if (states_equal(env, &sl->state, cur)) { /* reached equivalent register/stack state, * prune the search. * Registers read by the continuation are read by us. * If we have any write marks in env->cur_state, they * will prevent corresponding reads in the continuation * from reaching our parent (an explored_state). Our * own state will get the read marks recorded, but * they'll be immediately forgotten as we're pruning * this state and will pop a new one. */ propagate_liveness(&sl->state, cur); return 1; } sl = sl->next; } /* there were no equivalent states, remember current one. * technically the current state is not proven to be safe yet, * but it will either reach bpf_exit (which means it's safe) or * it will be rejected. Since there are no loops, we won't be * seeing this 'insn_idx' instruction again on the way to bpf_exit */ new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); if (!new_sl) return -ENOMEM; /* add new state to the head of linked list */ err = copy_verifier_state(&new_sl->state, cur); if (err) { free_verifier_state(&new_sl->state, false); kfree(new_sl); return err; } new_sl->next = env->explored_states[insn_idx]; env->explored_states[insn_idx] = new_sl; /* connect new state to parentage chain */ cur->parent = &new_sl->state; /* clear write marks in current state: the writes we did are not writes * our child did, so they don't screen off its reads from us. * (There are no read marks in current state, because reads always mark * their parent and current state never has children yet. Only * explored_states can get read marks.) */ for (i = 0; i < BPF_REG_FP; i++) cur->regs[i].live = REG_LIVE_NONE; for (i = 0; i < cur->allocated_stack / BPF_REG_SIZE; i++) if (cur->stack[i].slot_type[0] == STACK_SPILL) cur->stack[i].spilled_ptr.live = REG_LIVE_NONE; return 0; } static int ext_analyzer_insn_hook(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { if (env->dev_ops && env->dev_ops->insn_hook) return env->dev_ops->insn_hook(env, insn_idx, prev_insn_idx); return 0; } static int do_check(struct bpf_verifier_env *env) { struct bpf_verifier_state *state; struct bpf_insn *insns = env->prog->insnsi; struct bpf_reg_state *regs; int insn_cnt = env->prog->len; int insn_idx, prev_insn_idx = 0; int insn_processed = 0; bool do_print_state = false; state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); if (!state) return -ENOMEM; env->cur_state = state; init_reg_state(env, state->regs); state->parent = NULL; insn_idx = 0; for (;;) { struct bpf_insn *insn; u8 class; int err; if (insn_idx >= insn_cnt) { verbose(env, "invalid insn idx %d insn_cnt %d\n", insn_idx, insn_cnt); return -EFAULT; } insn = &insns[insn_idx]; class = BPF_CLASS(insn->code); if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { verbose(env, "BPF program is too large. Processed %d insn\n", insn_processed); return -E2BIG; } err = is_state_visited(env, insn_idx); if (err < 0) return err; if (err == 1) { /* found equivalent state, can prune the search */ if (env->log.level) { if (do_print_state) verbose(env, "\nfrom %d to %d: safe\n", prev_insn_idx, insn_idx); else verbose(env, "%d: safe\n", insn_idx); } goto process_bpf_exit; } if (need_resched()) cond_resched(); if (env->log.level > 1 || (env->log.level && do_print_state)) { if (env->log.level > 1) verbose(env, "%d:", insn_idx); else verbose(env, "\nfrom %d to %d:", prev_insn_idx, insn_idx); print_verifier_state(env, state); do_print_state = false; } if (env->log.level) { verbose(env, "%d: ", insn_idx); print_bpf_insn(verbose, env, insn, env->allow_ptr_leaks); } err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx); if (err) return err; regs = cur_regs(env); env->insn_aux_data[insn_idx].seen = true; if (class == BPF_ALU || class == BPF_ALU64) { err = check_alu_op(env, insn); if (err) return err; } else if (class == BPF_LDX) { enum bpf_reg_type *prev_src_type, src_reg_type; /* check for reserved fields is already done */ /* check src operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; src_reg_type = regs[insn->src_reg].type; /* check that memory (src_reg + off) is readable, * the state of dst_reg will be updated by this func */ err = check_mem_access(env, insn_idx, insn->src_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, insn->dst_reg); if (err) return err; prev_src_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_src_type == NOT_INIT) { /* saw a valid insn * dst_reg = *(u32 *)(src_reg + off) * save type to validate intersecting paths */ *prev_src_type = src_reg_type; } else if (src_reg_type != *prev_src_type && (src_reg_type == PTR_TO_CTX || *prev_src_type == PTR_TO_CTX)) { /* ABuser program is trying to use the same insn * dst_reg = *(u32*) (src_reg + off) * with different pointer types: * src_reg == ctx in one branch and * src_reg == stack|map in some other branch. * Reject it. */ verbose(env, "same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_STX) { enum bpf_reg_type *prev_dst_type, dst_reg_type; if (BPF_MODE(insn->code) == BPF_XADD) { err = check_xadd(env, insn_idx, insn); if (err) return err; insn_idx++; continue; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg_type = regs[insn->dst_reg].type; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg); if (err) return err; prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_dst_type == NOT_INIT) { *prev_dst_type = dst_reg_type; } else if (dst_reg_type != *prev_dst_type && (dst_reg_type == PTR_TO_CTX || *prev_dst_type == PTR_TO_CTX)) { verbose(env, "same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_ST) { if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { verbose(env, "BPF_ST uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); if (err) return err; } else if (class == BPF_JMP) { u8 opcode = BPF_OP(insn->code); if (opcode == BPF_CALL) { if (BPF_SRC(insn->code) != BPF_K || insn->off != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_CALL uses reserved fields\n"); return -EINVAL; } err = check_call(env, insn->imm, insn_idx); if (err) return err; } else if (opcode == BPF_JA) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_JA uses reserved fields\n"); return -EINVAL; } insn_idx += insn->off + 1; continue; } else if (opcode == BPF_EXIT) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_EXIT uses reserved fields\n"); return -EINVAL; } /* eBPF calling convetion is such that R0 is used * to return the value from eBPF program. * Make sure that it's readable at this time * of bpf_exit, which means that program wrote * something into it earlier */ err = check_reg_arg(env, BPF_REG_0, SRC_OP); if (err) return err; if (is_pointer_value(env, BPF_REG_0)) { verbose(env, "R0 leaks addr as return value\n"); return -EACCES; } err = check_return_code(env); if (err) return err; process_bpf_exit: err = pop_stack(env, &prev_insn_idx, &insn_idx); if (err < 0) { if (err != -ENOENT) return err; break; } else { do_print_state = true; continue; } } else { err = check_cond_jmp_op(env, insn, &insn_idx); if (err) return err; } } else if (class == BPF_LD) { u8 mode = BPF_MODE(insn->code); if (mode == BPF_ABS || mode == BPF_IND) { err = check_ld_abs(env, insn); if (err) return err; } else if (mode == BPF_IMM) { err = check_ld_imm(env, insn); if (err) return err; insn_idx++; env->insn_aux_data[insn_idx].seen = true; } else { verbose(env, "invalid BPF_LD mode\n"); return -EINVAL; } } else { verbose(env, "unknown insn class %d\n", class); return -EINVAL; } insn_idx++; } verbose(env, "processed %d insns, stack depth %d\n", insn_processed, env->prog->aux->stack_depth); return 0; } static int check_map_prealloc(struct bpf_map *map) { return (map->map_type != BPF_MAP_TYPE_HASH && map->map_type != BPF_MAP_TYPE_PERCPU_HASH && map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || !(map->map_flags & BPF_F_NO_PREALLOC); } static int check_map_prog_compatibility(struct bpf_verifier_env *env, struct bpf_map *map, struct bpf_prog *prog) { /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use * preallocated hash maps, since doing memory allocation * in overflow_handler can crash depending on where nmi got * triggered. */ if (prog->type == BPF_PROG_TYPE_PERF_EVENT) { if (!check_map_prealloc(map)) { verbose(env, "perf_event programs can only use preallocated hash map\n"); return -EINVAL; } if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta)) { verbose(env, "perf_event programs can only use preallocated inner hash map\n"); return -EINVAL; } } return 0; } /* look for pseudo eBPF instructions that access map FDs and * replace them with actual map pointers */ static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i, j, err; err = bpf_prog_calc_tag(env->prog); if (err) return err; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) == BPF_LDX && (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { verbose(env, "BPF_LDX uses reserved fields\n"); return -EINVAL; } if (BPF_CLASS(insn->code) == BPF_STX && ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { verbose(env, "BPF_STX uses reserved fields\n"); return -EINVAL; } if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { struct bpf_map *map; struct fd f; if (i == insn_cnt - 1 || insn[1].code != 0 || insn[1].dst_reg != 0 || insn[1].src_reg != 0 || insn[1].off != 0) { verbose(env, "invalid bpf_ld_imm64 insn\n"); return -EINVAL; } if (insn->src_reg == 0) /* valid generic load 64-bit imm */ goto next_insn; if (insn->src_reg != BPF_PSEUDO_MAP_FD) { verbose(env, "unrecognized bpf_ld_imm64 insn\n"); return -EINVAL; } f = fdget(insn->imm); map = __bpf_map_get(f); if (IS_ERR(map)) { verbose(env, "fd %d is not pointing to valid bpf_map\n", insn->imm); return PTR_ERR(map); } err = check_map_prog_compatibility(env, map, env->prog); if (err) { fdput(f); return err; } /* store map pointer inside BPF_LD_IMM64 instruction */ insn[0].imm = (u32) (unsigned long) map; insn[1].imm = ((u64) (unsigned long) map) >> 32; /* check whether we recorded this map already */ for (j = 0; j < env->used_map_cnt; j++) if (env->used_maps[j] == map) { fdput(f); goto next_insn; } if (env->used_map_cnt >= MAX_USED_MAPS) { fdput(f); return -E2BIG; } /* hold the map. If the program is rejected by verifier, * the map will be released by release_maps() or it * will be used by the valid program until it's unloaded * and all maps are released in free_bpf_prog_info() */ map = bpf_map_inc(map, false); if (IS_ERR(map)) { fdput(f); return PTR_ERR(map); } env->used_maps[env->used_map_cnt++] = map; fdput(f); next_insn: insn++; i++; } } /* now all pseudo BPF_LD_IMM64 instructions load valid * 'struct bpf_map *' into a register instead of user map_fd. * These pointers will be used later by verifier to validate map access. */ return 0; } /* drop refcnt of maps used by the rejected program */ static void release_maps(struct bpf_verifier_env *env) { int i; for (i = 0; i < env->used_map_cnt; i++) bpf_map_put(env->used_maps[i]); } /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i; for (i = 0; i < insn_cnt; i++, insn++) if (insn->code == (BPF_LD | BPF_IMM | BPF_DW)) insn->src_reg = 0; } /* single env->prog->insni[off] instruction was replaced with the range * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying * [0, off) and [off, end) to new locations, so the patched range stays zero */ static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; int i; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); for (i = off; i < off + cnt - 1; i++) new_data[i].seen = true; env->insn_aux_data = new_data; vfree(old_data); return 0; } static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, const struct bpf_insn *patch, u32 len) { struct bpf_prog *new_prog; new_prog = bpf_patch_insn_single(env->prog, off, patch, len); if (!new_prog) return NULL; if (adjust_insn_aux_data(env, new_prog->len, off, len)) return NULL; return new_prog; } /* The verifier does more data flow analysis than llvm and will not explore * branches that are dead at run time. Malicious programs can have dead code * too. Therefore replace all dead at-run-time code with nops. */ static void sanitize_dead_code(struct bpf_verifier_env *env) { struct bpf_insn_aux_data *aux_data = env->insn_aux_data; struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0); struct bpf_insn *insn = env->prog->insnsi; const int insn_cnt = env->prog->len; int i; for (i = 0; i < insn_cnt; i++) { if (aux_data[i].seen) continue; memcpy(insn + i, &nop, sizeof(nop)); } } /* convert load instructions that access fields of 'struct __sk_buff' * into sequence of instructions that access fields of 'struct sk_buff' */ static int convert_ctx_accesses(struct bpf_verifier_env *env) { const struct bpf_verifier_ops *ops = env->ops; int i, cnt, size, ctx_field_size, delta = 0; const int insn_cnt = env->prog->len; struct bpf_insn insn_buf[16], *insn; struct bpf_prog *new_prog; enum bpf_access_type type; bool is_narrower_load; u32 target_size; if (ops->gen_prologue) { cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, env->prog); if (cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } else if (cnt) { new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); if (!new_prog) return -ENOMEM; env->prog = new_prog; delta += cnt - 1; } } if (!ops->convert_ctx_access) return 0; insn = env->prog->insnsi + delta; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || insn->code == (BPF_LDX | BPF_MEM | BPF_H) || insn->code == (BPF_LDX | BPF_MEM | BPF_W) || insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) type = BPF_READ; else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || insn->code == (BPF_STX | BPF_MEM | BPF_H) || insn->code == (BPF_STX | BPF_MEM | BPF_W) || insn->code == (BPF_STX | BPF_MEM | BPF_DW)) type = BPF_WRITE; else continue; if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX) continue; ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; size = BPF_LDST_BYTES(insn); /* If the read access is a narrower load of the field, * convert to a 4/8-byte load, to minimum program type specific * convert_ctx_access changes. If conversion is successful, * we will apply proper mask to the result. */ is_narrower_load = size < ctx_field_size; if (is_narrower_load) { u32 off = insn->off; u8 size_code; if (type == BPF_WRITE) { verbose(env, "bpf verifier narrow ctx access misconfigured\n"); return -EINVAL; } size_code = BPF_H; if (ctx_field_size == 4) size_code = BPF_W; else if (ctx_field_size == 8) size_code = BPF_DW; insn->off = off & ~(ctx_field_size - 1); insn->code = BPF_LDX | BPF_MEM | size_code; } target_size = 0; cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog, &target_size); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || (ctx_field_size && !target_size)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } if (is_narrower_load && size < target_size) { if (ctx_field_size <= 4) insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, (1 << size * 8) - 1); else insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, (1 << size * 8) - 1); } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; /* keep walking new program and skip insns we just inserted */ env->prog = new_prog; insn = new_prog->insnsi + i + delta; } return 0; } /* fixup insn->imm field of bpf_call instructions * and inline eligible helpers as explicit sequence of BPF instructions * * this function is called after eBPF program passed verification */ static int fixup_bpf_calls(struct bpf_verifier_env *env) { struct bpf_prog *prog = env->prog; struct bpf_insn *insn = prog->insnsi; const struct bpf_func_proto *fn; const int insn_cnt = prog->len; struct bpf_insn insn_buf[16]; struct bpf_prog *new_prog; struct bpf_map *map_ptr; int i, cnt, delta = 0; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code != (BPF_JMP | BPF_CALL)) continue; if (insn->imm == BPF_FUNC_get_route_realm) prog->dst_needed = 1; if (insn->imm == BPF_FUNC_get_prandom_u32) bpf_user_rnd_init_once(); if (insn->imm == BPF_FUNC_tail_call) { /* If we tail call into other programs, we * cannot make any assumptions since they can * be replaced dynamically during runtime in * the program array. */ prog->cb_access = 1; env->prog->aux->stack_depth = MAX_BPF_STACK; /* mark bpf_tail_call as different opcode to avoid * conditional branch in the interpeter for every normal * call and to prevent accidental JITing by JIT compiler * that doesn't support bpf_tail_call yet */ insn->imm = 0; insn->code = BPF_JMP | BPF_TAIL_CALL; continue; } /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup * handlers are currently limited to 64 bit only. */ if (ebpf_jit_enabled() && BITS_PER_LONG == 64 && insn->imm == BPF_FUNC_map_lookup_elem) { map_ptr = env->insn_aux_data[i + delta].map_ptr; if (map_ptr == BPF_MAP_PTR_POISON || !map_ptr->ops->map_gen_lookup) goto patch_call_imm; cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; /* keep walking new program and skip insns we just inserted */ env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (insn->imm == BPF_FUNC_redirect_map) { /* Note, we cannot use prog directly as imm as subsequent * rewrites would still change the prog pointer. The only * stable address we can use is aux, which also works with * prog clones during blinding. */ u64 addr = (unsigned long)prog->aux; struct bpf_insn r4_ld[] = { BPF_LD_IMM64(BPF_REG_4, addr), *insn, }; cnt = ARRAY_SIZE(r4_ld); new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; } patch_call_imm: fn = env->ops->get_func_proto(insn->imm); /* all functions that have prototype and verifier allowed * programs to call them, must be real in-kernel functions */ if (!fn->func) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(insn->imm), insn->imm); return -EFAULT; } insn->imm = fn->func - __bpf_call_base; } return 0; } static void free_states(struct bpf_verifier_env *env) { struct bpf_verifier_state_list *sl, *sln; int i; if (!env->explored_states) return; for (i = 0; i < env->prog->len; i++) { sl = env->explored_states[i]; if (sl) while (sl != STATE_LIST_MARK) { sln = sl->next; free_verifier_state(&sl->state, false); kfree(sl); sl = sln; } } kfree(env->explored_states); } int bpf_check(struct bpf_prog **prog, union bpf_attr *attr) { struct bpf_verifier_env *env; struct bpf_verifer_log *log; int ret = -EINVAL; /* no program is valid */ if (ARRAY_SIZE(bpf_verifier_ops) == 0) return -EINVAL; /* 'struct bpf_verifier_env' can be global, but since it's not small, * allocate/free it every time bpf_check() is called */ env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); if (!env) return -ENOMEM; log = &env->log; env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) * (*prog)->len); ret = -ENOMEM; if (!env->insn_aux_data) goto err_free_env; env->prog = *prog; env->ops = bpf_verifier_ops[env->prog->type]; /* grab the mutex to protect few globals used by verifier */ mutex_lock(&bpf_verifier_lock); if (attr->log_level || attr->log_buf || attr->log_size) { /* user requested verbose verifier output * and supplied buffer to store the verification trace */ log->level = attr->log_level; log->ubuf = (char __user *) (unsigned long) attr->log_buf; log->len_total = attr->log_size; ret = -EINVAL; /* log attributes have to be sane */ if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 || !log->level || !log->ubuf) goto err_unlock; } env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) env->strict_alignment = true; if (env->prog->aux->offload) { ret = bpf_prog_offload_verifier_prep(env); if (ret) goto err_unlock; } ret = replace_map_fd_with_map_ptr(env); if (ret < 0) goto skip_full_check; env->explored_states = kcalloc(env->prog->len, sizeof(struct bpf_verifier_state_list *), GFP_USER); ret = -ENOMEM; if (!env->explored_states) goto skip_full_check; ret = check_cfg(env); if (ret < 0) goto skip_full_check; env->allow_ptr_leaks = capable(CAP_SYS_ADMIN); ret = do_check(env); if (env->cur_state) { free_verifier_state(env->cur_state, true); env->cur_state = NULL; } skip_full_check: while (!pop_stack(env, NULL, NULL)); free_states(env); if (ret == 0) sanitize_dead_code(env); if (ret == 0) /* program is valid, convert *(u32*)(ctx + off) accesses */ ret = convert_ctx_accesses(env); if (ret == 0) ret = fixup_bpf_calls(env); if (log->level && bpf_verifier_log_full(log)) ret = -ENOSPC; if (log->level && !log->ubuf) { ret = -EFAULT; goto err_release_maps; } if (ret == 0 && env->used_map_cnt) { /* if program passed verifier, update used_maps in bpf_prog_info */ env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, sizeof(env->used_maps[0]), GFP_KERNEL); if (!env->prog->aux->used_maps) { ret = -ENOMEM; goto err_release_maps; } memcpy(env->prog->aux->used_maps, env->used_maps, sizeof(env->used_maps[0]) * env->used_map_cnt); env->prog->aux->used_map_cnt = env->used_map_cnt; /* program is valid. Convert pseudo bpf_ld_imm64 into generic * bpf_ld_imm64 instructions */ convert_pseudo_ld_imm64(env); } err_release_maps: if (!env->prog->aux->used_maps) /* if we didn't copy map pointers into bpf_prog_info, release * them now. Otherwise free_bpf_prog_info() will release them. */ release_maps(env); *prog = env->prog; err_unlock: mutex_unlock(&bpf_verifier_lock); vfree(env->insn_aux_data); err_free_env: kfree(env); return ret; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2984_0
crossvul-cpp_data_good_2131_4
/* * HID driver for some petalynx "special" devices * * Copyright (c) 1999 Andreas Gal * Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz> * Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc * Copyright (c) 2006-2007 Jiri Kosina * Copyright (c) 2008 Jiri Slaby */ /* * 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. */ #include <linux/device.h> #include <linux/hid.h> #include <linux/module.h> #include "hid-ids.h" /* Petalynx Maxter Remote has maximum for consumer page set too low */ static __u8 *pl_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 62 && rdesc[39] == 0x2a && rdesc[40] == 0xf5 && rdesc[41] == 0x00 && rdesc[59] == 0x26 && rdesc[60] == 0xf9 && rdesc[61] == 0x00) { hid_info(hdev, "fixing up Petalynx Maxter Remote report descriptor\n"); rdesc[60] = 0xfa; rdesc[40] = 0xfa; } return rdesc; } #define pl_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \ EV_KEY, (c)) static int pl_input_mapping(struct hid_device *hdev, struct hid_input *hi, struct hid_field *field, struct hid_usage *usage, unsigned long **bit, int *max) { if ((usage->hid & HID_USAGE_PAGE) == HID_UP_LOGIVENDOR) { switch (usage->hid & HID_USAGE) { case 0x05a: pl_map_key_clear(KEY_TEXT); break; case 0x05b: pl_map_key_clear(KEY_RED); break; case 0x05c: pl_map_key_clear(KEY_GREEN); break; case 0x05d: pl_map_key_clear(KEY_YELLOW); break; case 0x05e: pl_map_key_clear(KEY_BLUE); break; default: return 0; } return 1; } if ((usage->hid & HID_USAGE_PAGE) == HID_UP_CONSUMER) { switch (usage->hid & HID_USAGE) { case 0x0f6: pl_map_key_clear(KEY_NEXT); break; case 0x0fa: pl_map_key_clear(KEY_BACK); break; default: return 0; } return 1; } return 0; } static int pl_probe(struct hid_device *hdev, const struct hid_device_id *id) { int ret; hdev->quirks |= HID_QUIRK_NOGET; ret = hid_parse(hdev); if (ret) { hid_err(hdev, "parse failed\n"); goto err_free; } ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT); if (ret) { hid_err(hdev, "hw start failed\n"); goto err_free; } return 0; err_free: return ret; } static const struct hid_device_id pl_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_PETALYNX, USB_DEVICE_ID_PETALYNX_MAXTER_REMOTE) }, { } }; MODULE_DEVICE_TABLE(hid, pl_devices); static struct hid_driver pl_driver = { .name = "petalynx", .id_table = pl_devices, .report_fixup = pl_report_fixup, .input_mapping = pl_input_mapping, .probe = pl_probe, }; module_hid_driver(pl_driver); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-119/c/good_2131_4
crossvul-cpp_data_good_1614_0
/* ----------------------------------------------------------------------------- * Copyright (c) 2011 Ozmo Inc * Released under the GNU General Public License Version 2 (GPLv2). * * This file implements the protocol specific parts of the USB service for a PD. * ----------------------------------------------------------------------------- */ #include <linux/module.h> #include <linux/timer.h> #include <linux/sched.h> #include <linux/netdevice.h> #include <linux/errno.h> #include <linux/input.h> #include <asm/unaligned.h> #include "ozdbg.h" #include "ozprotocol.h" #include "ozeltbuf.h" #include "ozpd.h" #include "ozproto.h" #include "ozusbif.h" #include "ozhcd.h" #include "ozusbsvc.h" #define MAX_ISOC_FIXED_DATA (253-sizeof(struct oz_isoc_fixed)) /* * Context: softirq */ static int oz_usb_submit_elt(struct oz_elt_buf *eb, struct oz_elt_info *ei, struct oz_usb_ctx *usb_ctx, u8 strid, u8 isoc) { int ret; struct oz_elt *elt = (struct oz_elt *)ei->data; struct oz_app_hdr *app_hdr = (struct oz_app_hdr *)(elt+1); elt->type = OZ_ELT_APP_DATA; ei->app_id = OZ_APPID_USB; ei->length = elt->length + sizeof(struct oz_elt); app_hdr->app_id = OZ_APPID_USB; spin_lock_bh(&eb->lock); if (isoc == 0) { app_hdr->elt_seq_num = usb_ctx->tx_seq_num++; if (usb_ctx->tx_seq_num == 0) usb_ctx->tx_seq_num = 1; } ret = oz_queue_elt_info(eb, isoc, strid, ei); if (ret) oz_elt_info_free(eb, ei); spin_unlock_bh(&eb->lock); return ret; } /* * Context: softirq */ int oz_usb_get_desc_req(void *hpd, u8 req_id, u8 req_type, u8 desc_type, u8 index, __le16 windex, int offset, int len) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_get_desc_req *body; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); oz_dbg(ON, " req_type = 0x%x\n", req_type); oz_dbg(ON, " desc_type = 0x%x\n", desc_type); oz_dbg(ON, " index = 0x%x\n", index); oz_dbg(ON, " windex = 0x%x\n", windex); oz_dbg(ON, " offset = 0x%x\n", offset); oz_dbg(ON, " len = 0x%x\n", len); if (len > 200) len = 200; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_get_desc_req); body = (struct oz_get_desc_req *)(elt+1); body->type = OZ_GET_DESC_REQ; body->req_id = req_id; put_unaligned(cpu_to_le16(offset), &body->offset); put_unaligned(cpu_to_le16(len), &body->size); body->req_type = req_type; body->desc_type = desc_type; body->w_index = windex; body->index = index; return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_set_config_req(void *hpd, u8 req_id, u8 index) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_set_config_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_set_config_req); body = (struct oz_set_config_req *)(elt+1); body->type = OZ_SET_CONFIG_REQ; body->req_id = req_id; body->index = index; return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_set_interface_req(void *hpd, u8 req_id, u8 index, u8 alt) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_set_interface_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_set_interface_req); body = (struct oz_set_interface_req *)(elt+1); body->type = OZ_SET_INTERFACE_REQ; body->req_id = req_id; body->index = index; body->alternative = alt; return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_set_clear_feature_req(void *hpd, u8 req_id, u8 type, u8 recipient, u8 index, __le16 feature) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_feature_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_feature_req); body = (struct oz_feature_req *)(elt+1); body->type = type; body->req_id = req_id; body->recipient = recipient; body->index = index; put_unaligned(feature, &body->feature); return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_vendor_class_req(void *hpd, u8 req_id, u8 req_type, u8 request, __le16 value, __le16 index, const u8 *data, int data_len) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_vendor_class_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_vendor_class_req) - 1 + data_len; body = (struct oz_vendor_class_req *)(elt+1); body->type = OZ_VENDOR_CLASS_REQ; body->req_id = req_id; body->req_type = req_type; body->request = request; put_unaligned(value, &body->value); put_unaligned(index, &body->index); if (data_len) memcpy(body->data, data, data_len); return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ int oz_usb_control_req(void *hpd, u8 req_id, struct usb_ctrlrequest *setup, const u8 *data, int data_len) { unsigned wvalue = le16_to_cpu(setup->wValue); unsigned windex = le16_to_cpu(setup->wIndex); unsigned wlength = le16_to_cpu(setup->wLength); int rc = 0; if ((setup->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) { switch (setup->bRequest) { case USB_REQ_GET_DESCRIPTOR: rc = oz_usb_get_desc_req(hpd, req_id, setup->bRequestType, (u8)(wvalue>>8), (u8)wvalue, setup->wIndex, 0, wlength); break; case USB_REQ_SET_CONFIGURATION: rc = oz_usb_set_config_req(hpd, req_id, (u8)wvalue); break; case USB_REQ_SET_INTERFACE: { u8 if_num = (u8)windex; u8 alt = (u8)wvalue; rc = oz_usb_set_interface_req(hpd, req_id, if_num, alt); } break; case USB_REQ_SET_FEATURE: rc = oz_usb_set_clear_feature_req(hpd, req_id, OZ_SET_FEATURE_REQ, setup->bRequestType & 0xf, (u8)windex, setup->wValue); break; case USB_REQ_CLEAR_FEATURE: rc = oz_usb_set_clear_feature_req(hpd, req_id, OZ_CLEAR_FEATURE_REQ, setup->bRequestType & 0xf, (u8)windex, setup->wValue); break; } } else { rc = oz_usb_vendor_class_req(hpd, req_id, setup->bRequestType, setup->bRequest, setup->wValue, setup->wIndex, data, data_len); } return rc; } /* * Context: softirq */ int oz_usb_send_isoc(void *hpd, u8 ep_num, struct urb *urb) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt_buf *eb; int i; int hdr_size; u8 *data; struct usb_iso_packet_descriptor *desc; if (pd->mode & OZ_F_ISOC_NO_ELTS) { for (i = 0; i < urb->number_of_packets; i++) { u8 *data; desc = &urb->iso_frame_desc[i]; data = ((u8 *)urb->transfer_buffer)+desc->offset; oz_send_isoc_unit(pd, ep_num, data, desc->length); } return 0; } hdr_size = sizeof(struct oz_isoc_fixed) - 1; eb = &pd->elt_buff; i = 0; while (i < urb->number_of_packets) { struct oz_elt_info *ei = oz_elt_info_alloc(eb); struct oz_elt *elt; struct oz_isoc_fixed *body; int unit_count; int unit_size; int rem; if (ei == NULL) return -1; rem = MAX_ISOC_FIXED_DATA; elt = (struct oz_elt *)ei->data; body = (struct oz_isoc_fixed *)(elt + 1); body->type = OZ_USB_ENDPOINT_DATA; body->endpoint = ep_num; body->format = OZ_DATA_F_ISOC_FIXED; unit_size = urb->iso_frame_desc[i].length; body->unit_size = (u8)unit_size; data = ((u8 *)(elt+1)) + hdr_size; unit_count = 0; while (i < urb->number_of_packets) { desc = &urb->iso_frame_desc[i]; if ((unit_size == desc->length) && (desc->length <= rem)) { memcpy(data, ((u8 *)urb->transfer_buffer) + desc->offset, unit_size); data += unit_size; rem -= unit_size; unit_count++; desc->status = 0; desc->actual_length = desc->length; i++; } else { break; } } elt->length = hdr_size + MAX_ISOC_FIXED_DATA - rem; /* Store the number of units in body->frame_number for the * moment. This field will be correctly determined before * the element is sent. */ body->frame_number = (u8)unit_count; oz_usb_submit_elt(eb, ei, usb_ctx, ep_num, pd->mode & OZ_F_ISOC_ANYTIME); } return 0; } /* * Context: softirq-serialized */ static void oz_usb_handle_ep_data(struct oz_usb_ctx *usb_ctx, struct oz_usb_hdr *usb_hdr, int len) { struct oz_data *data_hdr = (struct oz_data *)usb_hdr; switch (data_hdr->format) { case OZ_DATA_F_MULTIPLE_FIXED: { struct oz_multiple_fixed *body = (struct oz_multiple_fixed *)data_hdr; u8 *data = body->data; unsigned int n; if (!body->unit_size || len < sizeof(struct oz_multiple_fixed) - 1) break; n = (len - (sizeof(struct oz_multiple_fixed) - 1)) / body->unit_size; while (n--) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, body->unit_size); data += body->unit_size; } } break; case OZ_DATA_F_ISOC_FIXED: { struct oz_isoc_fixed *body = (struct oz_isoc_fixed *)data_hdr; int data_len = len-sizeof(struct oz_isoc_fixed)+1; int unit_size = body->unit_size; u8 *data = body->data; int count; int i; if (!unit_size) break; count = data_len/unit_size; for (i = 0; i < count; i++) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, unit_size); data += unit_size; } } break; } } /* * This is called when the PD has received a USB element. The type of element * is determined and is then passed to an appropriate handler function. * Context: softirq-serialized */ void oz_usb_rx(struct oz_pd *pd, struct oz_elt *elt) { struct oz_usb_hdr *usb_hdr = (struct oz_usb_hdr *)(elt + 1); struct oz_usb_ctx *usb_ctx; spin_lock_bh(&pd->app_lock[OZ_APPID_USB]); usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB]; if (usb_ctx) oz_usb_get(usb_ctx); spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]); if (usb_ctx == NULL) return; /* Context has gone so nothing to do. */ if (usb_ctx->stopped) goto done; /* If sequence number is non-zero then check it is not a duplicate. * Zero sequence numbers are always accepted. */ if (usb_hdr->elt_seq_num != 0) { if (((usb_ctx->rx_seq_num - usb_hdr->elt_seq_num) & 0x80) == 0) /* Reject duplicate element. */ goto done; } usb_ctx->rx_seq_num = usb_hdr->elt_seq_num; switch (usb_hdr->type) { case OZ_GET_DESC_RSP: { struct oz_get_desc_rsp *body = (struct oz_get_desc_rsp *)usb_hdr; u16 offs, total_size; u8 data_len; if (elt->length < sizeof(struct oz_get_desc_rsp) - 1) break; data_len = elt->length - (sizeof(struct oz_get_desc_rsp) - 1); offs = le16_to_cpu(get_unaligned(&body->offset)); total_size = le16_to_cpu(get_unaligned(&body->total_size)); oz_dbg(ON, "USB_REQ_GET_DESCRIPTOR - cnf\n"); oz_hcd_get_desc_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, data_len, offs, total_size); } break; case OZ_SET_CONFIG_RSP: { struct oz_set_config_rsp *body = (struct oz_set_config_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_SET_INTERFACE_RSP: { struct oz_set_interface_rsp *body = (struct oz_set_interface_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_VENDOR_CLASS_RSP: { struct oz_vendor_class_rsp *body = (struct oz_vendor_class_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, elt->length- sizeof(struct oz_vendor_class_rsp)+1); } break; case OZ_USB_ENDPOINT_DATA: oz_usb_handle_ep_data(usb_ctx, usb_hdr, elt->length); break; } done: oz_usb_put(usb_ctx); } /* * Context: softirq, process */ void oz_usb_farewell(struct oz_pd *pd, u8 ep_num, u8 *data, u8 len) { struct oz_usb_ctx *usb_ctx; spin_lock_bh(&pd->app_lock[OZ_APPID_USB]); usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB]; if (usb_ctx) oz_usb_get(usb_ctx); spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]); if (usb_ctx == NULL) return; /* Context has gone so nothing to do. */ if (!usb_ctx->stopped) { oz_dbg(ON, "Farewell indicated ep = 0x%x\n", ep_num); oz_hcd_data_ind(usb_ctx->hport, ep_num, data, len); } oz_usb_put(usb_ctx); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1614_0
crossvul-cpp_data_bad_4824_0
/* +----------------------------------------------------------------------+ | phar php single-file executable PHP extension | +----------------------------------------------------------------------+ | Copyright (c) 2005-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Gregory Beaver <cellog@php.net> | | Marcus Boerger <helly@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define PHAR_MAIN 1 #include "phar_internal.h" #include "SAPI.h" #include "func_interceptors.h" static void destroy_phar_data(void *pDest); ZEND_DECLARE_MODULE_GLOBALS(phar) char *(*phar_save_resolve_path)(const char *filename, int filename_len TSRMLS_DC); /** * set's phar->is_writeable based on the current INI value */ static int phar_set_writeable_bit(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { zend_bool keep = *(zend_bool *)argument; phar_archive_data *phar = *(phar_archive_data **)pDest; if (!phar->is_data) { phar->is_writeable = !keep; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* if the original value is 0 (disabled), then allow setting/unsetting at will. Otherwise only allow 1 (enabled), and error on disabling */ ZEND_INI_MH(phar_ini_modify_handler) /* {{{ */ { zend_bool old, ini; if (entry->name_length == 14) { old = PHAR_G(readonly_orig); } else { old = PHAR_G(require_hash_orig); } if (new_value_length == 2 && !strcasecmp("on", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 3 && !strcasecmp("yes", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 4 && !strcasecmp("true", new_value)) { ini = (zend_bool) 1; } else { ini = (zend_bool) atoi(new_value); } /* do not allow unsetting in runtime */ if (stage == ZEND_INI_STAGE_STARTUP) { if (entry->name_length == 14) { PHAR_G(readonly_orig) = ini; } else { PHAR_G(require_hash_orig) = ini; } } else if (old && !ini) { return FAILURE; } if (entry->name_length == 14) { PHAR_G(readonly) = ini; if (PHAR_GLOBALS->request_init && PHAR_GLOBALS->phar_fname_map.arBuckets) { zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_fname_map), phar_set_writeable_bit, (void *)&ini TSRMLS_CC); } } else { PHAR_G(require_hash) = ini; } return SUCCESS; } /* }}}*/ /* this global stores the global cached pre-parsed manifests */ HashTable cached_phars; HashTable cached_alias; static void phar_split_cache_list(TSRMLS_D) /* {{{ */ { char *tmp; char *key, *lasts, *end; char ds[2]; phar_archive_data *phar; uint i = 0; if (!PHAR_GLOBALS->cache_list || !(PHAR_GLOBALS->cache_list[0])) { return; } ds[0] = DEFAULT_DIR_SEPARATOR; ds[1] = '\0'; tmp = estrdup(PHAR_GLOBALS->cache_list); /* fake request startup */ PHAR_GLOBALS->request_init = 1; if (zend_hash_init(&EG(regular_list), 0, NULL, NULL, 0) == SUCCESS) { EG(regular_list).nNextFreeElement=1; /* we don't want resource id 0 */ } PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); /* these two are dummies and will be destroyed later */ zend_hash_init(&cached_phars, sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&cached_alias, sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); /* these two are real and will be copied over cached_phars/cached_alias later */ zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); PHAR_GLOBALS->manifest_cached = 1; PHAR_GLOBALS->persist = 1; for (key = php_strtok_r(tmp, ds, &lasts); key; key = php_strtok_r(NULL, ds, &lasts)) { end = strchr(key, DEFAULT_DIR_SEPARATOR); if (end) { if (SUCCESS == phar_open_from_filename(key, end - key, NULL, 0, 0, &phar, NULL TSRMLS_CC)) { finish_up: phar->phar_pos = i++; php_stream_close(phar->fp); phar->fp = NULL; } else { finish_error: PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->manifest_cached = 0; efree(tmp); zend_hash_destroy(&(PHAR_G(phar_fname_map))); PHAR_GLOBALS->phar_fname_map.arBuckets = 0; zend_hash_destroy(&(PHAR_G(phar_alias_map))); PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); /* free cached manifests */ PHAR_GLOBALS->request_init = 0; return; } } else { if (SUCCESS == phar_open_from_filename(key, strlen(key), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { goto finish_up; } else { goto finish_error; } } } PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->request_init = 0; /* destroy dummy values from before */ zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); cached_phars = PHAR_GLOBALS->phar_fname_map; cached_alias = PHAR_GLOBALS->phar_alias_map; PHAR_GLOBALS->phar_fname_map.arBuckets = 0; PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); efree(tmp); } /* }}} */ ZEND_INI_MH(phar_ini_cache_list) /* {{{ */ { PHAR_G(cache_list) = new_value; if (stage == ZEND_INI_STAGE_STARTUP) { phar_split_cache_list(TSRMLS_C); } return SUCCESS; } /* }}} */ PHP_INI_BEGIN() STD_PHP_INI_BOOLEAN("phar.readonly", "1", PHP_INI_ALL, phar_ini_modify_handler, readonly, zend_phar_globals, phar_globals) STD_PHP_INI_BOOLEAN("phar.require_hash", "1", PHP_INI_ALL, phar_ini_modify_handler, require_hash, zend_phar_globals, phar_globals) STD_PHP_INI_ENTRY("phar.cache_list", "", PHP_INI_SYSTEM, phar_ini_cache_list, cache_list, zend_phar_globals, phar_globals) PHP_INI_END() /** * When all uses of a phar have been concluded, this frees the manifest * and the phar slot */ void phar_destroy_phar_data(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->alias && phar->alias != phar->fname) { pefree(phar->alias, phar->is_persistent); phar->alias = NULL; } if (phar->fname) { pefree(phar->fname, phar->is_persistent); phar->fname = NULL; } if (phar->signature) { pefree(phar->signature, phar->is_persistent); phar->signature = NULL; } if (phar->manifest.arBuckets) { zend_hash_destroy(&phar->manifest); phar->manifest.arBuckets = NULL; } if (phar->mounted_dirs.arBuckets) { zend_hash_destroy(&phar->mounted_dirs); phar->mounted_dirs.arBuckets = NULL; } if (phar->virtual_dirs.arBuckets) { zend_hash_destroy(&phar->virtual_dirs); phar->virtual_dirs.arBuckets = NULL; } if (phar->metadata) { if (phar->is_persistent) { if (phar->metadata_len) { /* for zip comments that are strings */ free(phar->metadata); } else { zval_internal_ptr_dtor(&phar->metadata); } } else { zval_ptr_dtor(&phar->metadata); } phar->metadata_len = 0; phar->metadata = 0; } if (phar->fp) { php_stream_close(phar->fp); phar->fp = 0; } if (phar->ufp) { php_stream_close(phar->ufp); phar->ufp = 0; } pefree(phar, phar->is_persistent); } /* }}}*/ /** * Delete refcount and destruct if needed. On destruct return 1 else 0. */ int phar_archive_delref(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->is_persistent) { return 0; } if (--phar->refcount < 0) { if (PHAR_GLOBALS->request_done || zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } else if (!phar->refcount) { /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; if (phar->fp && !(phar->flags & PHAR_FILE_COMPRESSION_MASK)) { /* close open file handle - allows removal or rename of the file on windows, which has greedy locking only close if the archive was not already compressed. If it was compressed, then the fp does not refer to the original file */ php_stream_close(phar->fp); phar->fp = NULL; } if (!zend_hash_num_elements(&phar->manifest)) { /* this is a new phar that has perhaps had an alias/metadata set, but has never been flushed */ if (zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } } return 0; } /* }}}*/ /** * Destroy phar's in shutdown, here we don't care about aliases */ static void destroy_phar_data_only(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (EG(exception) || --phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_unalias_apply(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { return *(void**)pDest == argument ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_tmpclose_apply(void *pDest TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *) pDest; if (entry->fp_type != PHAR_TMP) { return ZEND_HASH_APPLY_KEEP; } if (entry->fp && !entry->fp_refcount) { php_stream_close(entry->fp); entry->fp = NULL; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Filename map destructor */ static void destroy_phar_data(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (PHAR_GLOBALS->request_ends) { /* first, iterate over the manifest and close all PHAR_TMP entry fp handles, this prevents unnecessary unfreed stream resources */ zend_hash_apply(&(phar_data->manifest), phar_tmpclose_apply TSRMLS_CC); destroy_phar_data_only(pDest); return; } zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_alias_map), phar_unalias_apply, phar_data TSRMLS_CC); if (--phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * destructor for the manifest hash, frees each file's entry */ void destroy_phar_manifest_entry(void *pDest) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)pDest; TSRMLS_FETCH(); if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->fp) { php_stream_close(entry->fp); entry->fp = 0; } if (entry->metadata) { if (entry->is_persistent) { if (entry->metadata_len) { /* for zip comments that are strings */ free(entry->metadata); } else { zval_internal_ptr_dtor(&entry->metadata); } } else { zval_ptr_dtor(&entry->metadata); } entry->metadata_len = 0; entry->metadata = 0; } if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); entry->metadata_str.c = 0; } pefree(entry->filename, entry->is_persistent); if (entry->link) { pefree(entry->link, entry->is_persistent); entry->link = 0; } if (entry->tmp) { pefree(entry->tmp, entry->is_persistent); entry->tmp = 0; } } /* }}} */ int phar_entry_delref(phar_entry_data *idata TSRMLS_DC) /* {{{ */ { int ret = 0; if (idata->internal_file && !idata->internal_file->is_persistent) { if (--idata->internal_file->fp_refcount < 0) { idata->internal_file->fp_refcount = 0; } if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } /* if phar_get_or_create_entry_data returns a sub-directory, we have to free it */ if (idata->internal_file->is_temp_dir) { destroy_phar_manifest_entry((void *)idata->internal_file); efree(idata->internal_file); } } phar_archive_delref(idata->phar TSRMLS_CC); efree(idata); return ret; } /* }}} */ /** * Removes an entry, either by actually removing it or by marking it. */ void phar_entry_remove(phar_entry_data *idata, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; phar = idata->phar; if (idata->internal_file->fp_refcount < 2) { if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } zend_hash_del(&idata->phar->manifest, idata->internal_file->filename, idata->internal_file->filename_len); idata->phar->refcount--; efree(idata); } else { idata->internal_file->is_deleted = 1; phar_entry_delref(idata TSRMLS_CC); } if (!phar->donotflush) { phar_flush(phar, 0, 0, 0, error TSRMLS_CC); } } /* }}} */ #define MAPPHAR_ALLOC_FAIL(msg) \ if (fp) {\ php_stream_close(fp);\ }\ if (error) {\ spprintf(error, 0, msg, fname);\ }\ return FAILURE; #define MAPPHAR_FAIL(msg) \ efree(savebuf);\ if (mydata) {\ phar_destroy_phar_data(mydata TSRMLS_CC);\ }\ if (signature) {\ pefree(signature, PHAR_G(persist));\ }\ MAPPHAR_ALLOC_FAIL(msg) #ifdef WORDS_BIGENDIAN # define PHAR_GET_32(buffer, var) \ var = ((((unsigned char*)(buffer))[3]) << 24) \ | ((((unsigned char*)(buffer))[2]) << 16) \ | ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 4 # define PHAR_GET_16(buffer, var) \ var = ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 2 #else # define PHAR_GET_32(buffer, var) \ memcpy(&var, buffer, sizeof(var)); \ buffer += 4 # define PHAR_GET_16(buffer, var) \ var = *(php_uint16*)(buffer); \ buffer += 2 #endif #define PHAR_ZIP_16(var) ((php_uint16)((((php_uint16)var[0]) & 0xff) | \ (((php_uint16)var[1]) & 0xff) << 8)) #define PHAR_ZIP_32(var) ((php_uint32)((((php_uint32)var[0]) & 0xff) | \ (((php_uint32)var[1]) & 0xff) << 8 | \ (((php_uint32)var[2]) & 0xff) << 16 | \ (((php_uint32)var[3]) & 0xff) << 24)) /** * Open an already loaded phar */ int phar_open_parsed_phar(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; #ifdef PHP_WIN32 char *unixfname; #endif if (error) { *error = NULL; } #ifdef PHP_WIN32 unixfname = estrndup(fname, fname_len); phar_unixify_path_separators(unixfname, fname_len); if (SUCCESS == phar_get_archive(&phar, unixfname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(unixfname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; efree(unixfname); #else if (SUCCESS == phar_get_archive(&phar, fname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(fname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; #endif /* logic above is as follows: If an explicit alias was requested, ensure the filename passed in matches the phar's filename. If no alias was passed in, then it can match either and be valid */ if (!is_data) { /* prevent any ".phar" without a stub getting through */ if (!phar->halt_offset && !phar->is_brandnew && (phar->is_tar || phar->is_zip)) { if (PHAR_G(readonly) && FAILURE == zend_hash_find(&(phar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { if (error) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); } return FAILURE; } } } if (pphar) { *pphar = phar; } return SUCCESS; } else { #ifdef PHP_WIN32 efree(unixfname); #endif if (pphar) { *pphar = NULL; } if (phar && error && !(options & REPORT_ERRORS)) { efree(error); } return FAILURE; } } /* }}}*/ /** * Parse out metadata from the manifest for a single file * * Meta-data is in this format: * [len32][data...] * * data is the serialized zval */ int phar_parse_metadata(char **buffer, zval **metadata, php_uint32 zip_metadata_len TSRMLS_DC) /* {{{ */ { php_unserialize_data_t var_hash; if (zip_metadata_len) { const unsigned char *p; unsigned char *p_buff = (unsigned char *)estrndup(*buffer, zip_metadata_len); p = p_buff; ALLOC_ZVAL(*metadata); INIT_ZVAL(**metadata); PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(metadata, &p, p + zip_metadata_len, &var_hash TSRMLS_CC)) { efree(p_buff); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zval_ptr_dtor(metadata); *metadata = NULL; return FAILURE; } efree(p_buff); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (PHAR_G(persist)) { /* lazy init metadata */ zval_ptr_dtor(metadata); *metadata = (zval *) pemalloc(zip_metadata_len, 1); memcpy(*metadata, *buffer, zip_metadata_len); return SUCCESS; } } else { *metadata = NULL; } return SUCCESS; } /* }}}*/ /** * Does not check for a previously opened phar in the cache. * * Parse a new one and add it to the cache, returning either SUCCESS or * FAILURE, and setting pphar to the pointer to the manifest entry * * This is used by phar_open_from_filename to process the manifest, but can be called * directly. */ static int phar_parse_pharfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, long halt_offset, phar_archive_data** pphar, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */ { char b32[4], *buffer, *endbuffer, *savebuf; phar_archive_data *mydata = NULL; phar_entry_info entry; php_uint32 manifest_len, manifest_count, manifest_flags, manifest_index, tmp_len, sig_flags; php_uint16 manifest_ver; php_uint32 len; long offset; int sig_len, register_alias = 0, temp_alias = 0; char *signature = NULL; if (pphar) { *pphar = NULL; } if (error) { *error = NULL; } /* check for ?>\n and increment accordingly */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } buffer = b32; if (3 != php_stream_read(fp, buffer, 3)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((*buffer == ' ' || *buffer == '\n') && *(buffer + 1) == '?' && *(buffer + 2) == '>') { int nextchar; halt_offset += 3; if (EOF == (nextchar = php_stream_getc(fp))) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((char) nextchar == '\r') { /* if we have an \r we require an \n as well */ if (EOF == (nextchar = php_stream_getc(fp)) || (char)nextchar != '\n') { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } ++halt_offset; } if ((char) nextchar == '\n') { ++halt_offset; } } /* make sure we are at the right location to read the manifest */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } /* read in manifest */ buffer = b32; if (4 != php_stream_read(fp, buffer, 4)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at manifest length)") } PHAR_GET_32(buffer, manifest_len); if (manifest_len > 1048576 * 100) { /* prevent serious memory issues by limiting manifest to at most 100 MB in length */ MAPPHAR_ALLOC_FAIL("manifest cannot be larger than 100 MB in phar \"%s\"") } buffer = (char *)emalloc(manifest_len); savebuf = buffer; endbuffer = buffer + manifest_len; if (manifest_len < 10 || manifest_len != php_stream_read(fp, buffer, manifest_len)) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* extract the number of entries */ PHAR_GET_32(buffer, manifest_count); if (manifest_count == 0) { MAPPHAR_FAIL("in phar \"%s\", manifest claims to have zero entries. Phars must have at least 1 entry"); } /* extract API version, lowest nibble currently unused */ manifest_ver = (((unsigned char)buffer[0]) << 8) + ((unsigned char)buffer[1]); buffer += 2; if ((manifest_ver & PHAR_API_VER_MASK) < PHAR_API_MIN_READ) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" is API version %1.u.%1.u.%1.u, and cannot be processed", fname, manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0x0F); } return FAILURE; } PHAR_GET_32(buffer, manifest_flags); manifest_flags &= ~PHAR_HDR_COMPRESSION_MASK; manifest_flags &= ~PHAR_FILE_COMPRESSION_MASK; /* remember whether this entire phar was compressed with gz/bzip2 */ manifest_flags |= compression; /* The lowest nibble contains the phar wide flags. The compression flags can */ /* be ignored on reading because it is being generated anyways. */ if (manifest_flags & PHAR_HDR_SIGNATURE) { char sig_buf[8], *sig_ptr = sig_buf; off_t read_len; size_t end_of_phar; if (-1 == php_stream_seek(fp, -8, SEEK_END) || (read_len = php_stream_tell(fp)) < 20 || 8 != php_stream_read(fp, sig_buf, 8) || memcmp(sig_buf+4, "GBMB", 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } PHAR_GET_32(sig_ptr, sig_flags); switch(sig_flags) { case PHAR_SIG_OPENSSL: { php_uint32 signature_len; char *sig; off_t whence; /* we store the signature followed by the signature length */ if (-1 == php_stream_seek(fp, -12, SEEK_CUR) || 4 != php_stream_read(fp, sig_buf, 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature length could not be read", fname); } return FAILURE; } sig_ptr = sig_buf; PHAR_GET_32(sig_ptr, signature_len); sig = (char *) emalloc(signature_len); whence = signature_len + 4; whence = -whence; if (-1 == php_stream_seek(fp, whence, SEEK_CUR) || !(end_of_phar = php_stream_tell(fp)) || signature_len != php_stream_read(fp, sig, signature_len)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature could not be read", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, end_of_phar, PHAR_SIG_OPENSSL, sig, signature_len, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" openssl signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } efree(sig); } break; #if PHAR_HASH_OK case PHAR_SIG_SHA512: { unsigned char digest[64]; php_stream_seek(fp, -(8 + 64), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA512, (char *)digest, 64, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA512 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_SHA256: { unsigned char digest[32]; php_stream_seek(fp, -(8 + 32), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA256, (char *)digest, 32, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA256 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } #else case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a unsupported signature", fname); } return FAILURE; #endif case PHAR_SIG_SHA1: { unsigned char digest[20]; php_stream_seek(fp, -(8 + 20), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA1, (char *)digest, 20, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA1 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_MD5: { unsigned char digest[16]; php_stream_seek(fp, -(8 + 16), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_MD5, (char *)digest, 16, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" MD5 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } default: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken or unsupported signature", fname); } return FAILURE; } } else if (PHAR_G(require_hash)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" does not have a signature", fname); } return FAILURE; } else { sig_flags = 0; sig_len = 0; } /* extract alias */ PHAR_GET_32(buffer, tmp_len); if (buffer + tmp_len > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (buffer overrun)"); } if (manifest_len < 10 + tmp_len) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* tmp_len = 0 says alias length is 0, which means the alias is not stored in the phar */ if (tmp_len) { /* if the alias is stored we enforce it (implicit overrides explicit) */ if (alias && alias_len && (alias_len != (int)tmp_len || strncmp(alias, buffer, tmp_len))) { buffer[tmp_len] = '\0'; php_stream_close(fp); if (signature) { efree(signature); } if (error) { spprintf(error, 0, "cannot load phar \"%s\" with implicit alias \"%s\" under different alias \"%s\"", fname, buffer, alias); } efree(savebuf); return FAILURE; } alias_len = tmp_len; alias = buffer; buffer += tmp_len; register_alias = 1; } else if (!alias_len || !alias) { /* if we neither have an explicit nor an implicit alias, we use the filename */ alias = NULL; alias_len = 0; register_alias = 0; } else if (alias_len) { register_alias = 1; temp_alias = 1; } /* we have 5 32-bit items plus 1 byte at least */ if (manifest_count > ((manifest_len - 10 - tmp_len) / (5 * 4 + 1))) { /* prevent serious memory issues */ MAPPHAR_FAIL("internal corruption of phar \"%s\" (too many manifest entries for size of manifest)") } mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); mydata->is_persistent = PHAR_G(persist); /* check whether we have meta data, zero check works regardless of byte order */ PHAR_GET_32(buffer, len); if (mydata->is_persistent) { mydata->metadata_len = len; if(!len) { /* FIXME: not sure why this is needed but removing it breaks tests */ PHAR_GET_32(buffer, len); } } if(len > endbuffer - buffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (trying to read past buffer end)"); } if (phar_parse_metadata(&buffer, &mydata->metadata, len TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } buffer += len; /* set up our manifest */ zend_hash_init(&mydata->manifest, manifest_count, zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->virtual_dirs, manifest_count * 2, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif mydata->fname_len = fname_len; offset = halt_offset + manifest_len + 4; memset(&entry, 0, sizeof(phar_entry_info)); entry.phar = mydata; entry.fp_type = PHAR_FP; entry.is_persistent = mydata->is_persistent; for (manifest_index = 0; manifest_index < manifest_count; ++manifest_index) { if (buffer + 24 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)") } PHAR_GET_32(buffer, entry.filename_len); if (entry.filename_len == 0) { MAPPHAR_FAIL("zero-length filename encountered in phar \"%s\""); } if (entry.is_persistent) { entry.manifest_pos = manifest_index; } if (entry.filename_len > endbuffer - buffer - 20) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)"); } if ((manifest_ver & PHAR_API_VER_MASK) >= PHAR_API_MIN_DIR && buffer[entry.filename_len - 1] == '/') { entry.is_dir = 1; } else { entry.is_dir = 0; } phar_add_virtual_dirs(mydata, buffer, entry.filename_len TSRMLS_CC); entry.filename = pestrndup(buffer, entry.filename_len, entry.is_persistent); buffer += entry.filename_len; PHAR_GET_32(buffer, entry.uncompressed_filesize); PHAR_GET_32(buffer, entry.timestamp); if (offset == halt_offset + (int)manifest_len + 4) { mydata->min_timestamp = entry.timestamp; mydata->max_timestamp = entry.timestamp; } else { if (mydata->min_timestamp > entry.timestamp) { mydata->min_timestamp = entry.timestamp; } else if (mydata->max_timestamp < entry.timestamp) { mydata->max_timestamp = entry.timestamp; } } PHAR_GET_32(buffer, entry.compressed_filesize); PHAR_GET_32(buffer, entry.crc32); PHAR_GET_32(buffer, entry.flags); if (entry.is_dir) { entry.filename_len--; entry.flags |= PHAR_ENT_PERM_DEF_DIR; } PHAR_GET_32(buffer, len); if (entry.is_persistent) { entry.metadata_len = len; } else { entry.metadata_len = 0; } if (len > endbuffer - buffer) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)"); } if (phar_parse_metadata(&buffer, &entry.metadata, len TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } buffer += len; entry.offset = entry.offset_abs = offset; offset += entry.compressed_filesize; switch (entry.flags & PHAR_ENT_COMPRESSION_MASK) { case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("zlib extension is required for gz compressed .phar file \"%s\""); } break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("bz2 extension is required for bzip2 compressed .phar file \"%s\""); } break; default: if (entry.uncompressed_filesize != entry.compressed_filesize) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("internal corruption of phar \"%s\" (compressed and uncompressed size does not match for uncompressed entry)"); } break; } manifest_flags |= (entry.flags & PHAR_ENT_COMPRESSION_MASK); /* if signature matched, no need to check CRC32 for each file */ entry.is_crc_checked = (manifest_flags & PHAR_HDR_SIGNATURE ? 1 : 0); phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&mydata->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL); } snprintf(mydata->version, sizeof(mydata->version), "%u.%u.%u", manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0xF); mydata->internal_file_start = halt_offset + manifest_len + 4; mydata->halt_offset = halt_offset; mydata->flags = manifest_flags; endbuffer = strrchr(mydata->fname, '/'); if (endbuffer) { mydata->ext = memchr(endbuffer, '.', (mydata->fname + fname_len) - endbuffer); if (mydata->ext == endbuffer) { mydata->ext = memchr(endbuffer + 1, '.', (mydata->fname + fname_len) - endbuffer - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + mydata->fname_len) - mydata->ext; } } mydata->alias = alias ? pestrndup(alias, alias_len, mydata->is_persistent) : pestrndup(mydata->fname, fname_len, mydata->is_persistent); mydata->alias_len = alias ? alias_len : fname_len; mydata->sig_flags = sig_flags; mydata->fp = fp; mydata->sig_len = sig_len; mydata->signature = signature; phar_request_initialize(TSRMLS_C); if (register_alias) { phar_archive_data **fd_ptr; mydata->is_temporary_alias = temp_alias; if (!phar_validate_alias(mydata->alias, mydata->alias_len)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", invalid alias"); } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", alias is already in use by existing archive"); } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); } else { mydata->is_temporary_alias = 1; } zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); efree(savebuf); if (pphar) { *pphar = mydata; } return SUCCESS; } /* }}} */ /** * Create or open a phar for writing */ int phar_open_or_create_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { const char *ext_str, *z; char *my_error; int ext_len; phar_archive_data **test, *unused = NULL; test = &unused; if (error) { *error = NULL; } /* first try to open an existing file */ if (phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 0, 1 TSRMLS_CC) == SUCCESS) { goto check_file; } /* next try to create a new file */ if (FAILURE == phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 1, 1 TSRMLS_CC)) { if (error) { if (ext_len == -2) { spprintf(error, 0, "Cannot create a phar archive from a URL like \"%s\". Phar objects can only be created from local files", fname); } else { spprintf(error, 0, "Cannot create phar '%s', file extension (or combination) not recognised or the directory does not exist", fname); } } return FAILURE; } check_file: if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, test, &my_error TSRMLS_CC) == SUCCESS) { if (pphar) { *pphar = *test; } if ((*test)->is_data && !(*test)->is_tar && !(*test)->is_zip) { if (error) { spprintf(error, 0, "Cannot open '%s' as a PharData object. Use Phar::__construct() for executable archives", fname); } return FAILURE; } if (PHAR_G(readonly) && !(*test)->is_data && ((*test)->is_tar || (*test)->is_zip)) { phar_entry_info *stub; if (FAILURE == zend_hash_find(&((*test)->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); return FAILURE; } } if (!PHAR_G(readonly) || (*test)->is_data) { (*test)->is_writeable = 1; } return SUCCESS; } else if (my_error) { if (error) { *error = my_error; } else { efree(my_error); } return FAILURE; } if (ext_len > 3 && (z = memchr(ext_str, 'z', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ip", 2)) { /* assume zip-based phar */ return phar_open_or_create_zip(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } if (ext_len > 3 && (z = memchr(ext_str, 't', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ar", 2)) { /* assume tar-based phar */ return phar_open_or_create_tar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } return phar_create_or_parse_filename(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } /* }}} */ int phar_create_or_parse_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *mydata; php_stream *fp; char *actual = NULL, *p; if (!pphar) { pphar = &mydata; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } /* first open readonly so it won't be created if not present */ fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|0, &actual); if (actual) { fname = actual; fname_len = strlen(actual); } if (fp) { if (phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC) == SUCCESS) { if ((*pphar)->is_data || !PHAR_G(readonly)) { (*pphar)->is_writeable = 1; } if (actual) { efree(actual); } return SUCCESS; } else { /* file exists, but is either corrupt or not a phar archive */ if (actual) { efree(actual); } return FAILURE; } } if (actual) { efree(actual); } if (PHAR_G(readonly) && !is_data) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "creating archive \"%s\" disabled by the php.ini setting phar.readonly", fname); } } return FAILURE; } /* set up our manifest */ mydata = ecalloc(1, sizeof(phar_archive_data)); mydata->fname = expand_filepath(fname, NULL TSRMLS_CC); fname_len = strlen(mydata->fname); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif p = strrchr(mydata->fname, '/'); if (p) { mydata->ext = memchr(p, '.', (mydata->fname + fname_len) - p); if (mydata->ext == p) { mydata->ext = memchr(p + 1, '.', (mydata->fname + fname_len) - p - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + fname_len) - mydata->ext; } } if (pphar) { *pphar = mydata; } zend_hash_init(&mydata->manifest, sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&mydata->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&mydata->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname_len = fname_len; snprintf(mydata->version, sizeof(mydata->version), "%s", PHP_PHAR_API_VERSION); mydata->is_temporary_alias = alias ? 0 : 1; mydata->internal_file_start = -1; mydata->fp = NULL; mydata->is_writeable = 1; mydata->is_brandnew = 1; phar_request_initialize(TSRMLS_C); zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); if (is_data) { alias = NULL; alias_len = 0; mydata->is_data = 1; /* assume tar format, PharData can specify other */ mydata->is_tar = 1; } else { phar_archive_data **fd_ptr; if (alias && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: phar \"%s\" cannot set alias \"%s\", already in use by another phar archive", mydata->fname, alias); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } mydata->alias = alias ? estrndup(alias, alias_len) : estrndup(mydata->fname, fname_len); mydata->alias_len = alias ? alias_len : fname_len; } if (alias_len && alias) { if (FAILURE == zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL)) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "archive \"%s\" cannot be associated with alias \"%s\", already in use", fname, alias); } } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } return SUCCESS; } /* }}}*/ /** * Return an already opened filename. * * Or scan a phar file for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ int phar_open_from_filename(char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { php_stream *fp; char *actual; int ret, is_data = 0; if (error) { *error = NULL; } if (!strstr(fname, ".phar")) { is_data = 1; } if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC) == SUCCESS) { return SUCCESS; } else if (error && *error) { return FAILURE; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, &actual); if (!fp) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}}*/ static inline char *phar_strnstr(const char *buf, int buf_len, const char *search, int search_len) /* {{{ */ { const char *c; int so_far = 0; if (buf_len < search_len) { return NULL; } c = buf - 1; do { if (!(c = memchr(c + 1, search[0], buf_len - search_len - so_far))) { return (char *) NULL; } so_far = c - buf; if (so_far >= (buf_len - search_len)) { return (char *) NULL; } if (!memcmp(c, search, search_len)) { return (char *) c; } } while (1); } /* }}} */ /** * Scan an open fp for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ static int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error TSRMLS_DC) /* {{{ */ { const char token[] = "__HALT_COMPILER();"; const char zip_magic[] = "PK\x03\x04"; const char gz_magic[] = "\x1f\x8b\x08"; const char bz_magic[] = "BZh"; char *pos, test = '\0'; const int window_size = 1024; char buffer[1024 + sizeof(token)]; /* a 1024 byte window + the size of the halt_compiler token (moving window) */ const long readsize = sizeof(buffer) - sizeof(token); const long tokenlen = sizeof(token) - 1; long halt_offset; size_t got; php_uint32 compression = PHAR_FILE_COMPRESSED_NONE; if (error) { *error = NULL; } if (-1 == php_stream_rewind(fp)) { MAPPHAR_ALLOC_FAIL("cannot rewind phar \"%s\"") } buffer[sizeof(buffer)-1] = '\0'; memset(buffer, 32, sizeof(token)); halt_offset = 0; /* Maybe it's better to compile the file instead of just searching, */ /* but we only want the offset. So we want a .re scanner to find it. */ while(!php_stream_eof(fp)) { if ((got = php_stream_read(fp, buffer+tokenlen, readsize)) < (size_t) tokenlen) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated entry)") } if (!test) { test = '\1'; pos = buffer+tokenlen; if (!memcmp(pos, gz_magic, 3)) { char err = 0; php_stream_filter *filter; php_stream *temp; /* to properly decompress, we have to tell zlib to look for a zlib or gzip header */ zval filterparams; if (!PHAR_G(has_zlib)) { MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file, enable zlib extension in php.ini") } array_init(&filterparams); /* this is defined in zlib's zconf.h */ #ifndef MAX_WBITS #define MAX_WBITS 15 #endif add_assoc_long(&filterparams, "window", MAX_WBITS + 32); /* entire file is gzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of gzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { err = 1; add_assoc_long(&filterparams, "window", MAX_WBITS); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } } else { zval_dtor(&filterparams); } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != php_stream_copy_to_stream_ex(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { if (err) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_GZ; /* now, start over */ test = '\0'; continue; } else if (!memcmp(pos, bz_magic, 3)) { php_stream_filter *filter; php_stream *temp; if (!PHAR_G(has_bz2)) { MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file, enable bz2 extension in php.ini") } /* entire file is bzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of bzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\", filter creation failed") } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != php_stream_copy_to_stream_ex(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_BZ2; /* now, start over */ test = '\0'; continue; } if (!memcmp(pos, zip_magic, 4)) { php_stream_seek(fp, 0, SEEK_END); return phar_parse_zipfile(fp, fname, fname_len, alias, alias_len, pphar, error TSRMLS_CC); } if (got > 512) { if (phar_is_tar(pos, fname)) { php_stream_rewind(fp); return phar_parse_tarfile(fp, fname, fname_len, alias, alias_len, pphar, is_data, compression, error TSRMLS_CC); } } } if (got > 0 && (pos = phar_strnstr(buffer, got + sizeof(token), token, sizeof(token)-1)) != NULL) { halt_offset += (pos - buffer); /* no -tokenlen+tokenlen here */ return phar_parse_pharfile(fp, fname, fname_len, alias, alias_len, halt_offset, pphar, compression, error TSRMLS_CC); } halt_offset += got; memmove(buffer, buffer + window_size, tokenlen); /* move the memory buffer by the size of the window */ } MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (__HALT_COMPILER(); not found)") } /* }}} */ /* * given the location of the file extension and the start of the file path, * determine the end of the portion of the path (i.e. /path/to/file.ext/blah * grabs "/path/to/file.ext" as does the straight /path/to/file.ext), * stat it to determine if it exists. * if so, check to see if it is a directory and fail if so * if not, check to see if its dirname() exists (i.e. "/path/to") and is a directory * succeed if we are creating the file, otherwise fail. */ static int phar_analyze_path(const char *fname, const char *ext, int ext_len, int for_create TSRMLS_DC) /* {{{ */ { php_stream_statbuf ssb; char *realpath; char *filename = estrndup(fname, (ext - fname) + ext_len); if ((realpath = expand_filepath(filename, NULL TSRMLS_CC))) { #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif if (zend_hash_exists(&(PHAR_GLOBALS->phar_fname_map), realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_phars, realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } efree(realpath); } if (SUCCESS == php_stream_stat_path((char *) filename, &ssb)) { efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return FAILURE; } if (for_create == 1) { return FAILURE; } return SUCCESS; } else { char *slash; if (!for_create) { efree(filename); return FAILURE; } slash = (char *) strrchr(filename, '/'); if (slash) { *slash = '\0'; } if (SUCCESS != php_stream_stat_path((char *) filename, &ssb)) { if (!slash) { if (!(realpath = expand_filepath(filename, NULL TSRMLS_CC))) { efree(filename); return FAILURE; } #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif slash = strstr(realpath, filename); if (slash) { slash += ((ext - fname) + ext_len); *slash = '\0'; } slash = strrchr(realpath, '/'); if (slash) { *slash = '\0'; } else { efree(realpath); efree(filename); return FAILURE; } if (SUCCESS != php_stream_stat_path(realpath, &ssb)) { efree(realpath); efree(filename); return FAILURE; } efree(realpath); if (ssb.sb.st_mode & S_IFDIR) { efree(filename); return SUCCESS; } } efree(filename); return FAILURE; } efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return SUCCESS; } return FAILURE; } } /* }}} */ /* check for ".phar" in extension */ static int phar_check_str(const char *fname, const char *ext_str, int ext_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { char test[51]; const char *pos; if (ext_len >= 50) { return FAILURE; } if (executable == 1) { /* copy "." as well */ memcpy(test, ext_str - 1, ext_len + 1); test[ext_len + 1] = '\0'; /* executable phars must contain ".phar" as a valid extension (phar://.pharmy/oops is invalid) */ /* (phar://hi/there/.phar/oops is also invalid) */ pos = strstr(test, ".phar"); if (pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } else { return FAILURE; } } /* data phars need only contain a single non-"." to be valid */ if (!executable) { pos = strstr(ext_str, ".phar"); if (!(pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) && *(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } else { if (*(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } return FAILURE; } /* }}} */ /* * if executable is 1, only returns SUCCESS if the extension is one of the tar/zip .phar extensions * if executable is 0, it returns SUCCESS only if the filename does *not* contain ".phar" anywhere, and treats * the first extension as the filename extension * * if an extension is found, it sets ext_str to the location of the file extension in filename, * and ext_len to the length of the extension. * for urls like "phar://alias/oops" it instead sets ext_len to -1 and returns FAILURE, which tells * the calling function to use "alias" as the phar alias * * the last parameter should be set to tell the thing to assume that filename is the full path, and only to check the * extension rules, not to iterate. */ int phar_detect_phar_fname_ext(const char *filename, int filename_len, const char **ext_str, int *ext_len, int executable, int for_create, int is_complete TSRMLS_DC) /* {{{ */ { const char *pos, *slash; *ext_str = NULL; *ext_len = 0; if (!filename_len || filename_len == 1) { return FAILURE; } phar_request_initialize(TSRMLS_C); /* first check for alias in first segment */ pos = memchr(filename, '/', filename_len); if (pos && pos != filename) { /* check for url like http:// or phar:// */ if (*(pos - 1) == ':' && (pos - filename) < filename_len - 1 && *(pos + 1) == '/') { *ext_len = -2; *ext_str = NULL; return FAILURE; } if (zend_hash_exists(&(PHAR_GLOBALS->phar_alias_map), (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_alias, (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } } if (zend_hash_num_elements(&(PHAR_GLOBALS->phar_fname_map)) || PHAR_G(manifest_cached)) { phar_archive_data **pphar; if (is_complete) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); woohoo: *ext_len = (*pphar)->ext_len; if (executable == 2) { return SUCCESS; } if (executable == 1 && !(*pphar)->is_data) { return SUCCESS; } if (!executable && (*pphar)->is_data) { return SUCCESS; } return FAILURE; } if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); goto woohoo; } } else { char *str_key; uint keylen; ulong unused; for (zend_hash_internal_pointer_reset(&(PHAR_GLOBALS->phar_fname_map)); HASH_KEY_NON_EXISTENT != zend_hash_get_current_key_ex(&(PHAR_GLOBALS->phar_fname_map), &str_key, &keylen, &unused, 0, NULL); zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)) ) { if (keylen > (uint) filename_len) { continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { if (FAILURE == zend_hash_get_current_data(&(PHAR_GLOBALS->phar_fname_map), (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } } if (PHAR_G(manifest_cached)) { for (zend_hash_internal_pointer_reset(&cached_phars); HASH_KEY_NON_EXISTENT != zend_hash_get_current_key_ex(&cached_phars, &str_key, &keylen, &unused, 0, NULL); zend_hash_move_forward(&cached_phars) ) { if (keylen > (uint) filename_len) { continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { if (FAILURE == zend_hash_get_current_data(&cached_phars, (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } } } } } pos = memchr(filename + 1, '.', filename_len); next_extension: if (!pos) { return FAILURE; } while (pos != filename && (*(pos - 1) == '/' || *(pos - 1) == '\0')) { pos = memchr(pos + 1, '.', filename_len - (pos - filename) + 1); if (!pos) { return FAILURE; } } slash = memchr(pos, '/', filename_len - (pos - filename)); if (!slash) { /* this is a url like "phar://blah.phar" with no directory */ *ext_str = pos; *ext_len = strlen(pos); /* file extension must contain "phar" */ switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* we are at the end of the string, so we fail */ return FAILURE; } } /* we've found an extension that ends at a directory separator */ *ext_str = pos; *ext_len = slash - pos; switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* look for more extensions */ pos = strchr(pos + 1, '.'); if (pos) { *ext_str = NULL; *ext_len = 0; } goto next_extension; } return FAILURE; } /* }}} */ static int php_check_dots(const char *element, int n) /* {{{ */ { for(n--; n >= 0; --n) { if (element[n] != '.') { return 1; } } return 0; } /* }}} */ #define IS_DIRECTORY_UP(element, len) \ (len >= 2 && !php_check_dots(element, len)) #define IS_DIRECTORY_CURRENT(element, len) \ (len == 1 && element[0] == '.') #define IS_BACKSLASH(c) ((c) == '/') #ifdef COMPILE_DL_PHAR /* stupid-ass non-extern declaration in tsrm_strtok.h breaks dumbass MS compiler */ static inline int in_character_class(char ch, const char *delim) /* {{{ */ { while (*delim) { if (*delim == ch) { return 1; } ++delim; } return 0; } /* }}} */ char *tsrm_strtok_r(char *s, const char *delim, char **last) /* {{{ */ { char *token; if (s == NULL) { s = *last; } while (*s && in_character_class(*s, delim)) { ++s; } if (!*s) { return NULL; } token = s; while (*s && !in_character_class(*s, delim)) { ++s; } if (!*s) { *last = s; } else { *s = '\0'; *last = s + 1; } return token; } /* }}} */ #endif /** * Remove .. and . references within a phar filename */ char *phar_fix_filepath(char *path, int *new_len, int use_cwd TSRMLS_DC) /* {{{ */ { char *newpath; int newpath_len; char *ptr; char *tok; int ptr_length, path_length = *new_len; if (PHAR_G(cwd_len) && use_cwd && path_length > 2 && path[0] == '.' && path[1] == '/') { newpath_len = PHAR_G(cwd_len); newpath = emalloc(strlen(path) + newpath_len + 1); memcpy(newpath, PHAR_G(cwd), newpath_len); } else { newpath = emalloc(strlen(path) + 2); newpath[0] = '/'; newpath_len = 1; } ptr = path; if (*ptr == '/') { ++ptr; } tok = ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { switch (path_length - (tok - path)) { case 1: if (*tok == '.') { efree(path); *new_len = 1; efree(newpath); return estrndup("/", 1); } break; case 2: if (tok[0] == '.' && tok[1] == '.') { efree(path); *new_len = 1; efree(newpath); return estrndup("/", 1); } } efree(newpath); return path; } while (ptr) { ptr_length = ptr - tok; last_time: if (IS_DIRECTORY_UP(tok, ptr_length)) { #define PREVIOUS newpath[newpath_len - 1] while (newpath_len > 1 && !IS_BACKSLASH(PREVIOUS)) { newpath_len--; } if (newpath[0] != '/') { newpath[newpath_len] = '\0'; } else if (newpath_len > 1) { --newpath_len; } } else if (!IS_DIRECTORY_CURRENT(tok, ptr_length)) { if (newpath_len > 1) { newpath[newpath_len++] = '/'; memcpy(newpath + newpath_len, tok, ptr_length+1); } else { memcpy(newpath + newpath_len, tok, ptr_length+1); } newpath_len += ptr_length; } if (ptr == path + path_length) { break; } tok = ++ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { ptr_length = path_length - (tok - path); ptr = path + path_length; goto last_time; } } efree(path); *new_len = newpath_len; newpath[newpath_len] = '\0'; return erealloc(newpath, newpath_len + 1); } /* }}} */ /** * Process a phar stream name, ensuring we can handle any of: * * - whatever.phar * - whatever.phar.gz * - whatever.phar.bz2 * - whatever.phar.php * * Optionally the name might start with 'phar://' * * This is used by phar_parse_url() */ int phar_split_fname(const char *filename, int filename_len, char **arch, int *arch_len, char **entry, int *entry_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { const char *ext_str; #ifdef PHP_WIN32 char *save; #endif int ext_len; if (CHECK_NULL_PATH(filename, filename_len)) { return FAILURE; } if (!strncasecmp(filename, "phar://", 7)) { filename += 7; filename_len -= 7; } ext_len = 0; #ifdef PHP_WIN32 save = filename; filename = estrndup(filename, filename_len); phar_unixify_path_separators(filename, filename_len); #endif if (phar_detect_phar_fname_ext(filename, filename_len, &ext_str, &ext_len, executable, for_create, 0 TSRMLS_CC) == FAILURE) { if (ext_len != -1) { if (!ext_str) { /* no / detected, restore arch for error message */ #ifdef PHP_WIN32 *arch = save; #else *arch = filename; #endif } #ifdef PHP_WIN32 efree(filename); #endif return FAILURE; } ext_len = 0; /* no extension detected - instead we are dealing with an alias */ } *arch_len = ext_str - filename + ext_len; *arch = estrndup(filename, *arch_len); if (ext_str[ext_len]) { *entry_len = filename_len - *arch_len; *entry = estrndup(ext_str+ext_len, *entry_len); #ifdef PHP_WIN32 phar_unixify_path_separators(*entry, *entry_len); #endif *entry = phar_fix_filepath(*entry, entry_len, 0 TSRMLS_CC); } else { *entry_len = 1; *entry = estrndup("/", 1); } #ifdef PHP_WIN32 efree(filename); #endif return SUCCESS; } /* }}} */ /** * Invoked when a user calls Phar::mapPhar() from within an executing .phar * to set up its manifest directly */ int phar_open_executed_filename(char *alias, int alias_len, char **error TSRMLS_DC) /* {{{ */ { char *fname; zval *halt_constant; php_stream *fp; int fname_len; char *actual = NULL; int ret; if (error) { *error = NULL; } fname = (char*)zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, 0, REPORT_ERRORS, NULL, 0 TSRMLS_CC) == SUCCESS) { return SUCCESS; } if (!strcmp(fname, "[no active file]")) { if (error) { spprintf(error, 0, "cannot initialize a phar outside of PHP execution"); } return FAILURE; } MAKE_STD_ZVAL(halt_constant); if (0 == zend_get_constant("__COMPILER_HALT_OFFSET__", 24, halt_constant TSRMLS_CC)) { FREE_ZVAL(halt_constant); if (error) { spprintf(error, 0, "__HALT_COMPILER(); must be declared in a phar"); } return FAILURE; } FREE_ZVAL(halt_constant); #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, &actual); if (!fp) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, 0, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}} */ /** * Validate the CRC32 of a file opened from within the phar */ int phar_postprocess_file(phar_entry_data *idata, php_uint32 crc32, char **error, int process_zip TSRMLS_DC) /* {{{ */ { php_uint32 crc = ~0; int len = idata->internal_file->uncompressed_filesize; php_stream *fp = idata->fp; phar_entry_info *entry = idata->internal_file; if (error) { *error = NULL; } if (entry->is_zip && process_zip > 0) { /* verify local file header */ phar_zip_file_header local; phar_zip_data_desc desc; if (SUCCESS != phar_open_archive_fp(idata->phar TSRMLS_CC)) { spprintf(error, 0, "phar error: unable to open zip-based phar archive \"%s\" to verify local file header for file \"%s\"", idata->phar->fname, entry->filename); return FAILURE; } php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset, SEEK_SET); if (sizeof(local) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &local, sizeof(local))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local file header for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } /* check for data descriptor */ if (((PHAR_ZIP_16(local.flags)) & 0x8) == 0x8) { php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset + sizeof(local) + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len) + entry->compressed_filesize, SEEK_SET); if (sizeof(desc) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &desc, sizeof(desc))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local data descriptor for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } if (desc.signature[0] == 'P' && desc.signature[1] == 'K') { memcpy(&(local.crc32), &(desc.crc32), 12); } else { /* old data descriptors have no signature */ memcpy(&(local.crc32), &desc, 12); } } /* verify local header */ if (entry->filename_len != PHAR_ZIP_16(local.filename_len) || entry->crc32 != PHAR_ZIP_32(local.crc32) || entry->uncompressed_filesize != PHAR_ZIP_32(local.uncompsize) || entry->compressed_filesize != PHAR_ZIP_32(local.compsize)) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (local header of file \"%s\" does not match central directory)", idata->phar->fname, entry->filename); return FAILURE; } /* construct actual offset to file start - local extra_len can be different from central extra_len */ entry->offset = entry->offset_abs = sizeof(local) + entry->header_offset + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len); if (idata->zero && idata->zero != entry->offset_abs) { idata->zero = entry->offset_abs; } } if (process_zip == 1) { return SUCCESS; } php_stream_seek(fp, idata->zero, SEEK_SET); while (len--) { CRC32(crc, php_stream_getc(fp)); } php_stream_seek(fp, idata->zero, SEEK_SET); if (~crc == crc32) { entry->is_crc_checked = 1; return SUCCESS; } else { spprintf(error, 0, "phar error: internal corruption of phar \"%s\" (crc32 mismatch on file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } } /* }}} */ static inline void phar_set_32(char *buffer, int var) /* {{{ */ { #ifdef WORDS_BIGENDIAN *((buffer) + 3) = (unsigned char) (((var) >> 24) & 0xFF); *((buffer) + 2) = (unsigned char) (((var) >> 16) & 0xFF); *((buffer) + 1) = (unsigned char) (((var) >> 8) & 0xFF); *((buffer) + 0) = (unsigned char) ((var) & 0xFF); #else memcpy(buffer, &var, sizeof(var)); #endif } /* }}} */ static int phar_flush_clean_deleted_apply(void *data TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)data; if (entry->fp_refcount <= 0 && entry->is_deleted) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ #include "stub.h" char *phar_create_default_stub(const char *index_php, const char *web_index, size_t *len, char **error TSRMLS_DC) /* {{{ */ { char *stub = NULL; int index_len, web_len; size_t dummy; if (!len) { len = &dummy; } if (error) { *error = NULL; } if (!index_php) { index_php = "index.php"; } if (!web_index) { web_index = "index.php"; } index_len = strlen(index_php); web_len = strlen(web_index); if (index_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", index_len); return NULL; } } if (web_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal web filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", web_len); return NULL; } } phar_get_stub(index_php, web_index, len, &stub, index_len+1, web_len+1 TSRMLS_CC); return stub; } /* }}} */ /** * Save phar contents to disk * * user_stub contains either a string, or a resource pointer, if len is a negative length. * user_stub and len should be both 0 if the default or existing stub should be used */ int phar_flush(phar_archive_data *phar, char *user_stub, long len, int convert, char **error TSRMLS_DC) /* {{{ */ { char halt_stub[] = "__HALT_COMPILER();"; char *newstub, *tmp; phar_entry_info *entry, *newentry; int halt_offset, restore_alias_len, global_flags = 0, closeoldfile; char *pos, has_dirs = 0; char manifest[18], entry_buffer[24]; off_t manifest_ftell; long offset; size_t wrote; php_uint32 manifest_len, mytime, loc, new_manifest_count; php_uint32 newcrc32; php_stream *file, *oldfile, *newfile, *stubfile; php_stream_filter *filter; php_serialize_data_t metadata_hash; smart_str main_metadata_str = {0}; int free_user_stub, free_fp = 1, free_ufp = 1; int manifest_hack = 0; if (phar->is_persistent) { if (error) { spprintf(error, 0, "internal error: attempt to flush cached zip-based phar \"%s\"", phar->fname); } return EOF; } if (error) { *error = NULL; } if (!zend_hash_num_elements(&phar->manifest) && !user_stub) { return EOF; } zend_hash_clean(&phar->virtual_dirs); if (phar->is_zip) { return phar_zip_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (phar->is_tar) { return phar_tar_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (PHAR_G(readonly)) { return EOF; } if (phar->fp && !phar->is_brandnew) { oldfile = phar->fp; closeoldfile = 0; php_stream_rewind(oldfile); } else { oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL); closeoldfile = oldfile != NULL; } newfile = php_stream_fopen_tmpfile(); if (!newfile) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } return EOF; } if (user_stub) { if (len < 0) { /* resource passed in */ if (!(php_stream_from_zval_no_verify(stubfile, (zval **)user_stub))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to access resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } if (len == -1) { len = PHP_STREAM_COPY_ALL; } else { len = -len; } user_stub = 0; if (!(len = php_stream_copy_to_mem(stubfile, &user_stub, len, 0)) || !user_stub) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to read resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } free_user_stub = 1; } else { free_user_stub = 0; } tmp = estrndup(user_stub, len); if ((pos = php_stristr(tmp, halt_stub, len, sizeof(halt_stub) - 1)) == NULL) { efree(tmp); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "illegal stub for phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } pos = user_stub + (pos - tmp); efree(tmp); len = pos - user_stub + 18; if ((size_t)len != php_stream_write(newfile, user_stub, len) || 5 != php_stream_write(newfile, " ?>\r\n", 5)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to create stub from string in new phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } phar->halt_offset = len + 5; if (free_user_stub) { efree(user_stub); } } else { size_t written; if (!user_stub && phar->halt_offset && oldfile && !phar->is_brandnew) { php_stream_copy_to_stream_ex(oldfile, newfile, phar->halt_offset, &written); newstub = NULL; } else { /* this is either a brand new phar or a default stub overwrite */ newstub = phar_create_default_stub(NULL, NULL, &(phar->halt_offset), NULL TSRMLS_CC); written = php_stream_write(newfile, newstub, phar->halt_offset); } if (phar->halt_offset != written) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (newstub) { spprintf(error, 0, "unable to create stub in new phar \"%s\"", phar->fname); } else { spprintf(error, 0, "unable to copy stub of old phar to new phar \"%s\"", phar->fname); } } if (newstub) { efree(newstub); } return EOF; } if (newstub) { efree(newstub); } } manifest_ftell = php_stream_tell(newfile); halt_offset = manifest_ftell; /* Check whether we can get rid of some of the deleted entries which are * unused. However some might still be in use so even after this clean-up * we need to skip entries marked is_deleted. */ zend_hash_apply(&phar->manifest, phar_flush_clean_deleted_apply TSRMLS_CC); /* compress as necessary, calculate crcs, serialize meta-data, manifest size, and file sizes */ main_metadata_str.c = 0; if (phar->metadata) { PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&main_metadata_str, &phar->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { main_metadata_str.len = 0; } new_manifest_count = 0; offset = 0; for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->cfp) { /* did we forget to get rid of cfp last time? */ php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar */ continue; } if (!entry->is_modified && entry->fp_refcount) { /* open file pointers refer to this fp, do not free the stream */ switch (entry->fp_type) { case PHAR_FP: free_fp = 0; break; case PHAR_UFP: free_ufp = 0; default: break; } } /* after excluding deleted files, calculate manifest size in bytes and number of entries */ ++new_manifest_count; phar_add_virtual_dirs(phar, entry->filename, entry->filename_len TSRMLS_CC); if (entry->is_dir) { /* we use this to calculate API version, 1.1.1 is used for phars with directories */ has_dirs = 1; } if (entry->metadata) { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&entry->metadata_str, &entry->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; } /* 32 bits for filename length, length of filename, manifest + metadata, and add 1 for trailing / if a directory */ offset += 4 + entry->filename_len + sizeof(entry_buffer) + entry->metadata_str.len + (entry->is_dir ? 1 : 0); /* compress and rehash as necessary */ if ((oldfile && !entry->is_modified) || entry->is_dir) { if (entry->fp_type == PHAR_UFP) { /* reset so we can copy the compressed data over */ entry->fp_type = PHAR_FP; } continue; } if (!phar_get_efp(entry, 0 TSRMLS_CC)) { /* re-open internal file pointer just-in-time */ newentry = phar_open_jit(phar, entry, error TSRMLS_CC); if (!newentry) { /* major problem re-opening, so we ignore this file and the error */ efree(*error); *error = NULL; continue; } entry = newentry; } file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } newcrc32 = ~0; mytime = entry->uncompressed_filesize; for (loc = 0;loc < mytime; ++loc) { CRC32(newcrc32, php_stream_getc(file)); } entry->crc32 = ~newcrc32; entry->is_crc_checked = 1; if (!(entry->flags & PHAR_ENT_COMPRESSION_MASK)) { /* not compressed */ entry->compressed_filesize = entry->uncompressed_filesize; continue; } filter = php_stream_filter_create(phar_compress_filter(entry, 0), NULL, 0 TSRMLS_CC); if (!filter) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (entry->flags & PHAR_ENT_COMPRESSED_GZ) { if (error) { spprintf(error, 0, "unable to gzip compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } else { if (error) { spprintf(error, 0, "unable to bzip2 compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* create new file that holds the compressed version */ /* work around inability to specify freedom in write and strictness in read count */ entry->cfp = php_stream_fopen_tmpfile(); if (!entry->cfp) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_flush(file); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_append((&entry->cfp->writefilters), filter); if (SUCCESS != php_stream_copy_to_stream_ex(file, entry->cfp, entry->uncompressed_filesize, NULL)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to copy compressed file contents of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_flush(filter, 1); php_stream_flush(entry->cfp); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_seek(entry->cfp, 0, SEEK_END); entry->compressed_filesize = (php_uint32) php_stream_tell(entry->cfp); /* generate crc on compressed file */ php_stream_rewind(entry->cfp); entry->old_flags = entry->flags; entry->is_modified = 1; global_flags |= (entry->flags & PHAR_ENT_COMPRESSION_MASK); } global_flags |= PHAR_HDR_SIGNATURE; /* write out manifest pre-header */ /* 4: manifest length * 4: manifest entry count * 2: phar version * 4: phar global flags * 4: alias length * ?: the alias itself * 4: phar metadata length * ?: phar metadata */ restore_alias_len = phar->alias_len; if (phar->is_temporary_alias) { phar->alias_len = 0; } manifest_len = offset + phar->alias_len + sizeof(manifest) + main_metadata_str.len; phar_set_32(manifest, manifest_len); /* Hack - see bug #65028, add padding byte to the end of the manifest */ if(manifest[0] == '\r' || manifest[0] == '\n') { manifest_len++; phar_set_32(manifest, manifest_len); manifest_hack = 1; } phar_set_32(manifest+4, new_manifest_count); if (has_dirs) { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION) & 0xF0)); } else { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION_NODIR) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION_NODIR) & 0xF0)); } phar_set_32(manifest+10, global_flags); phar_set_32(manifest+14, phar->alias_len); /* write the manifest header */ if (sizeof(manifest) != php_stream_write(newfile, manifest, sizeof(manifest)) || (size_t)phar->alias_len != php_stream_write(newfile, phar->alias, phar->alias_len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest header of new phar \"%s\"", phar->fname); } return EOF; } phar->alias_len = restore_alias_len; phar_set_32(manifest, main_metadata_str.len); if (4 != php_stream_write(newfile, manifest, 4) || (main_metadata_str.len && main_metadata_str.len != php_stream_write(newfile, main_metadata_str.c, main_metadata_str.len))) { smart_str_free(&main_metadata_str); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest meta-data of new phar \"%s\"", phar->fname); } return EOF; } smart_str_free(&main_metadata_str); /* re-calculate the manifest location to simplify later code */ manifest_ftell = php_stream_tell(newfile); /* now write the manifest */ for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar if deleted, ignore if mounted */ continue; } if (entry->is_dir) { /* add 1 for trailing slash */ phar_set_32(entry_buffer, entry->filename_len + 1); } else { phar_set_32(entry_buffer, entry->filename_len); } if (4 != php_stream_write(newfile, entry_buffer, 4) || entry->filename_len != php_stream_write(newfile, entry->filename, entry->filename_len) || (entry->is_dir && 1 != php_stream_write(newfile, "/", 1))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (entry->is_dir) { spprintf(error, 0, "unable to write filename of directory \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } else { spprintf(error, 0, "unable to write filename of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* set the manifest meta-data: 4: uncompressed filesize 4: creation timestamp 4: compressed filesize 4: crc32 4: flags 4: metadata-len +: metadata */ mytime = time(NULL); phar_set_32(entry_buffer, entry->uncompressed_filesize); phar_set_32(entry_buffer+4, mytime); phar_set_32(entry_buffer+8, entry->compressed_filesize); phar_set_32(entry_buffer+12, entry->crc32); phar_set_32(entry_buffer+16, entry->flags); phar_set_32(entry_buffer+20, entry->metadata_str.len); if (sizeof(entry_buffer) != php_stream_write(newfile, entry_buffer, sizeof(entry_buffer)) || entry->metadata_str.len != php_stream_write(newfile, entry->metadata_str.c, entry->metadata_str.len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write temporary manifest of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } /* Hack - see bug #65028, add padding byte to the end of the manifest */ if(manifest_hack) { if(1 != php_stream_write(newfile, manifest, 1)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write manifest padding byte"); } return EOF; } } /* now copy the actual file data to the new phar */ offset = php_stream_tell(newfile); for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_dir || entry->is_mounted) { continue; } if (entry->cfp) { file = entry->cfp; php_stream_rewind(file); } else { file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } if (!file) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } /* this will have changed for all files that have either changed compression or been modified */ entry->offset = entry->offset_abs = offset; offset += entry->compressed_filesize; if (php_stream_copy_to_stream_ex(file, newfile, entry->compressed_filesize, &wrote) == FAILURE) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } return EOF; } entry->is_modified = 0; if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = NULL; } if (entry->fp_type == PHAR_MOD) { /* this fp is in use by a phar_entry_data returned by phar_get_entry_data, it will be closed when the phar_entry_data is phar_entry_delref'ed */ if (entry->fp_refcount == 0 && entry->fp != phar->fp && entry->fp != phar->ufp) { php_stream_close(entry->fp); } entry->fp = NULL; entry->fp_type = PHAR_FP; } else if (entry->fp_type == PHAR_UFP) { entry->fp_type = PHAR_FP; } } /* append signature */ if (global_flags & PHAR_HDR_SIGNATURE) { char sig_buf[4]; php_stream_rewind(newfile); if (phar->signature) { efree(phar->signature); phar->signature = NULL; } switch(phar->sig_flags) { #ifndef PHAR_HASH_OK case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\" with requested hash type", entry->filename, phar->fname); } return EOF; #endif default: { char *digest = NULL; int digest_len; if (FAILURE == phar_create_signature(phar, newfile, &digest, &digest_len, error TSRMLS_CC)) { if (error) { char *save = *error; spprintf(error, 0, "phar error: unable to write signature: %s", save); efree(save); } if (digest) { efree(digest); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_write(newfile, digest, digest_len); efree(digest); if (phar->sig_flags == PHAR_SIG_OPENSSL) { phar_set_32(sig_buf, digest_len); php_stream_write(newfile, sig_buf, 4); } break; } } phar_set_32(sig_buf, phar->sig_flags); php_stream_write(newfile, sig_buf, 4); php_stream_write(newfile, "GBMB", 4); } /* finally, close the temp file, rename the original phar, move the temp to the old phar, unlink the old phar, and reload it into memory */ if (phar->fp && free_fp) { php_stream_close(phar->fp); } if (phar->ufp) { if (free_ufp) { php_stream_close(phar->ufp); } phar->ufp = NULL; } if (closeoldfile) { php_stream_close(oldfile); } phar->internal_file_start = halt_offset + manifest_len + 4; phar->halt_offset = halt_offset; phar->is_brandnew = 0; php_stream_rewind(newfile); if (phar->donotflush) { /* deferred flush */ phar->fp = newfile; } else { phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL); if (!phar->fp) { phar->fp = newfile; if (error) { spprintf(error, 4096, "unable to open new phar \"%s\" for writing", phar->fname); } return EOF; } if (phar->flags & PHAR_FILE_COMPRESSED_GZ) { /* to properly compress, we have to tell zlib to add a zlib header */ zval filterparams; array_init(&filterparams); add_assoc_long(&filterparams, "window", MAX_WBITS+16); filter = php_stream_filter_create("zlib.deflate", &filterparams, php_stream_is_persistent(phar->fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { if (error) { spprintf(error, 4096, "unable to compress all contents of phar \"%s\" using zlib, PHP versions older than 5.2.6 have a buggy zlib", phar->fname); } return EOF; } php_stream_filter_append(&phar->fp->writefilters, filter); php_stream_copy_to_stream_ex(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else if (phar->flags & PHAR_FILE_COMPRESSED_BZ2) { filter = php_stream_filter_create("bzip2.compress", NULL, php_stream_is_persistent(phar->fp) TSRMLS_CC); php_stream_filter_append(&phar->fp->writefilters, filter); php_stream_copy_to_stream_ex(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else { php_stream_copy_to_stream_ex(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); /* we could also reopen the file in "rb" mode but there is no need for that */ php_stream_close(newfile); } } if (-1 == php_stream_seek(phar->fp, phar->halt_offset, SEEK_SET)) { if (error) { spprintf(error, 0, "unable to seek to __HALT_COMPILER(); in new phar \"%s\"", phar->fname); } return EOF; } return EOF; } /* }}} */ #ifdef COMPILE_DL_PHAR ZEND_GET_MODULE(phar) #endif /* {{{ phar_functions[] * * Every user visible function must have an entry in phar_functions[]. */ zend_function_entry phar_functions[] = { PHP_FE_END }; /* }}}*/ static size_t phar_zend_stream_reader(void *handle, char *buf, size_t len TSRMLS_DC) /* {{{ */ { return php_stream_read(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC), buf, len); } /* }}} */ static size_t phar_zend_stream_fsizer(void *handle TSRMLS_DC) /* {{{ */ { return ((phar_archive_data*)handle)->halt_offset + 32; } /* }}} */ zend_op_array *(*phar_orig_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); #define phar_orig_zend_open zend_stream_open_function static char *phar_resolve_path(const char *filename, int filename_len TSRMLS_DC) { return phar_find_in_include_path((char *) filename, filename_len, NULL TSRMLS_CC); } static zend_op_array *phar_compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) /* {{{ */ { zend_op_array *res; char *name = NULL; int failed; phar_archive_data *phar; if (!file_handle || !file_handle->filename) { return phar_orig_compile_file(file_handle, type TSRMLS_CC); } if (strstr(file_handle->filename, ".phar") && !strstr(file_handle->filename, "://")) { if (SUCCESS == phar_open_from_filename((char*)file_handle->filename, strlen(file_handle->filename), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { if (phar->is_zip || phar->is_tar) { zend_file_handle f = *file_handle; /* zip or tar-based phar */ spprintf(&name, 4096, "phar://%s/%s", file_handle->filename, ".phar/stub.php"); if (SUCCESS == phar_orig_zend_open((const char *)name, file_handle TSRMLS_CC)) { efree(name); name = NULL; file_handle->filename = f.filename; if (file_handle->opened_path) { efree(file_handle->opened_path); } file_handle->opened_path = f.opened_path; file_handle->free_filename = f.free_filename; } else { *file_handle = f; } } else if (phar->flags & PHAR_FILE_COMPRESSION_MASK) { /* compressed phar */ file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; file_handle->handle.stream.fsizer = phar_zend_stream_fsizer; file_handle->handle.stream.isatty = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); memset(&file_handle->handle.stream.mmap, 0, sizeof(file_handle->handle.stream.mmap)); } } } zend_try { failed = 0; CG(zend_lineno) = 0; res = phar_orig_compile_file(file_handle, type TSRMLS_CC); } zend_catch { failed = 1; res = NULL; } zend_end_try(); if (name) { efree(name); } if (failed) { zend_bailout(); } return res; } /* }}} */ typedef zend_op_array* (zend_compile_t)(zend_file_handle*, int TSRMLS_DC); typedef zend_compile_t* (compile_hook)(zend_compile_t *ptr); PHP_GINIT_FUNCTION(phar) /* {{{ */ { phar_mime_type mime; memset(phar_globals, 0, sizeof(zend_phar_globals)); phar_globals->readonly = 1; zend_hash_init(&phar_globals->mime_types, 0, NULL, NULL, 1); #define PHAR_SET_MIME(mimetype, ret, fileext) \ mime.mime = mimetype; \ mime.len = sizeof((mimetype))+1; \ mime.type = ret; \ zend_hash_add(&phar_globals->mime_types, fileext, sizeof(fileext)-1, (void *)&mime, sizeof(phar_mime_type), NULL); \ PHAR_SET_MIME("text/html", PHAR_MIME_PHPS, "phps") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cc") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cpp") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c++") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "dtd") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "h") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "log") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "rng") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "txt") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "xsd") PHAR_SET_MIME("", PHAR_MIME_PHP, "php") PHAR_SET_MIME("", PHAR_MIME_PHP, "inc") PHAR_SET_MIME("video/avi", PHAR_MIME_OTHER, "avi") PHAR_SET_MIME("image/bmp", PHAR_MIME_OTHER, "bmp") PHAR_SET_MIME("text/css", PHAR_MIME_OTHER, "css") PHAR_SET_MIME("image/gif", PHAR_MIME_OTHER, "gif") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htm") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "html") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htmls") PHAR_SET_MIME("image/x-ico", PHAR_MIME_OTHER, "ico") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpe") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpg") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpeg") PHAR_SET_MIME("application/x-javascript", PHAR_MIME_OTHER, "js") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "midi") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "mid") PHAR_SET_MIME("audio/mod", PHAR_MIME_OTHER, "mod") PHAR_SET_MIME("movie/quicktime", PHAR_MIME_OTHER, "mov") PHAR_SET_MIME("audio/mp3", PHAR_MIME_OTHER, "mp3") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpg") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpeg") PHAR_SET_MIME("application/pdf", PHAR_MIME_OTHER, "pdf") PHAR_SET_MIME("image/png", PHAR_MIME_OTHER, "png") PHAR_SET_MIME("application/shockwave-flash", PHAR_MIME_OTHER, "swf") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tif") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tiff") PHAR_SET_MIME("audio/wav", PHAR_MIME_OTHER, "wav") PHAR_SET_MIME("image/xbm", PHAR_MIME_OTHER, "xbm") PHAR_SET_MIME("text/xml", PHAR_MIME_OTHER, "xml") phar_restore_orig_functions(TSRMLS_C); } /* }}} */ PHP_GSHUTDOWN_FUNCTION(phar) /* {{{ */ { zend_hash_destroy(&phar_globals->mime_types); } /* }}} */ PHP_MINIT_FUNCTION(phar) /* {{{ */ { REGISTER_INI_ENTRIES(); phar_orig_compile_file = zend_compile_file; zend_compile_file = phar_compile_file; phar_save_resolve_path = zend_resolve_path; zend_resolve_path = phar_resolve_path; phar_object_init(TSRMLS_C); phar_intercept_functions_init(TSRMLS_C); phar_save_orig_functions(TSRMLS_C); return php_register_url_stream_wrapper("phar", &php_stream_phar_wrapper TSRMLS_CC); } /* }}} */ PHP_MSHUTDOWN_FUNCTION(phar) /* {{{ */ { php_unregister_url_stream_wrapper("phar" TSRMLS_CC); phar_intercept_functions_shutdown(TSRMLS_C); if (zend_compile_file == phar_compile_file) { zend_compile_file = phar_orig_compile_file; } if (PHAR_G(manifest_cached)) { zend_hash_destroy(&(cached_phars)); zend_hash_destroy(&(cached_alias)); } return SUCCESS; } /* }}} */ void phar_request_initialize(TSRMLS_D) /* {{{ */ { if (!PHAR_GLOBALS->request_init) { PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); PHAR_GLOBALS->request_init = 1; PHAR_GLOBALS->request_ends = 0; PHAR_GLOBALS->request_done = 0; zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), 5, zend_get_hash_value, destroy_phar_data, 0); zend_hash_init(&(PHAR_GLOBALS->phar_persist_map), 5, zend_get_hash_value, NULL, 0); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), 5, zend_get_hash_value, NULL, 0); if (PHAR_G(manifest_cached)) { phar_archive_data **pphar; phar_entry_fp *stuff = (phar_entry_fp *) ecalloc(zend_hash_num_elements(&cached_phars), sizeof(phar_entry_fp)); for (zend_hash_internal_pointer_reset(&cached_phars); zend_hash_get_current_data(&cached_phars, (void **)&pphar) == SUCCESS; zend_hash_move_forward(&cached_phars)) { stuff[pphar[0]->phar_pos].manifest = (phar_entry_fp_info *) ecalloc( zend_hash_num_elements(&(pphar[0]->manifest)), sizeof(phar_entry_fp_info)); } PHAR_GLOBALS->cached_fp = stuff; } PHAR_GLOBALS->phar_SERVER_mung_list = 0; PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } } /* }}} */ PHP_RSHUTDOWN_FUNCTION(phar) /* {{{ */ { int i; PHAR_GLOBALS->request_ends = 1; if (PHAR_GLOBALS->request_init) { phar_release_functions(TSRMLS_C); zend_hash_destroy(&(PHAR_GLOBALS->phar_alias_map)); PHAR_GLOBALS->phar_alias_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_fname_map)); PHAR_GLOBALS->phar_fname_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_persist_map)); PHAR_GLOBALS->phar_persist_map.arBuckets = NULL; PHAR_GLOBALS->phar_SERVER_mung_list = 0; if (PHAR_GLOBALS->cached_fp) { for (i = 0; i < zend_hash_num_elements(&cached_phars); ++i) { if (PHAR_GLOBALS->cached_fp[i].fp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].fp); } if (PHAR_GLOBALS->cached_fp[i].ufp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].ufp); } efree(PHAR_GLOBALS->cached_fp[i].manifest); } efree(PHAR_GLOBALS->cached_fp); PHAR_GLOBALS->cached_fp = 0; } PHAR_GLOBALS->request_init = 0; if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); } PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } PHAR_GLOBALS->request_done = 1; return SUCCESS; } /* }}} */ PHP_MINFO_FUNCTION(phar) /* {{{ */ { phar_request_initialize(TSRMLS_C); php_info_print_table_start(); php_info_print_table_header(2, "Phar: PHP Archive support", "enabled"); php_info_print_table_row(2, "Phar EXT version", PHP_PHAR_VERSION); php_info_print_table_row(2, "Phar API version", PHP_PHAR_API_VERSION); php_info_print_table_row(2, "SVN revision", "$Id$"); php_info_print_table_row(2, "Phar-based phar archives", "enabled"); php_info_print_table_row(2, "Tar-based phar archives", "enabled"); php_info_print_table_row(2, "ZIP-based phar archives", "enabled"); if (PHAR_G(has_zlib)) { php_info_print_table_row(2, "gzip compression", "enabled"); } else { php_info_print_table_row(2, "gzip compression", "disabled (install ext/zlib)"); } if (PHAR_G(has_bz2)) { php_info_print_table_row(2, "bzip2 compression", "enabled"); } else { php_info_print_table_row(2, "bzip2 compression", "disabled (install pecl/bz2)"); } #ifdef PHAR_HAVE_OPENSSL php_info_print_table_row(2, "Native OpenSSL support", "enabled"); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { php_info_print_table_row(2, "OpenSSL support", "enabled"); } else { php_info_print_table_row(2, "OpenSSL support", "disabled (install ext/openssl)"); } #endif php_info_print_table_end(); php_info_print_box_start(0); PUTS("Phar based on pear/PHP_Archive, original concept by Davey Shafik."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Phar fully realized by Gregory Beaver and Marcus Boerger."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Portions of tar implementation Copyright (c) 2003-2009 Tim Kientzle."); php_info_print_box_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ phar_module_entry */ static const zend_module_dep phar_deps[] = { ZEND_MOD_OPTIONAL("apc") ZEND_MOD_OPTIONAL("bz2") ZEND_MOD_OPTIONAL("openssl") ZEND_MOD_OPTIONAL("zlib") ZEND_MOD_OPTIONAL("standard") #if defined(HAVE_HASH) && !defined(COMPILE_DL_HASH) ZEND_MOD_REQUIRED("hash") #endif #if HAVE_SPL ZEND_MOD_REQUIRED("spl") #endif ZEND_MOD_END }; zend_module_entry phar_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, phar_deps, "Phar", phar_functions, PHP_MINIT(phar), PHP_MSHUTDOWN(phar), NULL, PHP_RSHUTDOWN(phar), PHP_MINFO(phar), PHP_PHAR_VERSION, PHP_MODULE_GLOBALS(phar), /* globals descriptor */ PHP_GINIT(phar), /* globals ctor */ PHP_GSHUTDOWN(phar), /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4824_0
crossvul-cpp_data_good_4835_0
/* * HTTP protocol for ffmpeg client * Copyright (c) 2000, 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #if CONFIG_ZLIB #include <zlib.h> #endif /* CONFIG_ZLIB */ #include "libavutil/avassert.h" #include "libavutil/avstring.h" #include "libavutil/opt.h" #include "libavutil/time.h" #include "avformat.h" #include "http.h" #include "httpauth.h" #include "internal.h" #include "network.h" #include "os_support.h" #include "url.h" /* XXX: POST protocol is not completely implemented because ffmpeg uses * only a subset of it. */ /* The IO buffer size is unrelated to the max URL size in itself, but needs * to be large enough to fit the full request headers (including long * path names). */ #define BUFFER_SIZE MAX_URL_SIZE #define MAX_REDIRECTS 8 #define HTTP_SINGLE 1 #define HTTP_MUTLI 2 typedef enum { LOWER_PROTO, READ_HEADERS, WRITE_REPLY_HEADERS, FINISH }HandshakeState; typedef struct HTTPContext { const AVClass *class; URLContext *hd; unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end; int line_count; int http_code; /* Used if "Transfer-Encoding: chunked" otherwise -1. */ uint64_t chunksize; uint64_t off, end_off, filesize; char *location; HTTPAuthState auth_state; HTTPAuthState proxy_auth_state; char *http_proxy; char *headers; char *mime_type; char *user_agent; #if FF_API_HTTP_USER_AGENT char *user_agent_deprecated; #endif char *content_type; /* Set if the server correctly handles Connection: close and will close * the connection after feeding us the content. */ int willclose; int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */ int chunked_post; /* A flag which indicates if the end of chunked encoding has been sent. */ int end_chunked_post; /* A flag which indicates we have finished to read POST reply. */ int end_header; /* A flag which indicates if we use persistent connections. */ int multiple_requests; uint8_t *post_data; int post_datalen; int is_akamai; int is_mediagateway; char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name) /* A dictionary containing cookies keyed by cookie name */ AVDictionary *cookie_dict; int icy; /* how much data was read since the last ICY metadata packet */ uint64_t icy_data_read; /* after how many bytes of read data a new metadata packet will be found */ uint64_t icy_metaint; char *icy_metadata_headers; char *icy_metadata_packet; AVDictionary *metadata; #if CONFIG_ZLIB int compressed; z_stream inflate_stream; uint8_t *inflate_buffer; #endif /* CONFIG_ZLIB */ AVDictionary *chained_options; int send_expect_100; char *method; int reconnect; int reconnect_at_eof; int reconnect_streamed; int reconnect_delay; int reconnect_delay_max; int listen; char *resource; int reply_code; int is_multi_client; HandshakeState handshake_step; int is_connected_server; } HTTPContext; #define OFFSET(x) offsetof(HTTPContext, x) #define D AV_OPT_FLAG_DECODING_PARAM #define E AV_OPT_FLAG_ENCODING_PARAM #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION) static const AVOption options[] = { { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D }, { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E }, { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E }, { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E }, { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E }, { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D }, #if FF_API_HTTP_USER_AGENT { "user-agent", "override User-Agent header", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D }, #endif { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E }, { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E }, { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY }, { "cookies", "set cookies to be sent in applicable future requests, use newline delimited Set-Cookie HTTP field value syntax", OFFSET(cookies), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D }, { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D }, { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT }, { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT }, { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT }, { "auth_type", "HTTP authentication type", OFFSET(auth_state.auth_type), AV_OPT_TYPE_INT, { .i64 = HTTP_AUTH_NONE }, HTTP_AUTH_NONE, HTTP_AUTH_BASIC, D | E, "auth_type"}, { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"}, { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"}, { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E }, { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E }, { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D }, { "end_offset", "try to limit the request to bytes preceding this offset", OFFSET(end_off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D }, { "method", "Override the HTTP method or set the expected HTTP method from a client", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E }, { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D }, { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D }, { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D }, { "reconnect_delay_max", "max reconnect delay in seconds after which to give up", OFFSET(reconnect_delay_max), AV_OPT_TYPE_INT, { .i64 = 120 }, 0, UINT_MAX/1000/1000, D }, { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E }, { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E }, { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E}, { NULL } }; static int http_connect(URLContext *h, const char *path, const char *local_path, const char *hoststr, const char *auth, const char *proxyauth, int *new_location); static int http_read_header(URLContext *h, int *new_location); void ff_http_init_auth_state(URLContext *dest, const URLContext *src) { memcpy(&((HTTPContext *)dest->priv_data)->auth_state, &((HTTPContext *)src->priv_data)->auth_state, sizeof(HTTPAuthState)); memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state, &((HTTPContext *)src->priv_data)->proxy_auth_state, sizeof(HTTPAuthState)); } static int http_open_cnx_internal(URLContext *h, AVDictionary **options) { const char *path, *proxy_path, *lower_proto = "tcp", *local_path; char hostname[1024], hoststr[1024], proto[10]; char auth[1024], proxyauth[1024] = ""; char path1[MAX_URL_SIZE]; char buf[1024], urlbuf[MAX_URL_SIZE]; int port, use_proxy, err, location_changed = 0; HTTPContext *s = h->priv_data; av_url_split(proto, sizeof(proto), auth, sizeof(auth), hostname, sizeof(hostname), &port, path1, sizeof(path1), s->location); ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL); proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy"); use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) && proxy_path && av_strstart(proxy_path, "http://", NULL); if (!strcmp(proto, "https")) { lower_proto = "tls"; use_proxy = 0; if (port < 0) port = 443; } if (port < 0) port = 80; if (path1[0] == '\0') path = "/"; else path = path1; local_path = path; if (use_proxy) { /* Reassemble the request URL without auth string - we don't * want to leak the auth to the proxy. */ ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s", path1); path = urlbuf; av_url_split(NULL, 0, proxyauth, sizeof(proxyauth), hostname, sizeof(hostname), &port, NULL, 0, proxy_path); } ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL); if (!s->hd) { err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE, &h->interrupt_callback, options, h->protocol_whitelist, h->protocol_blacklist, h); if (err < 0) return err; } err = http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed); if (err < 0) return err; return location_changed; } /* return non zero if error */ static int http_open_cnx(URLContext *h, AVDictionary **options) { HTTPAuthType cur_auth_type, cur_proxy_auth_type; HTTPContext *s = h->priv_data; int location_changed, attempts = 0, redirects = 0; redo: av_dict_copy(options, s->chained_options, 0); cur_auth_type = s->auth_state.auth_type; cur_proxy_auth_type = s->auth_state.auth_type; location_changed = http_open_cnx_internal(h, options); if (location_changed < 0) goto fail; attempts++; if (s->http_code == 401) { if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) && s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) { ffurl_closep(&s->hd); goto redo; } else goto fail; } if (s->http_code == 407) { if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) && s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) { ffurl_closep(&s->hd); goto redo; } else goto fail; } if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307) && location_changed == 1) { /* url moved, get next */ ffurl_closep(&s->hd); if (redirects++ >= MAX_REDIRECTS) return AVERROR(EIO); /* Restart the authentication process with the new target, which * might use a different auth mechanism. */ memset(&s->auth_state, 0, sizeof(s->auth_state)); attempts = 0; location_changed = 0; goto redo; } return 0; fail: if (s->hd) ffurl_closep(&s->hd); if (location_changed < 0) return location_changed; return ff_http_averror(s->http_code, AVERROR(EIO)); } int ff_http_do_new_request(URLContext *h, const char *uri) { HTTPContext *s = h->priv_data; AVDictionary *options = NULL; int ret; s->off = 0; s->icy_data_read = 0; av_free(s->location); s->location = av_strdup(uri); if (!s->location) return AVERROR(ENOMEM); ret = http_open_cnx(h, &options); av_dict_free(&options); return ret; } int ff_http_averror(int status_code, int default_averror) { switch (status_code) { case 400: return AVERROR_HTTP_BAD_REQUEST; case 401: return AVERROR_HTTP_UNAUTHORIZED; case 403: return AVERROR_HTTP_FORBIDDEN; case 404: return AVERROR_HTTP_NOT_FOUND; default: break; } if (status_code >= 400 && status_code <= 499) return AVERROR_HTTP_OTHER_4XX; else if (status_code >= 500) return AVERROR_HTTP_SERVER_ERROR; else return default_averror; } static int http_write_reply(URLContext* h, int status_code) { int ret, body = 0, reply_code, message_len; const char *reply_text, *content_type; HTTPContext *s = h->priv_data; char message[BUFFER_SIZE]; content_type = "text/plain"; if (status_code < 0) body = 1; switch (status_code) { case AVERROR_HTTP_BAD_REQUEST: case 400: reply_code = 400; reply_text = "Bad Request"; break; case AVERROR_HTTP_FORBIDDEN: case 403: reply_code = 403; reply_text = "Forbidden"; break; case AVERROR_HTTP_NOT_FOUND: case 404: reply_code = 404; reply_text = "Not Found"; break; case 200: reply_code = 200; reply_text = "OK"; content_type = s->content_type ? s->content_type : "application/octet-stream"; break; case AVERROR_HTTP_SERVER_ERROR: case 500: reply_code = 500; reply_text = "Internal server error"; break; default: return AVERROR(EINVAL); } if (body) { s->chunked_post = 0; message_len = snprintf(message, sizeof(message), "HTTP/1.1 %03d %s\r\n" "Content-Type: %s\r\n" "Content-Length: %"SIZE_SPECIFIER"\r\n" "%s" "\r\n" "%03d %s\r\n", reply_code, reply_text, content_type, strlen(reply_text) + 6, // 3 digit status code + space + \r\n s->headers ? s->headers : "", reply_code, reply_text); } else { s->chunked_post = 1; message_len = snprintf(message, sizeof(message), "HTTP/1.1 %03d %s\r\n" "Content-Type: %s\r\n" "Transfer-Encoding: chunked\r\n" "%s" "\r\n", reply_code, reply_text, content_type, s->headers ? s->headers : ""); } av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message); if ((ret = ffurl_write(s->hd, message, message_len)) < 0) return ret; return 0; } static void handle_http_errors(URLContext *h, int error) { av_assert0(error < 0); http_write_reply(h, error); } static int http_handshake(URLContext *c) { int ret, err, new_location; HTTPContext *ch = c->priv_data; URLContext *cl = ch->hd; switch (ch->handshake_step) { case LOWER_PROTO: av_log(c, AV_LOG_TRACE, "Lower protocol\n"); if ((ret = ffurl_handshake(cl)) > 0) return 2 + ret; if (ret < 0) return ret; ch->handshake_step = READ_HEADERS; ch->is_connected_server = 1; return 2; case READ_HEADERS: av_log(c, AV_LOG_TRACE, "Read headers\n"); if ((err = http_read_header(c, &new_location)) < 0) { handle_http_errors(c, err); return err; } ch->handshake_step = WRITE_REPLY_HEADERS; return 1; case WRITE_REPLY_HEADERS: av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code); if ((err = http_write_reply(c, ch->reply_code)) < 0) return err; ch->handshake_step = FINISH; return 1; case FINISH: return 0; } // this should never be reached. return AVERROR(EINVAL); } static int http_listen(URLContext *h, const char *uri, int flags, AVDictionary **options) { HTTPContext *s = h->priv_data; int ret; char hostname[1024], proto[10]; char lower_url[100]; const char *lower_proto = "tcp"; int port; av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri); if (!strcmp(proto, "https")) lower_proto = "tls"; ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port, NULL); if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0) goto fail; if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE, &h->interrupt_callback, options, h->protocol_whitelist, h->protocol_blacklist, h )) < 0) goto fail; s->handshake_step = LOWER_PROTO; if (s->listen == HTTP_SINGLE) { /* single client */ s->reply_code = 200; while ((ret = http_handshake(h)) > 0); } fail: av_dict_free(&s->chained_options); return ret; } static int http_open(URLContext *h, const char *uri, int flags, AVDictionary **options) { HTTPContext *s = h->priv_data; int ret; if( s->seekable == 1 ) h->is_streamed = 0; else h->is_streamed = 1; s->filesize = UINT64_MAX; s->location = av_strdup(uri); if (!s->location) return AVERROR(ENOMEM); if (options) av_dict_copy(&s->chained_options, *options, 0); if (s->headers) { int len = strlen(s->headers); if (len < 2 || strcmp("\r\n", s->headers + len - 2)) { av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n"); ret = av_reallocp(&s->headers, len + 3); if (ret < 0) return ret; s->headers[len] = '\r'; s->headers[len + 1] = '\n'; s->headers[len + 2] = '\0'; } } if (s->listen) { return http_listen(h, uri, flags, options); } ret = http_open_cnx(h, options); if (ret < 0) av_dict_free(&s->chained_options); return ret; } static int http_accept(URLContext *s, URLContext **c) { int ret; HTTPContext *sc = s->priv_data; HTTPContext *cc; URLContext *sl = sc->hd; URLContext *cl = NULL; av_assert0(sc->listen); if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0) goto fail; cc = (*c)->priv_data; if ((ret = ffurl_accept(sl, &cl)) < 0) goto fail; cc->hd = cl; cc->is_multi_client = 1; fail: return ret; } static int http_getc(HTTPContext *s) { int len; if (s->buf_ptr >= s->buf_end) { len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE); if (len < 0) { return len; } else if (len == 0) { return AVERROR_EOF; } else { s->buf_ptr = s->buffer; s->buf_end = s->buffer + len; } } return *s->buf_ptr++; } static int http_get_line(HTTPContext *s, char *line, int line_size) { int ch; char *q; q = line; for (;;) { ch = http_getc(s); if (ch < 0) return ch; if (ch == '\n') { /* process line */ if (q > line && q[-1] == '\r') q--; *q = '\0'; return 0; } else { if ((q - line) < line_size - 1) *q++ = ch; } } } static int check_http_code(URLContext *h, int http_code, const char *end) { HTTPContext *s = h->priv_data; /* error codes are 4xx and 5xx, but regard 401 as a success, so we * don't abort until all headers have been parsed. */ if (http_code >= 400 && http_code < 600 && (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) && (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) { end += strspn(end, SPACE_CHARS); av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end); return ff_http_averror(http_code, AVERROR(EIO)); } return 0; } static int parse_location(HTTPContext *s, const char *p) { char redirected_location[MAX_URL_SIZE], *new_loc; ff_make_absolute_url(redirected_location, sizeof(redirected_location), s->location, p); new_loc = av_strdup(redirected_location); if (!new_loc) return AVERROR(ENOMEM); av_free(s->location); s->location = new_loc; return 0; } /* "bytes $from-$to/$document_size" */ static void parse_content_range(URLContext *h, const char *p) { HTTPContext *s = h->priv_data; const char *slash; if (!strncmp(p, "bytes ", 6)) { p += 6; s->off = strtoull(p, NULL, 10); if ((slash = strchr(p, '/')) && strlen(slash) > 0) s->filesize = strtoull(slash + 1, NULL, 10); } if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647)) h->is_streamed = 0; /* we _can_ in fact seek */ } static int parse_content_encoding(URLContext *h, const char *p) { if (!av_strncasecmp(p, "gzip", 4) || !av_strncasecmp(p, "deflate", 7)) { #if CONFIG_ZLIB HTTPContext *s = h->priv_data; s->compressed = 1; inflateEnd(&s->inflate_stream); if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) { av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n", s->inflate_stream.msg); return AVERROR(ENOSYS); } if (zlibCompileFlags() & (1 << 17)) { av_log(h, AV_LOG_WARNING, "Your zlib was compiled without gzip support.\n"); return AVERROR(ENOSYS); } #else av_log(h, AV_LOG_WARNING, "Compressed (%s) content, need zlib with gzip support\n", p); return AVERROR(ENOSYS); #endif /* CONFIG_ZLIB */ } else if (!av_strncasecmp(p, "identity", 8)) { // The normal, no-encoding case (although servers shouldn't include // the header at all if this is the case). } else { av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p); } return 0; } // Concat all Icy- header lines static int parse_icy(HTTPContext *s, const char *tag, const char *p) { int len = 4 + strlen(p) + strlen(tag); int is_first = !s->icy_metadata_headers; int ret; av_dict_set(&s->metadata, tag, p, 0); if (s->icy_metadata_headers) len += strlen(s->icy_metadata_headers); if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0) return ret; if (is_first) *s->icy_metadata_headers = '\0'; av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p); return 0; } static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies) { char *eql, *name; // duplicate the cookie name (dict will dupe the value) if (!(eql = strchr(p, '='))) return AVERROR(EINVAL); if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM); // add the cookie to the dictionary av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY); return 0; } static int cookie_string(AVDictionary *dict, char **cookies) { AVDictionaryEntry *e = NULL; int len = 1; // determine how much memory is needed for the cookies string while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX)) len += strlen(e->key) + strlen(e->value) + 1; // reallocate the cookies e = NULL; if (*cookies) av_free(*cookies); *cookies = av_malloc(len); if (!*cookies) return AVERROR(ENOMEM); *cookies[0] = '\0'; // write out the cookies while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX)) av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value); return 0; } static int process_line(URLContext *h, char *line, int line_count, int *new_location) { HTTPContext *s = h->priv_data; const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET"; char *tag, *p, *end, *method, *resource, *version; int ret; /* end of header */ if (line[0] == '\0') { s->end_header = 1; return 0; } p = line; if (line_count == 0) { if (s->is_connected_server) { // HTTP method method = p; while (*p && !av_isspace(*p)) p++; *(p++) = '\0'; av_log(h, AV_LOG_TRACE, "Received method: %s\n", method); if (s->method) { if (av_strcasecmp(s->method, method)) { av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n", s->method, method); return ff_http_averror(400, AVERROR(EIO)); } } else { // use autodetected HTTP method to expect av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method); if (av_strcasecmp(auto_method, method)) { av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match " "(%s autodetected %s received)\n", auto_method, method); return ff_http_averror(400, AVERROR(EIO)); } if (!(s->method = av_strdup(method))) return AVERROR(ENOMEM); } // HTTP resource while (av_isspace(*p)) p++; resource = p; while (!av_isspace(*p)) p++; *(p++) = '\0'; av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource); if (!(s->resource = av_strdup(resource))) return AVERROR(ENOMEM); // HTTP version while (av_isspace(*p)) p++; version = p; while (*p && !av_isspace(*p)) p++; *p = '\0'; if (av_strncasecmp(version, "HTTP/", 5)) { av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n"); return ff_http_averror(400, AVERROR(EIO)); } av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version); } else { while (!av_isspace(*p) && *p != '\0') p++; while (av_isspace(*p)) p++; s->http_code = strtol(p, &end, 10); av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code); if ((ret = check_http_code(h, s->http_code, end)) < 0) return ret; } } else { while (*p != '\0' && *p != ':') p++; if (*p != ':') return 1; *p = '\0'; tag = line; p++; while (av_isspace(*p)) p++; if (!av_strcasecmp(tag, "Location")) { if ((ret = parse_location(s, p)) < 0) return ret; *new_location = 1; } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == UINT64_MAX) { s->filesize = strtoull(p, NULL, 10); } else if (!av_strcasecmp(tag, "Content-Range")) { parse_content_range(h, p); } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) { h->is_streamed = 0; } else if (!av_strcasecmp(tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) { s->filesize = UINT64_MAX; s->chunksize = 0; } else if (!av_strcasecmp(tag, "WWW-Authenticate")) { ff_http_auth_handle_header(&s->auth_state, tag, p); } else if (!av_strcasecmp(tag, "Authentication-Info")) { ff_http_auth_handle_header(&s->auth_state, tag, p); } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) { ff_http_auth_handle_header(&s->proxy_auth_state, tag, p); } else if (!av_strcasecmp(tag, "Connection")) { if (!strcmp(p, "close")) s->willclose = 1; } else if (!av_strcasecmp(tag, "Server")) { if (!av_strcasecmp(p, "AkamaiGHost")) { s->is_akamai = 1; } else if (!av_strncasecmp(p, "MediaGateway", 12)) { s->is_mediagateway = 1; } } else if (!av_strcasecmp(tag, "Content-Type")) { av_free(s->mime_type); s->mime_type = av_strdup(p); } else if (!av_strcasecmp(tag, "Set-Cookie")) { if (parse_cookie(s, p, &s->cookie_dict)) av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p); } else if (!av_strcasecmp(tag, "Icy-MetaInt")) { s->icy_metaint = strtoull(p, NULL, 10); } else if (!av_strncasecmp(tag, "Icy-", 4)) { if ((ret = parse_icy(s, tag, p)) < 0) return ret; } else if (!av_strcasecmp(tag, "Content-Encoding")) { if ((ret = parse_content_encoding(h, p)) < 0) return ret; } } return 1; } /** * Create a string containing cookie values for use as a HTTP cookie header * field value for a particular path and domain from the cookie values stored in * the HTTP protocol context. The cookie string is stored in *cookies. * * @return a negative value if an error condition occurred, 0 otherwise */ static int get_cookies(HTTPContext *s, char **cookies, const char *path, const char *domain) { // cookie strings will look like Set-Cookie header field values. Multiple // Set-Cookie fields will result in multiple values delimited by a newline int ret = 0; char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies; if (!set_cookies) return AVERROR(EINVAL); // destroy any cookies in the dictionary. av_dict_free(&s->cookie_dict); *cookies = NULL; while ((cookie = av_strtok(set_cookies, "\n", &next))) { int domain_offset = 0; char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL; set_cookies = NULL; // store the cookie in a dict in case it is updated in the response if (parse_cookie(s, cookie, &s->cookie_dict)) av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie); while ((param = av_strtok(cookie, "; ", &next_param))) { if (cookie) { // first key-value pair is the actual cookie value cvalue = av_strdup(param); cookie = NULL; } else if (!av_strncasecmp("path=", param, 5)) { av_free(cpath); cpath = av_strdup(&param[5]); } else if (!av_strncasecmp("domain=", param, 7)) { // if the cookie specifies a sub-domain, skip the leading dot thereby // supporting URLs that point to sub-domains and the master domain int leading_dot = (param[7] == '.'); av_free(cdomain); cdomain = av_strdup(&param[7+leading_dot]); } else { // ignore unknown attributes } } if (!cdomain) cdomain = av_strdup(domain); // ensure all of the necessary values are valid if (!cdomain || !cpath || !cvalue) { av_log(s, AV_LOG_WARNING, "Invalid cookie found, no value, path or domain specified\n"); goto done_cookie; } // check if the request path matches the cookie path if (av_strncasecmp(path, cpath, strlen(cpath))) goto done_cookie; // the domain should be at least the size of our cookie domain domain_offset = strlen(domain) - strlen(cdomain); if (domain_offset < 0) goto done_cookie; // match the cookie domain if (av_strcasecmp(&domain[domain_offset], cdomain)) goto done_cookie; // cookie parameters match, so copy the value if (!*cookies) { if (!(*cookies = av_strdup(cvalue))) { ret = AVERROR(ENOMEM); goto done_cookie; } } else { char *tmp = *cookies; size_t str_size = strlen(cvalue) + strlen(*cookies) + 3; if (!(*cookies = av_malloc(str_size))) { ret = AVERROR(ENOMEM); goto done_cookie; } snprintf(*cookies, str_size, "%s; %s", tmp, cvalue); av_free(tmp); } done_cookie: av_freep(&cdomain); av_freep(&cpath); av_freep(&cvalue); if (ret < 0) { if (*cookies) av_freep(cookies); av_free(cset_cookies); return ret; } } av_free(cset_cookies); return 0; } static inline int has_header(const char *str, const char *header) { /* header + 2 to skip over CRLF prefix. (make sure you have one!) */ if (!str) return 0; return av_stristart(str, header + 2, NULL) || av_stristr(str, header); } static int http_read_header(URLContext *h, int *new_location) { HTTPContext *s = h->priv_data; char line[MAX_URL_SIZE]; int err = 0; s->chunksize = UINT64_MAX; for (;;) { if ((err = http_get_line(s, line, sizeof(line))) < 0) return err; av_log(h, AV_LOG_TRACE, "header='%s'\n", line); err = process_line(h, line, s->line_count, new_location); if (err < 0) return err; if (err == 0) break; s->line_count++; } if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000) h->is_streamed = 1; /* we can in fact _not_ seek */ // add any new cookies into the existing cookie string cookie_string(s->cookie_dict, &s->cookies); av_dict_free(&s->cookie_dict); return err; } static int http_connect(URLContext *h, const char *path, const char *local_path, const char *hoststr, const char *auth, const char *proxyauth, int *new_location) { HTTPContext *s = h->priv_data; int post, err; char headers[HTTP_HEADERS_SIZE] = ""; char *authstr = NULL, *proxyauthstr = NULL; uint64_t off = s->off; int len = 0; const char *method; int send_expect_100 = 0; /* send http header */ post = h->flags & AVIO_FLAG_WRITE; if (s->post_data) { /* force POST method and disable chunked encoding when * custom HTTP post data is set */ post = 1; s->chunked_post = 0; } if (s->method) method = s->method; else method = post ? "POST" : "GET"; authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path, method); proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth, local_path, method); if (post && !s->post_data) { send_expect_100 = s->send_expect_100; /* The user has supplied authentication but we don't know the auth type, * send Expect: 100-continue to get the 401 response including the * WWW-Authenticate header, or an 100 continue if no auth actually * is needed. */ if (auth && *auth && s->auth_state.auth_type == HTTP_AUTH_NONE && s->http_code != 401) send_expect_100 = 1; } #if FF_API_HTTP_USER_AGENT if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) { av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n"); s->user_agent = av_strdup(s->user_agent_deprecated); } #endif /* set default headers if needed */ if (!has_header(s->headers, "\r\nUser-Agent: ")) len += av_strlcatf(headers + len, sizeof(headers) - len, "User-Agent: %s\r\n", s->user_agent); if (!has_header(s->headers, "\r\nAccept: ")) len += av_strlcpy(headers + len, "Accept: */*\r\n", sizeof(headers) - len); // Note: we send this on purpose even when s->off is 0 when we're probing, // since it allows us to detect more reliably if a (non-conforming) // server supports seeking by analysing the reply headers. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) { len += av_strlcatf(headers + len, sizeof(headers) - len, "Range: bytes=%"PRIu64"-", s->off); if (s->end_off) len += av_strlcatf(headers + len, sizeof(headers) - len, "%"PRId64, s->end_off - 1); len += av_strlcpy(headers + len, "\r\n", sizeof(headers) - len); } if (send_expect_100 && !has_header(s->headers, "\r\nExpect: ")) len += av_strlcatf(headers + len, sizeof(headers) - len, "Expect: 100-continue\r\n"); if (!has_header(s->headers, "\r\nConnection: ")) { if (s->multiple_requests) len += av_strlcpy(headers + len, "Connection: keep-alive\r\n", sizeof(headers) - len); else len += av_strlcpy(headers + len, "Connection: close\r\n", sizeof(headers) - len); } if (!has_header(s->headers, "\r\nHost: ")) len += av_strlcatf(headers + len, sizeof(headers) - len, "Host: %s\r\n", hoststr); if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data) len += av_strlcatf(headers + len, sizeof(headers) - len, "Content-Length: %d\r\n", s->post_datalen); if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type) len += av_strlcatf(headers + len, sizeof(headers) - len, "Content-Type: %s\r\n", s->content_type); if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) { char *cookies = NULL; if (!get_cookies(s, &cookies, path, hoststr) && cookies) { len += av_strlcatf(headers + len, sizeof(headers) - len, "Cookie: %s\r\n", cookies); av_free(cookies); } } if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) len += av_strlcatf(headers + len, sizeof(headers) - len, "Icy-MetaData: %d\r\n", 1); /* now add in custom headers */ if (s->headers) av_strlcpy(headers + len, s->headers, sizeof(headers) - len); snprintf(s->buffer, sizeof(s->buffer), "%s %s HTTP/1.1\r\n" "%s" "%s" "%s" "%s%s" "\r\n", method, path, post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "", headers, authstr ? authstr : "", proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : ""); av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer); if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0) goto done; if (s->post_data) if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0) goto done; /* init input buffer */ s->buf_ptr = s->buffer; s->buf_end = s->buffer; s->line_count = 0; s->off = 0; s->icy_data_read = 0; s->filesize = UINT64_MAX; s->willclose = 0; s->end_chunked_post = 0; s->end_header = 0; if (post && !s->post_data && !send_expect_100) { /* Pretend that it did work. We didn't read any header yet, since * we've still to send the POST data, but the code calling this * function will check http_code after we return. */ s->http_code = 200; err = 0; goto done; } /* wait for header */ err = http_read_header(h, new_location); if (err < 0) goto done; if (*new_location) s->off = off; err = (off == s->off) ? 0 : -1; done: av_freep(&authstr); av_freep(&proxyauthstr); return err; } static int http_buf_read(URLContext *h, uint8_t *buf, int size) { HTTPContext *s = h->priv_data; int len; /* read bytes from input buffer first */ len = s->buf_end - s->buf_ptr; if (len > 0) { if (len > size) len = size; memcpy(buf, s->buf_ptr, len); s->buf_ptr += len; } else { uint64_t target_end = s->end_off ? s->end_off : s->filesize; if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end) return AVERROR_EOF; len = ffurl_read(s->hd, buf, size); if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) { av_log(h, AV_LOG_ERROR, "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n", s->off, target_end ); return AVERROR(EIO); } } if (len > 0) { s->off += len; if (s->chunksize > 0) s->chunksize -= len; } return len; } #if CONFIG_ZLIB #define DECOMPRESS_BUF_SIZE (256 * 1024) static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size) { HTTPContext *s = h->priv_data; int ret; if (!s->inflate_buffer) { s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE); if (!s->inflate_buffer) return AVERROR(ENOMEM); } if (s->inflate_stream.avail_in == 0) { int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE); if (read <= 0) return read; s->inflate_stream.next_in = s->inflate_buffer; s->inflate_stream.avail_in = read; } s->inflate_stream.avail_out = size; s->inflate_stream.next_out = buf; ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg); return size - s->inflate_stream.avail_out; } #endif /* CONFIG_ZLIB */ static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect); static int http_read_stream(URLContext *h, uint8_t *buf, int size) { HTTPContext *s = h->priv_data; int err, new_location, read_ret; int64_t seek_ret; if (!s->hd) return AVERROR_EOF; if (s->end_chunked_post && !s->end_header) { err = http_read_header(h, &new_location); if (err < 0) return err; } if (s->chunksize != UINT64_MAX) { if (!s->chunksize) { char line[32]; do { if ((err = http_get_line(s, line, sizeof(line))) < 0) return err; } while (!*line); /* skip CR LF from last chunk */ s->chunksize = strtoull(line, NULL, 16); av_log(h, AV_LOG_TRACE, "Chunked encoding data size: %"PRIu64"'\n", s->chunksize); if (!s->chunksize) return 0; else if (s->chunksize == UINT64_MAX) { av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n", s->chunksize); return AVERROR(EINVAL); } } size = FFMIN(size, s->chunksize); } #if CONFIG_ZLIB if (s->compressed) return http_buf_read_compressed(h, buf, size); #endif /* CONFIG_ZLIB */ read_ret = http_buf_read(h, buf, size); if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize) || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) { uint64_t target = h->is_streamed ? 0 : s->off; if (s->reconnect_delay > s->reconnect_delay_max) return AVERROR(EIO); av_log(h, AV_LOG_INFO, "Will reconnect at %"PRIu64" error=%s.\n", s->off, av_err2str(read_ret)); av_usleep(1000U*1000*s->reconnect_delay); s->reconnect_delay = 1 + 2*s->reconnect_delay; seek_ret = http_seek_internal(h, target, SEEK_SET, 1); if (seek_ret != target) { av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target); return read_ret; } read_ret = http_buf_read(h, buf, size); } else s->reconnect_delay = 0; return read_ret; } // Like http_read_stream(), but no short reads. // Assumes partial reads are an error. static int http_read_stream_all(URLContext *h, uint8_t *buf, int size) { int pos = 0; while (pos < size) { int len = http_read_stream(h, buf + pos, size - pos); if (len < 0) return len; pos += len; } return pos; } static void update_metadata(HTTPContext *s, char *data) { char *key; char *val; char *end; char *next = data; while (*next) { key = next; val = strstr(key, "='"); if (!val) break; end = strstr(val, "';"); if (!end) break; *val = '\0'; *end = '\0'; val += 2; av_dict_set(&s->metadata, key, val, 0); next = end + 2; } } static int store_icy(URLContext *h, int size) { HTTPContext *s = h->priv_data; /* until next metadata packet */ uint64_t remaining; if (s->icy_metaint < s->icy_data_read) return AVERROR_INVALIDDATA; remaining = s->icy_metaint - s->icy_data_read; if (!remaining) { /* The metadata packet is variable sized. It has a 1 byte header * which sets the length of the packet (divided by 16). If it's 0, * the metadata doesn't change. After the packet, icy_metaint bytes * of normal data follows. */ uint8_t ch; int len = http_read_stream_all(h, &ch, 1); if (len < 0) return len; if (ch > 0) { char data[255 * 16 + 1]; int ret; len = ch * 16; ret = http_read_stream_all(h, data, len); if (ret < 0) return ret; data[len + 1] = 0; if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0) return ret; update_metadata(s, data); } s->icy_data_read = 0; remaining = s->icy_metaint; } return FFMIN(size, remaining); } static int http_read(URLContext *h, uint8_t *buf, int size) { HTTPContext *s = h->priv_data; if (s->icy_metaint > 0) { size = store_icy(h, size); if (size < 0) return size; } size = http_read_stream(h, buf, size); if (size > 0) s->icy_data_read += size; return size; } /* used only when posting data */ static int http_write(URLContext *h, const uint8_t *buf, int size) { char temp[11] = ""; /* 32-bit hex + CRLF + nul */ int ret; char crlf[] = "\r\n"; HTTPContext *s = h->priv_data; if (!s->chunked_post) { /* non-chunked data is sent without any special encoding */ return ffurl_write(s->hd, buf, size); } /* silently ignore zero-size data since chunk encoding that would * signal EOF */ if (size > 0) { /* upload data using chunked encoding */ snprintf(temp, sizeof(temp), "%x\r\n", size); if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 || (ret = ffurl_write(s->hd, buf, size)) < 0 || (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0) return ret; } return size; } static int http_shutdown(URLContext *h, int flags) { int ret = 0; char footer[] = "0\r\n\r\n"; HTTPContext *s = h->priv_data; /* signal end of chunked encoding if used */ if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) || ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) { ret = ffurl_write(s->hd, footer, sizeof(footer) - 1); ret = ret > 0 ? 0 : ret; s->end_chunked_post = 1; } return ret; } static int http_close(URLContext *h) { int ret = 0; HTTPContext *s = h->priv_data; #if CONFIG_ZLIB inflateEnd(&s->inflate_stream); av_freep(&s->inflate_buffer); #endif /* CONFIG_ZLIB */ if (!s->end_chunked_post) /* Close the write direction by sending the end of chunked encoding. */ ret = http_shutdown(h, h->flags); if (s->hd) ffurl_closep(&s->hd); av_dict_free(&s->chained_options); return ret; } static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect) { HTTPContext *s = h->priv_data; URLContext *old_hd = s->hd; uint64_t old_off = s->off; uint8_t old_buf[BUFFER_SIZE]; int old_buf_size, ret; AVDictionary *options = NULL; if (whence == AVSEEK_SIZE) return s->filesize; else if (!force_reconnect && ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))) return s->off; else if ((s->filesize == UINT64_MAX && whence == SEEK_END)) return AVERROR(ENOSYS); if (whence == SEEK_CUR) off += s->off; else if (whence == SEEK_END) off += s->filesize; else if (whence != SEEK_SET) return AVERROR(EINVAL); if (off < 0) return AVERROR(EINVAL); s->off = off; if (s->off && h->is_streamed) return AVERROR(ENOSYS); /* we save the old context in case the seek fails */ old_buf_size = s->buf_end - s->buf_ptr; memcpy(old_buf, s->buf_ptr, old_buf_size); s->hd = NULL; /* if it fails, continue on old connection */ if ((ret = http_open_cnx(h, &options)) < 0) { av_dict_free(&options); memcpy(s->buffer, old_buf, old_buf_size); s->buf_ptr = s->buffer; s->buf_end = s->buffer + old_buf_size; s->hd = old_hd; s->off = old_off; return ret; } av_dict_free(&options); ffurl_close(old_hd); return off; } static int64_t http_seek(URLContext *h, int64_t off, int whence) { return http_seek_internal(h, off, whence, 0); } static int http_get_file_handle(URLContext *h) { HTTPContext *s = h->priv_data; return ffurl_get_file_handle(s->hd); } #define HTTP_CLASS(flavor) \ static const AVClass flavor ## _context_class = { \ .class_name = # flavor, \ .item_name = av_default_item_name, \ .option = options, \ .version = LIBAVUTIL_VERSION_INT, \ } #if CONFIG_HTTP_PROTOCOL HTTP_CLASS(http); const URLProtocol ff_http_protocol = { .name = "http", .url_open2 = http_open, .url_accept = http_accept, .url_handshake = http_handshake, .url_read = http_read, .url_write = http_write, .url_seek = http_seek, .url_close = http_close, .url_get_file_handle = http_get_file_handle, .url_shutdown = http_shutdown, .priv_data_size = sizeof(HTTPContext), .priv_data_class = &http_context_class, .flags = URL_PROTOCOL_FLAG_NETWORK, .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy" }; #endif /* CONFIG_HTTP_PROTOCOL */ #if CONFIG_HTTPS_PROTOCOL HTTP_CLASS(https); const URLProtocol ff_https_protocol = { .name = "https", .url_open2 = http_open, .url_read = http_read, .url_write = http_write, .url_seek = http_seek, .url_close = http_close, .url_get_file_handle = http_get_file_handle, .url_shutdown = http_shutdown, .priv_data_size = sizeof(HTTPContext), .priv_data_class = &https_context_class, .flags = URL_PROTOCOL_FLAG_NETWORK, .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy" }; #endif /* CONFIG_HTTPS_PROTOCOL */ #if CONFIG_HTTPPROXY_PROTOCOL static int http_proxy_close(URLContext *h) { HTTPContext *s = h->priv_data; if (s->hd) ffurl_closep(&s->hd); return 0; } static int http_proxy_open(URLContext *h, const char *uri, int flags) { HTTPContext *s = h->priv_data; char hostname[1024], hoststr[1024]; char auth[1024], pathbuf[1024], *path; char lower_url[100]; int port, ret = 0, attempts = 0; HTTPAuthType cur_auth_type; char *authstr; int new_loc; if( s->seekable == 1 ) h->is_streamed = 0; else h->is_streamed = 1; av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port, pathbuf, sizeof(pathbuf), uri); ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL); path = pathbuf; if (*path == '/') path++; ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port, NULL); redo: ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE, &h->interrupt_callback, NULL, h->protocol_whitelist, h->protocol_blacklist, h); if (ret < 0) return ret; authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth, path, "CONNECT"); snprintf(s->buffer, sizeof(s->buffer), "CONNECT %s HTTP/1.1\r\n" "Host: %s\r\n" "Connection: close\r\n" "%s%s" "\r\n", path, hoststr, authstr ? "Proxy-" : "", authstr ? authstr : ""); av_freep(&authstr); if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0) goto fail; s->buf_ptr = s->buffer; s->buf_end = s->buffer; s->line_count = 0; s->filesize = UINT64_MAX; cur_auth_type = s->proxy_auth_state.auth_type; /* Note: This uses buffering, potentially reading more than the * HTTP header. If tunneling a protocol where the server starts * the conversation, we might buffer part of that here, too. * Reading that requires using the proper ffurl_read() function * on this URLContext, not using the fd directly (as the tls * protocol does). This shouldn't be an issue for tls though, * since the client starts the conversation there, so there * is no extra data that we might buffer up here. */ ret = http_read_header(h, &new_loc); if (ret < 0) goto fail; attempts++; if (s->http_code == 407 && (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) && s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) { ffurl_closep(&s->hd); goto redo; } if (s->http_code < 400) return 0; ret = ff_http_averror(s->http_code, AVERROR(EIO)); fail: http_proxy_close(h); return ret; } static int http_proxy_write(URLContext *h, const uint8_t *buf, int size) { HTTPContext *s = h->priv_data; return ffurl_write(s->hd, buf, size); } const URLProtocol ff_httpproxy_protocol = { .name = "httpproxy", .url_open = http_proxy_open, .url_read = http_buf_read, .url_write = http_proxy_write, .url_close = http_proxy_close, .url_get_file_handle = http_get_file_handle, .priv_data_size = sizeof(HTTPContext), .flags = URL_PROTOCOL_FLAG_NETWORK, }; #endif /* CONFIG_HTTPPROXY_PROTOCOL */
./CrossVul/dataset_final_sorted/CWE-119/c/good_4835_0
crossvul-cpp_data_good_4788_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L AAA BBBB EEEEE L % % L A A B B E L % % L AAAAA BBBB EEE L % % L A A B B E L % % LLLLL A A BBBB EEEEE LLLLL % % % % % % Read ASCII String As An Image. % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/annotate.h" #include "magick/artifact.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/draw.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/pixel-accessor.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/utility.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d L A B E L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadLABELImage() reads a LABEL image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadLABELImage method is: % % Image *ReadLABELImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadLABELImage(const ImageInfo *image_info, ExceptionInfo *exception) { char geometry[MaxTextExtent], *property; const char *label; DrawInfo *draw_info; Image *image; MagickBooleanType status; TypeMetric metrics; size_t height, width; /* Initialize Image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); (void) ResetImagePage(image,"0x0+0+0"); property=InterpretImageProperties(image_info,image,image_info->filename); (void) SetImageProperty(image,"label",property); property=DestroyString(property); label=GetImageProperty(image,"label"); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->text=ConstantString(label); metrics.width=0; metrics.ascent=0.0; status=GetMultilineTypeMetrics(image,draw_info,&metrics); if ((image->columns == 0) && (image->rows == 0)) { image->columns=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); image->rows=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); } else if (((image->columns == 0) || (image->rows == 0)) || (fabs(image_info->pointsize) < MagickEpsilon)) { double high, low; /* Auto fit text into bounding box. */ for ( ; ; draw_info->pointsize*=2.0) { (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); (void) GetMultilineTypeMetrics(image,draw_info,&metrics); width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width >= image->columns) && (height >= image->rows)) break; } else if (((image->columns != 0) && (width >= image->columns)) || ((image->rows != 0) && (height >= image->rows))) break; } high=draw_info->pointsize; for (low=1.0; (high-low) > 0.5; ) { draw_info->pointsize=(low+high)/2.0; (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); (void) GetMultilineTypeMetrics(image,draw_info,&metrics); width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width < image->columns) && (height < image->rows)) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } else if (((image->columns != 0) && (width < image->columns)) || ((image->rows != 0) && (height < image->rows))) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } draw_info->pointsize=(low+high)/2.0-0.5; } status=GetMultilineTypeMetrics(image,draw_info,&metrics); if (status == MagickFalse) { draw_info=DestroyDrawInfo(draw_info); InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (image->columns == 0) image->columns=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); if (image->columns == 0) image->columns=(size_t) floor(draw_info->pointsize+draw_info->stroke_width+ 0.5); if (image->rows == 0) image->rows=(size_t) floor(metrics.ascent-metrics.descent+ draw_info->stroke_width+0.5); if (image->rows == 0) image->rows=(size_t) floor(draw_info->pointsize+draw_info->stroke_width+ 0.5); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { draw_info=DestroyDrawInfo(draw_info); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { draw_info=DestroyDrawInfo(draw_info); InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } /* Draw label. */ (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", draw_info->direction == RightToLeftDirection ? image->columns- metrics.bounds.x2 : 0.0,draw_info->gravity == UndefinedGravity ? metrics.ascent : 0.0); draw_info->geometry=AcquireString(geometry); status=AnnotateImage(image,draw_info); if (image_info->pointsize == 0.0) { char pointsize[MaxTextExtent]; (void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g", draw_info->pointsize); (void) SetImageProperty(image,"label:pointsize",pointsize); } draw_info=DestroyDrawInfo(draw_info); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r L A B E L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterLABELImage() adds properties for the LABEL image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterLABELImage method is: % % size_t RegisterLABELImage(void) % */ ModuleExport size_t RegisterLABELImage(void) { MagickInfo *entry; entry=SetMagickInfo("LABEL"); entry->decoder=(DecodeImageHandler *) ReadLABELImage; entry->adjoin=MagickFalse; entry->format_type=ImplicitFormatType; entry->description=ConstantString("Image label"); entry->module=ConstantString("LABEL"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r L A B E L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterLABELImage() removes format registrations made by the % LABEL module from the list of supported formats. % % The format of the UnregisterLABELImage method is: % % UnregisterLABELImage(void) % */ ModuleExport void UnregisterLABELImage(void) { (void) UnregisterMagickInfo("LABEL"); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_4788_0
crossvul-cpp_data_good_342_1
/* * Support for ePass2003 smart cards * * Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com> * Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #ifdef ENABLE_SM /* empty file without SM enabled */ #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table epass2003_atrs[] = { /* This is a FIPS certified card using SCP01 security messaging. */ {"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e", "FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00", "FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL }, {NULL, NULL, NULL, 0, 0, NULL} }; static struct sc_card_operations *iso_ops = NULL; static struct sc_card_operations epass2003_ops; static struct sc_card_driver epass2003_drv = { "epass2003", "epass2003", &epass2003_ops, NULL, 0, NULL }; #define KEY_TYPE_AES 0x01 /* FIPS mode */ #define KEY_TYPE_DES 0x02 /* Non-FIPS mode */ #define KEY_LEN_AES 16 #define KEY_LEN_DES 8 #define KEY_LEN_DES3 24 #define HASH_LEN 24 static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID }; /*0x00:plain; 0x01:scp01 sm*/ #define SM_PLAIN 0x00 #define SM_SCP01 0x01 static unsigned char g_init_key_enc[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_init_key_mac[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_random[8] = { 0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40 }; typedef struct epass2003_exdata_st { unsigned char sm; /* SM_PLAIN or SM_SCP01 */ unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */ unsigned char sk_enc[16]; /* encrypt session key */ unsigned char sk_mac[16]; /* mac session key */ unsigned char icv_mac[16]; /* instruction counter vector(for sm) */ unsigned char currAlg; /* current Alg */ unsigned int ecAlgFlags; /* Ec Alg mechanism type*/ } epass2003_exdata; #define REVERSE_ORDER4(x) ( \ ((unsigned long)x & 0xFF000000)>> 24 | \ ((unsigned long)x & 0x00FF0000)>> 8 | \ ((unsigned long)x & 0x0000FF00)<< 8 | \ ((unsigned long)x & 0x000000FF)<< 24) static const struct sc_card_error epass2003_errors[] = { { 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" }, { 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" }, { 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" }, { 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" }, { 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" }, { 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"}, { 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"}, { 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" }, { 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" }, { 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" }, { 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" }, { 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" }, { 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" }, { 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" }, { 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" }, { 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" }, { 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" }, { 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" }, { 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" }, { 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" }, { 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" }, { 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" }, { 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" }, { 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" }, { 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" }, { 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" }, { 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" }, { 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" }, { 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" }, { 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" }, { 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" }, { 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"}, { 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"}, { 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" }, { 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" }, { 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" }, { 0x9000,SC_SUCCESS, NULL } }; static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu); static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out); int epass2003_refresh(struct sc_card *card); static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType); static int epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]); int i; /* Handle special cases here */ if (sw1 == 0x6C) { sc_log(card->ctx, "Wrong length; correct length is %d", sw2); return SC_ERROR_WRONG_LENGTH; } for (i = 0; i < err_count; i++) { if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) { sc_log(card->ctx, "%s", epass2003_errors[i].errorstr); return epass2003_errors[i].errorno; } } sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2); return SC_ERROR_CARD_CMD_FAILED; } static int sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu) { int r = sc_transmit_apdu(card, apdu); if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2))) { epass2003_refresh(card); r = sc_transmit_apdu(card, apdu); } return r; } static int openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_EncryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_DecryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int aes128_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, size_t length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output); } static int aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output); } static int aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output); } static int des3_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, int length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output); } static int des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_des_cbc(), key, iv, input, length, output); } static int des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_des_cbc(), key, iv, input, length, output); } static int openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length, unsigned char *output) { int r = 0; EVP_MD_CTX *ctx = NULL; unsigned outl = 0; ctx = EVP_MD_CTX_create(); if (ctx == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } EVP_MD_CTX_init(ctx); EVP_DigestInit_ex(ctx, digest, NULL); if (!EVP_DigestUpdate(ctx, input, length)) { r = SC_ERROR_INTERNAL; goto err; } if (!EVP_DigestFinal_ex(ctx, output, &outl)) { r = SC_ERROR_INTERNAL; goto err; } r = SC_SUCCESS; err: if (ctx) EVP_MD_CTX_destroy(ctx); return r; } static int sha1_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha1(), input, length, output); } static int sha256_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha256(), input, length, output); } static int gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac, unsigned char *result, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned char data[256] = { 0 }; unsigned char tmp_sm; unsigned long blocksize = 0; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = sizeof(g_random); apdu.data = g_random; /* host random */ apdu.le = apdu.resplen = 28; apdu.resp = result; /* card random is result[12~19] */ tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "gen_init_key failed"); /* Step 1 - Generate Derivation data */ memcpy(data, &result[16], 4); memcpy(&data[4], g_random, 4); memcpy(&data[8], &result[12], 4); memcpy(&data[12], &g_random[4], 4); /* Step 2,3 - Create S-ENC/S-MAC Session Key */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } else { des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } memcpy(data, g_random, 8); memcpy(&data[8], &result[12], 8); data[16] = 0x80; blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); memset(&data[17], 0x00, blocksize - 1); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); /* verify card cryptogram */ if (0 != memcmp(&cryptogram[16], &result[20], 8)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); unsigned char data[256] = { 0 }; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; unsigned char mac[256] = { 0 }; unsigned long i; unsigned char tmp_sm; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); memcpy(data, ran_key, 8); memcpy(&data[8], g_random, 8); data[16] = 0x80; memset(&data[17], 0x00, blocksize - 1); memset(iv, 0, 16); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } else { des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } memset(data, 0, sizeof(data)); memcpy(data, "\x84\x82\x03\x00\x10", 5); memcpy(&data[5], &cryptogram[16], 8); memcpy(&data[13], "\x80\x00\x00", 3); /* calculate mac icv */ memset(iv, 0x00, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 0; } else { des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 8; } /* save mac icv */ memset(exdata->icv_mac, 0x00, 16); memcpy(exdata->icv_mac, &mac[i], 8); /* verify host cryptogram */ memcpy(data, &cryptogram[16], 8); memcpy(&data[8], &mac[i], 8); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00); apdu.cla = 0x84; apdu.lc = apdu.datalen = 16; apdu.data = data; tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU verify_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "verify_init_key failed"); return r; } static int mutual_auth(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac) { struct sc_context *ctx = card->ctx; int r; unsigned char result[256] = { 0 }; unsigned char ran_key[8] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(ctx); r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype); LOG_TEST_RET(ctx, r, "gen_init_key failed"); memcpy(ran_key, &result[12], 8); r = verify_init_key(card, ran_key, exdata->smtype); LOG_TEST_RET(ctx, r, "verify_init_key failed"); LOG_FUNC_RETURN(ctx, r); } int epass2003_refresh(struct sc_card *card) { int r = SC_SUCCESS; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (exdata->sm) { card->sm_ctx.sm_mode = 0; r = mutual_auth(card, g_init_key_enc, g_init_key_mac); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; LOG_TEST_RET(card->ctx, r, "mutual_auth failed"); } return r; } /* Data(TLV)=0x87|L|0x01+Cipher */ static int construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf, unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char pad[4096] = { 0 }; size_t pad_len; size_t tlv_more; /* increased tlv length */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* padding */ apdu_buf[block_size] = 0x87; memcpy(pad, apdu->data, apdu->lc); pad[apdu->lc] = 0x80; if ((apdu->lc + 1) % block_size) pad_len = ((apdu->lc + 1) / block_size + 1) * block_size; else pad_len = apdu->lc + 1; /* encode Lc' */ if (pad_len > 0x7E) { /* Lc' > 0x7E, use extended APDU */ apdu_buf[block_size + 1] = 0x82; apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100); apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100); apdu_buf[block_size + 4] = 0x01; tlv_more = 5; } else { apdu_buf[block_size + 1] = (unsigned char)pad_len + 1; apdu_buf[block_size + 2] = 0x01; tlv_more = 3; } memcpy(data_tlv, &apdu_buf[block_size], tlv_more); /* encrypt Data */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len); *data_tlv_len = tlv_more + pad_len; return 0; } /* Le(TLV)=0x97|L|Le */ static int construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len, unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); *(apdu_buf + block_size + data_tlv_len) = 0x97; if (apdu->le > 0x7F) { /* Le' > 0x7E, use extended APDU */ *(apdu_buf + block_size + data_tlv_len + 1) = 2; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100); *(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100); memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4); *le_tlv_len = 4; } else { *(apdu_buf + block_size + data_tlv_len + 1) = 1; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le; memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3); *le_tlv_len = 3; } return 0; } /* MAC(TLV)=0x8e|0x08|MAC */ static int construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, sizeof iv); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; } /* According to GlobalPlatform Card Specification's SCP01 * encode APDU from * CLA INS P1 P2 [Lc] Data [Le] * to * CLA INS P1 P2 Lc' Data' [Le] * where * Data'=Data(TLV)+Le(TLV)+MAC(TLV) */ static int encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm, unsigned char *apdu_buf, size_t * apdu_buf_len) { size_t block_size = 0; unsigned char dataTLV[4096] = { 0 }; size_t data_tlv_len = 0; unsigned char le_tlv[256] = { 0 }; size_t le_tlv_len = 0; size_t mac_tlv_len = 10; size_t tmp_lc = 0; size_t tmp_le = 0; unsigned char mac_tlv[256] = { 0 }; epass2003_exdata *exdata = NULL; mac_tlv[0] = 0x8E; mac_tlv[1] = 8; /* size_t plain_le = 0; */ if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata*)card->drv_data; block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8); sm->cse = SC_APDU_CASE_4_SHORT; apdu_buf[0] = (unsigned char)plain->cla; apdu_buf[1] = (unsigned char)plain->ins; apdu_buf[2] = (unsigned char)plain->p1; apdu_buf[3] = (unsigned char)plain->p2; /* plain_le = plain->le; */ /* padding */ apdu_buf[4] = 0x80; memset(&apdu_buf[5], 0x00, block_size - 5); /* Data -> Data' */ if (plain->lc != 0) if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype)) return -1; if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0)) if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv, &le_tlv_len, exdata->smtype)) return -1; if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype)) return -1; memset(apdu_buf + 4, 0, *apdu_buf_len - 4); sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len; if (sm->lc > 0xFF) { sm->cse = SC_APDU_CASE_4_EXT; apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000); apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100); apdu_buf[6] = (unsigned char)((sm->lc) % 0x100); tmp_lc = 3; } else { apdu_buf[4] = (unsigned char)sm->lc; tmp_lc = 1; } memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len); memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen); *apdu_buf_len = 0; if (4 == le_tlv_len) { sm->cse = SC_APDU_CASE_4_EXT; *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100); *(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100); tmp_le = 2; } else if (3 == le_tlv_len) { *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le; tmp_le = 1; } *apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le; /* sm->le = calc_le(plain_le); */ return 0; } static int epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm) { unsigned char buf[4096] = { 0 }; /* APDU buffer */ size_t buf_len = sizeof(buf); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); if (exdata->sm) plain->cla |= 0x0C; sm->cse = plain->cse; sm->cla = plain->cla; sm->ins = plain->ins; sm->p1 = plain->p1; sm->p2 = plain->p2; sm->lc = plain->lc; sm->le = plain->le; sm->control = plain->control; sm->flags = plain->flags; switch (sm->cla & 0x0C) { case 0x00: case 0x04: sm->datalen = plain->datalen; memcpy((void *)sm->data, plain->data, plain->datalen); sm->resplen = plain->resplen; memcpy(sm->resp, plain->resp, plain->resplen); break; case 0x0C: memset(buf, 0, sizeof(buf)); if (0 != encode_apdu(card, plain, sm, buf, &buf_len)) return SC_ERROR_CARD_CMD_FAILED; break; default: return SC_ERROR_INCORRECT_PARAMETERS; } return SC_SUCCESS; } /* According to GlobalPlatform Card Specification's SCP01 * decrypt APDU response from * ResponseData' SW1 SW2 * to * ResponseData SW1 SW2 * where * ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV) * where * Data(TLV)=0x87|L|Cipher * SW12(TLV)=0x99|0x02|SW1+SW2 * MAC(TLV)=0x8e|0x08|MAC */ static int decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len || *out_len < cipher_len - 2) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } static int epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { len = plain->resplen; if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); if (!sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); if (!(*sm_apdu)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (plain) rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain); if ((*sm_apdu)->data) { unsigned char * p = (unsigned char *)((*sm_apdu)->data); free(p); } if ((*sm_apdu)->resp) { free((*sm_apdu)->resp); } free(*sm_apdu); *sm_apdu = NULL; LOG_FUNC_RETURN(ctx, rv); } static int epass2003_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; struct sc_apdu *apdu = NULL; int rv; LOG_FUNC_CALLED(ctx); if (!plain || !sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); *sm_apdu = NULL; //construct new SM apdu from original apdu apdu = calloc(1, sizeof(struct sc_apdu)); if (!apdu) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->resp) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE; apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE; rv = epass2003_sm_wrap_apdu(card, plain, apdu); if (rv) { rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu); if (rv < 0) goto err; } *sm_apdu = apdu; apdu = NULL; err: if (apdu) { free((unsigned char *) apdu->data); free(apdu->resp); free(apdu); apdu = NULL; } LOG_FUNC_RETURN(ctx, rv); } static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu) { int r; LOG_FUNC_CALLED(card->ctx); r = sc_transmit_apdu_t(card, apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return r; } static int get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t resplen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type); apdu.resp = resp; apdu.le = 0; apdu.resplen = resplen; if (0x86 == type) { /* No SM temporarily */ unsigned char tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = sc_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; } else { r = sc_transmit_apdu_t(card, &apdu); } LOG_TEST_RET(card->ctx, r, "APDU get_data failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get_data failed"); memcpy(data, resp, datalen); return r; } /* card driver functions */ static int epass2003_match_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); r = _sc_match_atr(card, epass2003_atrs, &card->type); if (r < 0) return 0; return 1; } static int epass2003_init(struct sc_card *card) { unsigned int flags; unsigned int ext_flags; unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t datalen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); card->name = "epass2003"; card->cla = 0x00; exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata)); if (!exdata) return SC_ERROR_OUT_OF_MEMORY; card->drv_data = exdata; exdata->sm = SM_SCP01; /* decide FIPS/Non-FIPS mode */ if (SC_SUCCESS != get_data(card, 0x86, data, datalen)) return SC_ERROR_INVALID_CARD; if (0x01 == data[2]) exdata->smtype = KEY_TYPE_AES; else exdata->smtype = KEY_TYPE_DES; if (0x84 == data[14]) { if (0x00 == data[16]) { exdata->sm = SM_PLAIN; } } /* mutual authentication */ card->max_recv_size = 0xD8; card->max_send_size = 0xE8; card->sm_ctx.ops.open = epass2003_refresh; card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu; card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu; /* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */ epass2003_refresh(card); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); //set EC Alg Flags flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW; ext_flags = 0; _sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL); card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_finish(sc_card_t *card) { epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data; if (exdata) free(exdata); return SC_SUCCESS; } /* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the * same DF, so use hook functions to increase/decrease FID by 0x20 */ static int epass2003_hook_path(struct sc_path *path, int inc) { u8 fid_h = path->value[path->len - 2]; u8 fid_l = path->value[path->len - 1]; switch (fid_h) { case 0x29: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: if (inc) fid_l = fid_l * FID_STEP; else fid_l = fid_l / FID_STEP; path->value[path->len - 1] = fid_l; return 1; default: break; } return 0; } static void epass2003_hook_file(struct sc_file *file, int inc) { int fidl = file->id & 0xff; int fidh = file->id & 0xff00; if (epass2003_hook_path(&file->path, inc)) { if (inc) file->id = fidh + fidl * FID_STEP; else file->id = fidh + fidl / FID_STEP; } } static int epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out) { struct sc_apdu apdu; u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen; sc_file_t *file = NULL; epass2003_hook_path(in_path, 1); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: apdu.p1 = 0; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.p2 = 0; /* first record, return FCI */ apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 0; } else { apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */ /* Not allowed to select private key file, so fake fci. */ /* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */ apdu.resplen = 0x18; memcpy(apdu.resp, "\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff", apdu.resplen); apdu.resp[9] = path[1]; apdu.sw1 = 0x90; apdu.sw2 = 0x00; } else { r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); } if (file_out == NULL) { if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(card->ctx, 0); LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(card->ctx, r); if (apdu.resplen < 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); switch (apdu.resp[0]) { case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; if (card->ops->process_fci == NULL) { sc_file_free(file); LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } if ((size_t) apdu.resp[1] + 2 <= apdu.resplen) card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]); epass2003_hook_file(file, 0); *file_out = file; break; case 0x00: /* proprietary coding */ LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } return 0; } static int epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo, sc_file_t ** file_out) { int r; sc_file_t *file = 0; sc_path_t path; memset(&path, 0, sizeof(path)); path.type = SC_PATH_TYPE_FILE_ID; path.value[0] = id_hi; path.value[1] = id_lo; path.len = 2; r = epass2003_select_fid_(card, &path, &file); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ if (file && file->type == SC_FILE_TYPE_DF) { card->cache.current_path.type = SC_PATH_TYPE_PATH; card->cache.current_path.value[0] = 0x3f; card->cache.current_path.value[1] = 0x00; if (id_hi == 0x3f && id_lo == 0x00) { card->cache.current_path.len = 2; } else { card->cache.current_path.len = 4; card->cache.current_path.value[2] = id_hi; card->cache.current_path.value[3] = id_lo; } } if (file_out) *file_out = file; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r = 0; if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_DF_NAME && card->cache.current_path.len == in_path->len && memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) { if (file_out) { *file_out = sc_file_new(); if (!file_out) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } } else { r = iso_ops->select_file(card, in_path, file_out); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ card->cache.current_path.type = SC_PATH_TYPE_DF_NAME; card->cache.current_path.len = in_path->len; memcpy(card->cache.current_path.value, in_path->value, in_path->len); } if (file_out) { sc_file_t *file = *file_out; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->path.len = 0; file->size = 0; /* AID */ memcpy(file->name, in_path->value, in_path->len); file->namelen = in_path->len; file->id = 0x0000; } LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len, sc_file_t ** file_out) { u8 n_pathbuf[SC_MAX_PATH_SIZE]; const u8 *path = pathbuf; size_t pathlen = len; int bMatch = -1; unsigned int i; int r; if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* if pathlen == 6 then the first FID must be MF (== 3F00) */ if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* unify path (the first FID should be MF) */ if (path[0] != 0x3f || path[1] != 0x00) { n_pathbuf[0] = 0x3f; n_pathbuf[1] = 0x00; for (i = 0; i < pathlen; i++) n_pathbuf[i + 2] = pathbuf[i]; path = n_pathbuf; pathlen += 2; } /* check current working directory */ if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_PATH && card->cache.current_path.len >= 2 && card->cache.current_path.len <= pathlen) { bMatch = 0; for (i = 0; i < card->cache.current_path.len; i += 2) if (card->cache.current_path.value[i] == path[i] && card->cache.current_path.value[i + 1] == path[i + 1]) bMatch += 2; } if (card->cache.valid && bMatch > 2) { if (pathlen - bMatch == 2) { /* we are in the right directory */ return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out); } else if (pathlen - bMatch > 2) { /* two more steps to go */ sc_path_t new_path; /* first step: change directory */ r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); new_path.type = SC_PATH_TYPE_PATH; new_path.len = pathlen - bMatch - 2; memcpy(new_path.value, &(path[bMatch + 2]), new_path.len); /* final step: select file */ return epass2003_select_file(card, &new_path, file_out); } else { /* if (bMatch - pathlen == 0) */ /* done: we are already in the * requested directory */ sc_log(card->ctx, "cache hit\n"); /* copy file info (if necessary) */ if (file_out) { sc_file_t *file = sc_file_new(); if (!file) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->id = (path[pathlen - 2] << 8) + path[pathlen - 1]; file->path = card->cache.current_path; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->size = 0; file->namelen = 0; file->magic = SC_FILE_MAGIC; *file_out = file; } /* nothing left to do */ return SC_SUCCESS; } } else { /* no usable cache */ for (i = 0; i < pathlen - 2; i += 2) { r = epass2003_select_fid(card, path[i], path[i + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); } return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out); } } static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r; char pbuf[SC_MAX_PATH_STRING_SIZE]; LOG_FUNC_CALLED(card->ctx); r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path); if (r != SC_SUCCESS) pbuf[0] = '\0'; sc_log(card->ctx, "current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n", card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ? "aid" : "path", card->cache.valid ? "valid" : "invalid", pbuf, card->cache.current_path.len); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (in_path->len != 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out); case SC_PATH_TYPE_DF_NAME: return epass2003_select_aid(card, in_path, file_out); case SC_PATH_TYPE_PATH: return epass2003_select_path(card, in_path->value, in_path->len, file_out); default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } } static int epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num) { struct sc_apdu apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 *p; unsigned short fid = 0; int r, locked = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0); p = sbuf; *p++ = 0x80; /* algorithm reference */ *p++ = 0x01; *p++ = 0x84; *p++ = 0x81; *p++ = 0x02; fid = 0x2900; fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff)); *p++ = fid >> 8; *p++ = fid & 0xff; r = p - sbuf; apdu.lc = r; apdu.datalen = r; apdu.data = sbuf; if (env->algorithm == SC_ALGORITHM_EC) { apdu.p2 = 0xB6; exdata->currAlg = SC_ALGORITHM_EC; if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1) { sbuf[2] = 0x91; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1; } else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256) { sbuf[2] = 0x92; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256; } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags); goto err; } } else if(env->algorithm == SC_ALGORITHM_RSA) { exdata->currAlg = SC_ALGORITHM_RSA; apdu.p2 = 0xB8; sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags); } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm); } if (se_num > 0) { r = sc_lock(card); LOG_TEST_RET(card->ctx, r, "sc_lock() failed"); locked = 1; } if (apdu.datalen != 0) { r = sc_transmit_apdu_t(card, &apdu); if (r) { sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r)); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) { sc_log(card->ctx, "%s: Card returned error", sc_strerror(r)); goto err; } } if (se_num <= 0) return 0; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num); r = sc_transmit_apdu_t(card, &apdu); sc_unlock(card); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); err: if (locked) sc_unlock(card); return r; } static int epass2003_restore_security_env(struct sc_card *card, int se_num) { LOG_FUNC_CALLED(card->ctx); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if(exdata->currAlg == SC_ALGORITHM_EC) { if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x14; apdu.datalen = 0x14; } else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x20; apdu.datalen = 0x20; } else { return SC_ERROR_NOT_SUPPORTED; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } else if(exdata->currAlg == SC_ALGORITHM_RSA) { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } else { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e) { if (e == NULL) return SC_ERROR_OBJECT_NOT_FOUND; switch (e->method) { case SC_AC_NONE: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE); case SC_AC_NEVER: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE); default: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); } static int epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen) { sc_context_t *ctx = card->ctx; size_t taglen, len = buflen; const u8 *tag = NULL, *p = buf; sc_log(ctx, "processing FCI bytes"); tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen); if (tag != NULL && taglen == 2) { file->id = (tag[0] << 8) | tag[1]; sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]); } tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen); if (tag != NULL && taglen > 0 && taglen < 3) { file->size = tag[0]; if (taglen == 2) file->size = (file->size << 8) + tag[1]; sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u", file->size); } if (tag == NULL) { tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen); if (tag != NULL && taglen >= 2) { int bytes = (tag[0] << 8) + tag[1]; sc_log(ctx, " bytes in file: %d", bytes); file->size = bytes; } } tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen); if (tag != NULL) { if (taglen > 0) { unsigned char byte = tag[0]; const char *type; if (byte == 0x38) { type = "DF"; file->type = SC_FILE_TYPE_DF; } else if (0x01 <= byte && byte <= 0x07) { type = "working EF"; file->type = SC_FILE_TYPE_WORKING_EF; switch (byte) { case 0x01: file->ef_structure = SC_FILE_EF_TRANSPARENT; break; case 0x02: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x04: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x03: case 0x05: case 0x06: case 0x07: break; default: break; } } else if (0x10 == byte) { type = "BSO"; file->type = SC_FILE_TYPE_BSO; } else if (0x11 <= byte) { type = "internal EF"; file->type = SC_FILE_TYPE_INTERNAL_EF; switch (byte) { case 0x11: break; case 0x12: break; default: break; } } else { type = "unknown"; file->type = SC_FILE_TYPE_INTERNAL_EF; } sc_log(ctx, "type %s, EF structure %d", type, byte); } } tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen); if (tag != NULL && taglen > 0 && taglen <= 16) { memcpy(file->name, tag, taglen); file->namelen = taglen; sc_log_hex(ctx, "File name", file->name, file->namelen); if (!file->type) file->type = SC_FILE_TYPE_DF; } tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); else file->prop_attr_len = 0; tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen); if (tag != NULL && taglen) sc_file_set_sec_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen); if (tag != NULL && taglen == 1) { if (tag[0] == 0x01) file->status = SC_FILE_STATUS_CREATION; else if (tag[0] == 0x07 || tag[0] == 0x05) file->status = SC_FILE_STATUS_ACTIVATED; else if (tag[0] == 0x06 || tag[0] == 0x04) file->status = SC_FILE_STATUS_INVALIDATED; } file->magic = SC_FILE_MAGIC; return 0; } static int epass2003_construct_fci(struct sc_card *card, const sc_file_t * file, u8 * out, size_t * outlen) { u8 *p = out; u8 buf[64]; unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; int rv; unsigned ii; if (*outlen < 2) return SC_ERROR_BUFFER_TOO_SMALL; *p++ = 0x62; p++; if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p); } } if (file->type == SC_FILE_TYPE_DF) { buf[0] = 0x38; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_WORKING_EF) { buf[0] = file->ef_structure & 7; if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { buf[1] = 0x00; buf[2] = 0x00; buf[3] = 0x40; /* record length */ buf[4] = 0x00; /* record count */ sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p); } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { buf[0] = 0x11; buf[1] = 0x00; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = 0x12; buf[1] = 0x00; } else { return SC_ERROR_NOT_SUPPORTED; } sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = 0x10; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p); if (file->type == SC_FILE_TYPE_DF) { if (file->namelen != 0) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p); } else { return SC_ERROR_INVALID_ARGUMENTS; } } if (file->type == SC_FILE_TYPE_DF) { unsigned char data[2] = {0x00, 0x7F}; /* 127 files at most */ sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = file->size & 0xff; sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p); } } if (file->sec_attr_len) { memcpy(buf, file->sec_attr, file->sec_attr_len); sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p); } else { sc_log(card->ctx, "SC_FILE_ACL"); if (file->type == SC_FILE_TYPE_DF) { ops[0] = SC_AC_OP_LIST_FILES; ops[1] = SC_AC_OP_CREATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_WRITE; ops[3] = SC_AC_OP_DELETE; } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_BSO) { ops[0] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } } else { return SC_ERROR_NOT_SUPPORTED; } for (ii = 0; ii < sizeof(ops); ii++) { const struct sc_acl_entry *entry; buf[ii] = 0xFF; if (ops[ii] == 0xFF) continue; entry = sc_file_get_acl_entry(file, ops[ii]); rv = acl_to_ac_byte(card, entry); LOG_TEST_RET(card->ctx, rv, "Invalid ACL"); buf[ii] = rv; } sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x13; } } /* VT ??? */ if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { unsigned char data[2] = {0x00, 0x66}; sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x14; } } out[1] = p - out - 2; *outlen = p - out; return 0; } static int epass2003_create_file(struct sc_card *card, sc_file_t * file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; struct sc_apdu apdu; len = SC_MAX_APDU_BUFFER_SIZE; epass2003_hook_file(file, 1); if (card->ops->construct_fci == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); r = epass2003_construct_fci(card, file, sbuf, &len); LOG_TEST_RET(card->ctx, r, "construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong"); epass2003_hook_file(file, 0); return r; } static int epass2003_delete_file(struct sc_card *card, const sc_path_t * path) { int r; u8 sbuf[2]; struct sc_apdu apdu; LOG_FUNC_CALLED(card->ctx); r = sc_select_file(card, path, NULL); epass2003_hook_path((struct sc_path *)path, 1); if (r == SC_SUCCESS) { sbuf[0] = path->value[path->len - 2]; sbuf[1] = path->value[path->len - 1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Delete file failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen) { struct sc_apdu apdu; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00); apdu.cla = 0x80; apdu.le = 0; apdu.resplen = sizeof(rbuf); apdu.resp = rbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Card returned error"); if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0) LOG_FUNC_RETURN(card->ctx, 0); buflen = buflen < apdu.resplen ? buflen : apdu.resplen; memcpy(buf, rbuf, buflen); LOG_FUNC_RETURN(card->ctx, buflen); } static int internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor, sc_pkcs15_bignum_t data) { int r; struct sc_apdu apdu; u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); sbuff[0] = ((fid & 0xff00) >> 8); sbuff[1] = (fid & 0x00ff); memcpy(&sbuff[2], data.data, data.len); // sc_mem_reverse(&sbuff[2], data.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 2 + data.len; apdu.data = sbuff; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa) { int r; LOG_FUNC_CALLED(card->ctx); r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus); LOG_TEST_RET(card->ctx, r, "write n failed"); r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d); LOG_TEST_RET(card->ctx, r, "write d failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType) { if ((NULL == data) || (NULL == hash)) return SC_ERROR_INVALID_ARGUMENTS; if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1) { unsigned char data_hash[24] = { 0 }; size_t len = 0; sha1_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[20], &len, 4); memcpy(hash, data_hash, 24); } else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256) { unsigned char data_hash[36] = { 0 }; size_t len = 0; sha256_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[32], &len, 4); memcpy(hash, data_hash, 36); } else { return SC_ERROR_NOT_SUPPORTED; } return SC_SUCCESS; } static int install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, unsigned char useac, unsigned char modifyac, unsigned char EC, unsigned char *data, unsigned long dataLen) { int r; struct sc_apdu apdu; unsigned char isapp = 0x00; /* appendable */ unsigned char tmp_data[256] = { 0 }; tmp_data[0] = ktype; tmp_data[1] = kid; tmp_data[2] = useac; tmp_data[3] = modifyac; tmp_data[8] = 0xFF; if (0x04 == ktype || 0x06 == ktype) { tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO); tmp_data[9] = (EC << 4) | EC; } memcpy(&tmp_data[10], data, dataLen); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 10 + dataLen; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "install_secret_key failed"); return r; } static int internal_install_pre(struct sc_card *card) { int r; /* init key for enc */ r = install_secret_key(card, 0x01, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_enc, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); /* init key for mac */ r = install_secret_key(card, 0x02, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_mac, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); return r; } /* use external auth secret as pin */ static int internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin) { int r; unsigned char hash[HASH_LEN] = { 0 }; r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid, pin->key_data.es_secret.ac[0], pin->key_data.es_secret.ac[1], pin->key_data.es_secret.EC, hash, HASH_LEN); LOG_TEST_RET(card->ctx, r, "Install failed"); return r; } static int epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data) { LOG_FUNC_CALLED(card->ctx); if (data->type & SC_EPASS2003_KEY) { if (data->type == SC_EPASS2003_KEY_RSA) return internal_write_rsa_key(card, data->key_data.es_key.fid, data->key_data.es_key.rsa); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else if (data->type & SC_EPASS2003_SECRET) { if (data->type == SC_EPASS2003_SECRET_PRE) return internal_install_pre(card); else if (data->type == SC_EPASS2003_SECRET_PIN) return internal_install_pin(card, data); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data) { int r; size_t len = data->key_length; struct sc_apdu apdu; u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); if(len == 256) { sbuf[0] = 0x02; } else { sbuf[0] = 0x01; } sbuf[1] = (u8) ((len >> 8) & 0xff); sbuf[2] = (u8) (len & 0xff); sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF); sbuf[4] = (u8) ((data->prkey_id) & 0xFF); sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF); sbuf[6] = (u8) ((data->pukey_id) & 0xFF); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.lc = apdu.datalen = 7; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "generate keypair failed"); /* read public key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00); if(len == 256) { apdu.p1 = 0x00; } apdu.cla = 0x80; apdu.lc = apdu.datalen = 2; apdu.data = &sbuf[5]; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x00; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get pukey failed"); if (len < apdu.resplen) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); data->modulus = (u8 *) malloc(len); if (!data->modulus) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(data->modulus, rbuf, len); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_erase_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); sc_invalidate_cache(card); r = sc_delete_file(card, sc_get_mf_path()); LOG_TEST_RET(card->ctx, r, "delete MF failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial) { u8 rbuf[8]; size_t rbuf_len = sizeof(rbuf); LOG_FUNC_CALLED(card->ctx); if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len)) return SC_ERROR_CARD_CMD_FAILED; card->serialnr.len = serial->len = 8; memcpy(card->serialnr.value, rbuf, 8); memcpy(serial->value, rbuf, 8); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd is %0lx", cmd); switch (cmd) { case SC_CARDCTL_ENTERSAFE_WRITE_KEY: return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr); case SC_CARDCTL_ENTERSAFE_GENERATE_KEY: return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr); case SC_CARDCTL_ERASE_CARD: return epass2003_erase_card(card); case SC_CARDCTL_GET_SERIALNR: return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr); default: return SC_ERROR_NOT_SUPPORTED; } } static void internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num) { pin->encoding = SC_PIN_ENCODING_ASCII; pin->min_length = 4; pin->max_length = 16; pin->pad_length = 16; pin->offset = 5 + num * 16; pin->pad_char = 0x00; } static int get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries) { unsigned char maxcounter[2] = { 0 }; static const sc_path_t file_path = { {0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6, 0, 0, SC_PATH_TYPE_PATH, {{0}, 0} }; int ret; ret = sc_select_file(card, &file_path, NULL); LOG_TEST_RET(card->ctx, ret, "select max counter file failed"); ret = sc_read_binary(card, 0, maxcounter, 2, 0); LOG_TEST_RET(card->ctx, ret, "read max counter file failed"); *maxtries = maxcounter[0]; return SC_SUCCESS; } static int get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid); apdu.resp = NULL; apdu.resplen = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed"); if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) { *retries = (apdu.sw2 & 0x0f); r = SC_SUCCESS; } else { LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed"); r = SC_ERROR_CARD_CMD_FAILED; } return r; } static int epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { u8 rbuf[16]; size_t out_len; int r; LOG_FUNC_CALLED(card->ctx); r = iso_ops->get_challenge(card, rbuf, sizeof rbuf); LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed"); if (len < (size_t) r) { out_len = len; } else { out_len = (size_t) r; } memcpy(rnd, rbuf, out_len); LOG_FUNC_RETURN(card->ctx, (int) out_len); } static int external_key_auth(struct sc_card *card, unsigned char kid, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; unsigned char tmp_data[16] = { 0 }; unsigned char hash[HASH_LEN] = { 0 }; unsigned char iv[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed"); r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid); apdu.lc = apdu.datalen = 8; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "external_key_auth failed"); return r; } static int update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, const unsigned char *data, unsigned long datalen) { int r; struct sc_apdu apdu; unsigned char hash[HASH_LEN] = { 0 }; unsigned char tmp_data[256] = { 0 }; unsigned char maxtries = 0; r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); tmp_data[0] = (maxtries << 4) | maxtries; memcpy(&tmp_data[1], hash, HASH_LEN); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid); apdu.cla = 0x80; apdu.lc = apdu.datalen = 1 + HASH_LEN; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "update_secret_key failed"); return r; } /* use external auth secret as pin */ static int epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { int r; u8 kid; u8 retries = 0; u8 pin_low = 3; unsigned char maxtries = 0; LOG_FUNC_CALLED(card->ctx); internal_sanitize_pin_info(&data->pin1, 0); internal_sanitize_pin_info(&data->pin2, 1); data->flags |= SC_PIN_CMD_NEED_PADDING; kid = data->pin_reference; /* get pin retries */ if (data->cmd == SC_PIN_CMD_GET_INFO) { r = get_external_key_retries(card, 0x80 | kid, &retries); if (r == SC_SUCCESS) { data->pin1.tries_left = retries; if (tries_left) *tries_left = retries; r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); data->pin1.max_tries = maxtries; } //remove below code, because the old implement only return PIN retries, now modify the code and return PIN status // return r; } else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */ r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data, data->pin1.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */ r = update_secret_key(card, 0x04, kid, data->pin2.data, (unsigned long)data->pin2.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else { r = external_key_auth(card, kid, (unsigned char *)data->pin1.data, data->pin1.len); get_external_key_retries(card, 0x80 | kid, &retries); if (retries < pin_low) sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries); } LOG_TEST_RET(card->ctx, r, "verify pin failed"); if (r == SC_SUCCESS) { data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN; } return r; } static struct sc_card_driver *sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; epass2003_ops = *iso_ops; epass2003_ops.match_card = epass2003_match_card; epass2003_ops.init = epass2003_init; epass2003_ops.finish = epass2003_finish; epass2003_ops.write_binary = NULL; epass2003_ops.write_record = NULL; epass2003_ops.select_file = epass2003_select_file; epass2003_ops.get_response = NULL; epass2003_ops.restore_security_env = epass2003_restore_security_env; epass2003_ops.set_security_env = epass2003_set_security_env; epass2003_ops.decipher = epass2003_decipher; epass2003_ops.compute_signature = epass2003_decipher; epass2003_ops.create_file = epass2003_create_file; epass2003_ops.delete_file = epass2003_delete_file; epass2003_ops.list_files = epass2003_list_files; epass2003_ops.card_ctl = epass2003_card_ctl; epass2003_ops.process_fci = epass2003_process_fci; epass2003_ops.construct_fci = epass2003_construct_fci; epass2003_ops.pin_cmd = epass2003_pin_cmd; epass2003_ops.check_sw = epass2003_check_sw; epass2003_ops.get_challenge = epass2003_get_challenge; return &epass2003_drv; } struct sc_card_driver *sc_get_epass2003_driver(void) { return sc_get_driver(); } #endif /* #ifdef ENABLE_OPENSSL */ #endif /* #ifdef ENABLE_SM */
./CrossVul/dataset_final_sorted/CWE-119/c/good_342_1
crossvul-cpp_data_bad_934_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N M M % % P P NN N MM MM % % PPPP N N N M M M % % P N NN M M % % P N N M M % % % % % % Read/Write PBMPlus Portable Anymap Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" /* Typedef declarations. */ typedef struct _CommentInfo { char *comment; size_t extent; } CommentInfo; /* Forward declarations. */ static MagickBooleanType WritePNMImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNM() returns MagickTrue if the image format type, identified by the % magick string, is PNM. % % The format of the IsPNM method is: % % MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o extent: Specifies the extent of the magick string. % */ static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) { if (extent < 2) return(MagickFalse); if ((*magick == (unsigned char) 'P') && ((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') || (magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') || (magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f'))) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNMImage() reads a Portable Anymap image file and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadPNMImage method is: % % Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static int PNMComment(Image *image,CommentInfo *comment_info, ExceptionInfo *exception) { int c; register char *p; /* Read comment. */ p=comment_info->comment+strlen(comment_info->comment); for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++) { if ((size_t) (p-comment_info->comment+1) >= comment_info->extent) { comment_info->extent<<=1; comment_info->comment=(char *) ResizeQuantumMemory( comment_info->comment,comment_info->extent, sizeof(*comment_info->comment)); if (comment_info->comment == (char *) NULL) return(-1); p=comment_info->comment+strlen(comment_info->comment); } c=ReadBlobByte(image); if (c != EOF) { *p=(char) c; *(p+1)='\0'; } } return(c); } static unsigned int PNMInteger(Image *image,CommentInfo *comment_info, const unsigned int base,ExceptionInfo *exception) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(0); if (c == (int) '#') c=PNMComment(image,comment_info,exception); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); if (base == 2) return((unsigned int) (c-(int) '0')); /* Evaluate number. */ value=0; while (isdigit(c) != 0) { if (value <= (unsigned int) (INT_MAX/10)) { value*=10; if (value <= (unsigned int) (INT_MAX-(c-(int) '0'))) value+=c-(int) '0'; } c=ReadBlobByte(image); if (c == EOF) return(0); } if (c == (int) '#') c=PNMComment(image,comment_info,exception); return(value); } static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPNMException(exception,message) \ { \ if (comment_info.comment != (char *) NULL) \ comment_info.comment=DestroyString(comment_info.comment); \ ThrowReaderException((exception),(message)); \ } char format; CommentInfo comment_info; double quantum_scale; Image *image; MagickBooleanType status; QuantumAny max_value; QuantumInfo *quantum_info; QuantumType quantum_type; size_t depth, extent, packet_size; ssize_t count, row, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PNM image. */ count=ReadBlob(image,1,(unsigned char *) &format); do { /* Initialize image structure. */ comment_info.comment=AcquireString(NULL); comment_info.extent=MagickPathExtent; if ((count != 1) || (format != 'P')) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); max_value=1; quantum_type=RGBQuantum; quantum_scale=1.0; format=(char) ReadBlobByte(image); if (format != '7') { /* PBM, PGM, PPM, and PNM. */ image->columns=(size_t) PNMInteger(image,&comment_info,10,exception); image->rows=(size_t) PNMInteger(image,&comment_info,10,exception); if ((format == 'f') || (format == 'F')) { char scale[MagickPathExtent]; if (ReadBlobString(image,scale) != (char *) NULL) quantum_scale=StringToDouble(scale,(char **) NULL); } else { if ((format == '1') || (format == '4')) max_value=1; /* bitmap */ else max_value=(QuantumAny) PNMInteger(image,&comment_info,10, exception); } } else { char keyword[MagickPathExtent], value[MagickPathExtent]; int c; register char *p; /* PAM. */ for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == '#') { /* Comment. */ c=PNMComment(image,&comment_info,exception); c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } p=keyword; do { if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c)); *p='\0'; if (LocaleCompare(keyword,"endhdr") == 0) break; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); p=value; while (isalnum(c) || (c == '_')) { if ((size_t) (p-value) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"depth") == 0) packet_size=StringToUnsignedLong(value); (void) packet_size; if (LocaleCompare(keyword,"height") == 0) image->rows=StringToUnsignedLong(value); if (LocaleCompare(keyword,"maxval") == 0) max_value=StringToUnsignedLong(value); if (LocaleCompare(keyword,"TUPLTYPE") == 0) { if (LocaleCompare(value,"BLACKANDWHITE") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; } if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"GRAYSCALE") == 0) { quantum_type=GrayQuantum; (void) SetImageColorspace(image,GRAYColorspace,exception); } if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"RGB_ALPHA") == 0) { image->alpha_trait=BlendPixelTrait; quantum_type=RGBAQuantum; } if (LocaleCompare(value,"CMYK") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); quantum_type=CMYKQuantum; } if (LocaleCompare(value,"CMYK_ALPHA") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=CMYKAQuantum; } } if (LocaleCompare(keyword,"width") == 0) image->columns=StringToUnsignedLong(value); } } if ((image->columns == 0) || (image->rows == 0)) ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize"); if ((max_value == 0) || (max_value > 4294967295UL)) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); for (depth=1; GetQuantumRange(depth) < max_value; depth++) ; image->depth=depth; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image)) ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { comment_info.comment=DestroyString(comment_info.comment); \ return(DestroyImageList(image)); } (void) ResetImagePixels(image,exception); /* Convert PNM pixels to runextent-encoded MIFF packets. */ row=0; y=0; switch (format) { case '1': { /* Convert PBM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGray(image,PNMInteger(image,&comment_info,2,exception) == 0 ? QuantumRange : 0,q); if (EOFBlob(image) != MagickFalse) break; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=BilevelType; break; } case '2': { Quantum intensity; /* Convert PGM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelGray(image,intensity,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=GrayscaleType; break; } case '3': { /* Convert PNM image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelGreen(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelBlue(image,pixel,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } break; } case '4': { /* Convert PBM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumMinIsWhite(quantum_info,MagickTrue); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '5': { /* Convert PGM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '6': { /* Convert PNM raster image to pixel packets. */ quantum_type=RGBQuantum; extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { size_t channels; /* Convert PAM raster image to pixel packets. */ switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { channels=1; break; } case CMYKQuantum: case CMYKAQuantum: { channels=4; break; } default: { channels=3; break; } } if (image->alpha_trait != UndefinedPixelTrait) channels++; extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); if (image->depth != 1) SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); else SetPixelAlpha(image,QuantumRange- ScaleAnyToQuantum(pixel,max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } } } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case 'F': case 'f': { /* Convert PFM raster image to pixel packets. */ if (format == 'f') (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian; image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,32); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumScale(quantum_info,(double) QuantumRange*fabs(quantum_scale)); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1), image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } default: ThrowPNMException(CorruptImageError,"ImproperImageHeader"); } if (*comment_info.comment != '\0') (void) SetImageProperty(image,"comment",comment_info.comment,exception); comment_info.comment=DestroyString(comment_info.comment); if (y < (ssize_t) image->rows) ThrowPNMException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((format == '1') || (format == '2') || (format == '3')) do { /* Skip to end of line. */ count=ReadBlob(image,1,(unsigned char *) &format); if (count != 1) break; if (format == 'P') break; } while (format != '\n'); count=ReadBlob(image,1,(unsigned char *) &format); if ((count == 1) && (format == 'P')) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count == 1) && (format == 'P')); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNMImage() adds properties for the PNM image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNMImage method is: % % size_t RegisterPNMImage(void) % */ ModuleExport size_t RegisterPNMImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PNM","PAM","Common 2-dimensional bitmap format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PBM", "Portable bitmap format (black and white)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-bitmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PFM","Portable float format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PGM","Portable graymap format (gray scale)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-greymap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PNM","Portable anymap"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->magick=(IsImageFormatHandler *) IsPNM; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PPM","Portable pixmap format (color)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNMImage() removes format registrations made by the % PNM module from the list of supported formats. % % The format of the UnregisterPNMImage method is: % % UnregisterPNMImage(void) % */ ModuleExport void UnregisterPNMImage(void) { (void) UnregisterMagickInfo("PAM"); (void) UnregisterMagickInfo("PBM"); (void) UnregisterMagickInfo("PGM"); (void) UnregisterMagickInfo("PNM"); (void) UnregisterMagickInfo("PPM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNMImage() writes an image to a file in the PNM rasterfile format. % % The format of the WritePNMImage method is: % % MagickBooleanType WritePNMImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], format, magick[MagickPathExtent]; const char *value; MagickBooleanType status; MagickOffsetType scene; Quantum index; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MagickPathExtent); max_value=GetQuantumRange(image->depth); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MagickPathExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MagickPathExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MagickPathExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent); if (IdentifyImageMonochrome(image,exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent); break; } default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MagickPathExtent); break; } } if (image->alpha_trait != UndefinedPixelTrait) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "TUPLTYPE %s\nENDHDR\n",type); (void) WriteBlobString(image,buffer); } /* Convert runextent encoded to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToLong(index)); extent=(size_t) count; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)), ScaleQuantumToChar(GetPixelGreen(image,p)), ScaleQuantumToChar(GetPixelBlue(image,p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)), ScaleQuantumToShort(GetPixelGreen(image,p)), ScaleQuantumToShort(GetPixelBlue(image,p))); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)), ScaleQuantumToLong(GetPixelGreen(image,p)), ScaleQuantumToLong(GetPixelBlue(image,p))); extent=(size_t) count; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { register unsigned char *pixels; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { register unsigned char *pixels; /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)), max_value); else { if (image->depth == 16) pixel=ScaleQuantumToLong(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { register unsigned char *pixels; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register unsigned char *pixels; /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { register unsigned char *pixels; (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_934_0
crossvul-cpp_data_good_935_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N M M % % P P NN N MM MM % % PPPP N N N M M M % % P N NN M M % % P N N M M % % % % % % Read/Write PBMPlus Portable Anymap Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" /* Typedef declarations. */ typedef struct _CommentInfo { char *comment; size_t extent; } CommentInfo; /* Forward declarations. */ static MagickBooleanType WritePNMImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNM() returns MagickTrue if the image format type, identified by the % magick string, is PNM. % % The format of the IsPNM method is: % % MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o extent: Specifies the extent of the magick string. % */ static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) { if (extent < 2) return(MagickFalse); if ((*magick == (unsigned char) 'P') && ((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') || (magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') || (magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f'))) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNMImage() reads a Portable Anymap image file and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadPNMImage method is: % % Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static int PNMComment(Image *image,CommentInfo *comment_info) { int c; register char *p; /* Read comment. */ p=comment_info->comment+strlen(comment_info->comment); for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++) { if ((size_t) (p-comment_info->comment+1) >= comment_info->extent) { comment_info->extent<<=1; comment_info->comment=(char *) ResizeQuantumMemory( comment_info->comment,comment_info->extent, sizeof(*comment_info->comment)); if (comment_info->comment == (char *) NULL) return(-1); p=comment_info->comment+strlen(comment_info->comment); } c=ReadBlobByte(image); if (c != EOF) { *p=(char) c; *(p+1)='\0'; } } return(c); } static unsigned int PNMInteger(Image *image,CommentInfo *comment_info, const unsigned int base) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(0); if (c == (int) '#') c=PNMComment(image,comment_info); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); if (base == 2) return((unsigned int) (c-(int) '0')); /* Evaluate number. */ value=0; while (isdigit(c) != 0) { if (value <= (unsigned int) (INT_MAX/10)) { value*=10; if (value <= (unsigned int) (INT_MAX-(c-(int) '0'))) value+=c-(int) '0'; } c=ReadBlobByte(image); if (c == EOF) return(0); } if (c == (int) '#') c=PNMComment(image,comment_info); return(value); } static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPNMException(exception,message) \ { \ if (comment_info.comment != (char *) NULL) \ comment_info.comment=DestroyString(comment_info.comment); \ ThrowReaderException((exception),(message)); \ } char format; CommentInfo comment_info; double quantum_scale; Image *image; MagickBooleanType status; QuantumAny max_value; QuantumInfo *quantum_info; QuantumType quantum_type; size_t depth, extent, packet_size; ssize_t count, row, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PNM image. */ count=ReadBlob(image,1,(unsigned char *) &format); do { /* Initialize image structure. */ comment_info.comment=AcquireString(NULL); comment_info.extent=MagickPathExtent; if ((count != 1) || (format != 'P')) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); max_value=1; quantum_type=RGBQuantum; quantum_scale=1.0; format=(char) ReadBlobByte(image); if (format != '7') { /* PBM, PGM, PPM, and PNM. */ image->columns=PNMInteger(image,&comment_info,10); image->rows=PNMInteger(image,&comment_info,10); if ((format == 'f') || (format == 'F')) { char scale[MaxTextExtent]; if (ReadBlobString(image,scale) != (char *) NULL) quantum_scale=StringToDouble(scale,(char **) NULL); } else { if ((format == '1') || (format == '4')) max_value=1; /* bitmap */ else max_value=PNMInteger(image,&comment_info,10); } } else { char keyword[MaxTextExtent], value[MaxTextExtent]; int c; register char *p; /* PAM. */ for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == '#') { /* Comment. */ c=PNMComment(image,&comment_info); c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } p=keyword; do { if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c)); *p='\0'; if (LocaleCompare(keyword,"endhdr") == 0) break; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); p=value; while (isalnum(c) || (c == '_')) { if ((size_t) (p-value) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"depth") == 0) packet_size=StringToUnsignedLong(value); (void) packet_size; if (LocaleCompare(keyword,"height") == 0) image->rows=StringToUnsignedLong(value); if (LocaleCompare(keyword,"maxval") == 0) max_value=StringToUnsignedLong(value); if (LocaleCompare(keyword,"TUPLTYPE") == 0) { if (LocaleCompare(value,"BLACKANDWHITE") == 0) { (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; } if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace); image->matte=MagickTrue; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"GRAYSCALE") == 0) { (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; } if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace); image->matte=MagickTrue; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"RGB_ALPHA") == 0) { quantum_type=RGBAQuantum; image->matte=MagickTrue; } if (LocaleCompare(value,"CMYK") == 0) { (void) SetImageColorspace(image,CMYKColorspace); quantum_type=CMYKQuantum; } if (LocaleCompare(value,"CMYK_ALPHA") == 0) { (void) SetImageColorspace(image,CMYKColorspace); image->matte=MagickTrue; quantum_type=CMYKAQuantum; } } if (LocaleCompare(keyword,"width") == 0) image->columns=StringToUnsignedLong(value); } } if ((image->columns == 0) || (image->rows == 0)) ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize"); if ((max_value == 0) || (max_value > 4294967295U)) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); for (depth=1; GetQuantumRange(depth) < max_value; depth++) ; image->depth=depth; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image)) ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile"); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } (void) ResetImagePixels(image,exception); /* Convert PNM pixels. */ row=0; switch (format) { case '1': { /* Convert PBM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,PNMInteger(image,&comment_info,2) == 0 ? QuantumRange : 0); if (EOFBlob(image) != MagickFalse) break; SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=BilevelType; break; } case '2': { size_t intensity; /* Convert PGM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10), max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(q,intensity); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=GrayscaleType; break; } case '3': { /* Convert PNM image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { QuantumAny pixel; pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10), max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(q,pixel); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10), max_value); SetPixelGreen(q,pixel); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10), max_value); SetPixelBlue(q,pixel); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } break; } case '4': { /* Convert PBM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumMinIsWhite(quantum_info,MagickTrue); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register PixelPacket *magick_restrict q; ssize_t count, offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '5': { /* Convert PGM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t count, offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '6': { /* Convert PNM raster image to pixel packets. */ quantum_type=RGBQuantum; extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t count, offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; p=pixels; switch (image->depth) { case 8: { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q->opacity=OpaqueOpacity; q++; } break; } case 16: { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleShortToQuantum(pixel)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleShortToQuantum(pixel)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleShortToQuantum(pixel)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } case 32: { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleLongToQuantum(pixel)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleLongToQuantum(pixel)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleLongToQuantum(pixel)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } default: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } break; } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register IndexPacket *indexes; size_t channels; /* Convert PAM raster image to pixel packets. */ switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { channels=1; break; } case CMYKQuantum: case CMYKAQuantum: { channels=4; break; } default: { channels=3; break; } } if (image->matte != MagickFalse) channels++; extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register PixelPacket *magick_restrict q; ssize_t count, offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushCharPixel(p,&pixel); if (image->depth != 1) SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); else SetPixelOpacity(q,QuantumRange-ScaleAnyToQuantum( pixel,max_value)); } q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value)); } q++; } break; } case CMYKQuantum: case CMYKAQuantum: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel, max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushCharPixel(p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel, max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value)); } q++; } break; } default: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushCharPixel(p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value)); } q++; } break; } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case 'F': case 'f': { /* Convert PFM raster image to pixel packets. */ if (format == 'f') (void) SetImageColorspace(image,GRAYColorspace); quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian; image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,32); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumScale(quantum_info,(MagickRealType) QuantumRange* fabs(quantum_scale)); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register PixelPacket *magick_restrict q; ssize_t count, offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if ((size_t) count != extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1), image->columns,1,exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } default: ThrowPNMException(CorruptImageError,"ImproperImageHeader"); } if (*comment_info.comment != '\0') (void) SetImageProperty(image,"comment",comment_info.comment); comment_info.comment=DestroyString(comment_info.comment); if (y < (ssize_t) image->rows) ThrowPNMException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((format == '1') || (format == '2') || (format == '3')) do { /* Skip to end of line. */ count=ReadBlob(image,1,(unsigned char *) &format); if (count != 1) break; if (format == 'P') break; } while (format != '\n'); count=ReadBlob(image,1,(unsigned char *) &format); if ((count == 1) && (format == 'P')) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count == 1) && (format == 'P')); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNMImage() adds properties for the PNM image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNMImage method is: % % size_t RegisterPNMImage(void) % */ ModuleExport size_t RegisterPNMImage(void) { MagickInfo *entry; entry=SetMagickInfo("PAM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->description=ConstantString("Common 2-dimensional bitmap format"); entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PBM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->description=ConstantString("Portable bitmap format (black and white)"); entry->mime_type=ConstantString("image/x-portable-bitmap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PFM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->endian_support=MagickTrue; entry->description=ConstantString("Portable float format"); entry->module=ConstantString("PFM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PGM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->description=ConstantString("Portable graymap format (gray scale)"); entry->mime_type=ConstantString("image/x-portable-greymap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->magick=(IsImageFormatHandler *) IsPNM; entry->description=ConstantString("Portable anymap"); entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PPM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->description=ConstantString("Portable pixmap format (color)"); entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNMImage() removes format registrations made by the % PNM module from the list of supported formats. % % The format of the UnregisterPNMImage method is: % % UnregisterPNMImage(void) % */ ModuleExport void UnregisterPNMImage(void) { (void) UnregisterMagickInfo("PAM"); (void) UnregisterMagickInfo("PBM"); (void) UnregisterMagickInfo("PGM"); (void) UnregisterMagickInfo("PNM"); (void) UnregisterMagickInfo("PPM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNMImage() writes an image to a file in the PNM rasterfile format. % % The format of the WritePNMImage method is: % % MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image) { char buffer[MaxTextExtent], format, magick[MaxTextExtent]; const char *value; IndexPacket index; MagickBooleanType status; MagickOffsetType scene; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *pixels, *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ max_value=GetQuantumRange(image->depth); packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MaxTextExtent); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,&image->exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,&image->exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MaxTextExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MaxTextExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,&image->exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MaxTextExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent); if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent); break; } default: { quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MaxTextExtent); break; } } if (image->matte != MagickFalse) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n", type); (void) WriteBlobString(image,buffer); } /* Convert to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } *q++=' '; p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToLong(index)); extent=(size_t) count; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)), ScaleQuantumToChar(GetPixelGreen(p)), ScaleQuantumToChar(GetPixelBlue(p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)), ScaleQuantumToShort(GetPixelGreen(p)), ScaleQuantumToShort(GetPixelBlue(p))); else count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)), ScaleQuantumToLong(GetPixelGreen(p)), ScaleQuantumToLong(GetPixelBlue(p))); extent=(size_t) count; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,pixels,&image->exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,pixels,&image->exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopCharPixel((unsigned char) pixel,q); p++; } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 32) pixel=ScaleQuantumToLong(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p++; } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); p++; } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_935_0
crossvul-cpp_data_good_634_2
/********************************************************************* * * This is based on code created by Peter Harvey, * (pharvey@codebydesign.com). * * Modified and extended by Nick Gorham * (nick@lurcher.org). * * Any bugs or problems should be considered the fault of Nick and not * Peter. * * copyright (c) 1999 Nick Gorham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ********************************************************************** * * $Id: SQLSetDescField.c,v 1.7 2009/02/18 17:59:08 lurcher Exp $ * * $Log: SQLSetDescField.c,v $ * Revision 1.7 2009/02/18 17:59:08 lurcher * Shift to using config.h, the compile lines were making it hard to spot warnings * * Revision 1.6 2007/05/25 16:42:32 lurcher * Sync up * * Revision 1.5 2005/11/21 17:25:43 lurcher * A few DM fixes for Oracle's ODBC driver * * Revision 1.4 2003/10/30 18:20:46 lurcher * * Fix broken thread protection * Remove SQLNumResultCols after execute, lease S4/S% to driver * Fix string overrun in SQLDriverConnect * Add initial support for Interix * * Revision 1.3 2003/02/27 12:19:40 lurcher * * Add the A functions as well as the W * * Revision 1.2 2002/12/05 17:44:31 lurcher * * Display unknown return values in return logging * * Revision 1.1.1.1 2001/10/17 16:40:07 lurcher * * First upload to SourceForge * * Revision 1.4 2001/07/03 09:30:41 nick * * Add ability to alter size of displayed message in the log * * Revision 1.3 2001/04/17 16:29:39 nick * * More checks and autotest fixes * * Revision 1.2 2001/04/12 17:43:36 nick * * Change logging and added autotest to odbctest * * Revision 1.1.1.1 2000/09/04 16:42:52 nick * Imported Sources * * Revision 1.7 1999/11/13 23:41:00 ngorham * * Alter the way DM logging works * Upgrade the Postgres driver to 6.4.6 * * Revision 1.6 1999/10/24 23:54:19 ngorham * * First part of the changes to the error reporting * * Revision 1.5 1999/09/21 22:34:25 ngorham * * Improve performance by removing unneeded logging calls when logging is * disabled * * Revision 1.4 1999/07/10 21:10:17 ngorham * * Adjust error sqlstate from driver manager, depending on requested * version (ODBC2/3) * * Revision 1.3 1999/07/04 21:05:08 ngorham * * Add LGPL Headers to code * * Revision 1.2 1999/06/30 23:56:55 ngorham * * Add initial thread safety code * * Revision 1.1.1.1 1999/05/29 13:41:08 sShandyb * first go at it * * Revision 1.1.1.1 1999/05/27 18:23:18 pharvey * Imported sources * * Revision 1.2 1999/05/04 22:41:12 nick * and another night ends * * Revision 1.1 1999/04/25 23:06:11 nick * Initial revision * * **********************************************************************/ #include <config.h> #include "drivermanager.h" static char const rcsid[]= "$RCSfile: SQLSetDescField.c,v $ $Revision: 1.7 $"; SQLRETURN SQLSetDescFieldA( SQLHDESC descriptor_handle, SQLSMALLINT rec_number, SQLSMALLINT field_identifier, SQLPOINTER value, SQLINTEGER buffer_length ) { return SQLSetDescField( descriptor_handle, rec_number, field_identifier, value, buffer_length ); } SQLRETURN SQLSetDescField( SQLHDESC descriptor_handle, SQLSMALLINT rec_number, SQLSMALLINT field_identifier, SQLPOINTER value, SQLINTEGER buffer_length ) { /* * not quite sure how the descriptor can be * allocated to a statement, all the documentation talks * about state transitions on statement states, but the * descriptor may be allocated with more than one statement * at one time. Which one should I check ? */ DMHDESC descriptor = (DMHDESC) descriptor_handle; SQLRETURN ret; SQLCHAR s1[ 100 + LOG_MESSAGE_LEN ]; int isStrField = 0; /* * check descriptor */ if ( !__validate_desc( descriptor )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: SQL_INVALID_HANDLE" ); return SQL_INVALID_HANDLE; } function_entry( descriptor ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tEntry:\ \n\t\t\tDescriptor = %p\ \n\t\t\tRec Number = %d\ \n\t\t\tField Ident = %s\ \n\t\t\tValue = %p\ \n\t\t\tBuffer Length = %d", descriptor, rec_number, __desc_attr_as_string( s1, field_identifier ), value, (int)buffer_length ); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } thread_protect( SQL_HANDLE_DESC, descriptor ); if ( descriptor -> connection -> state < STATE_C4 ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * check status of statements associated with this descriptor */ if( __check_stmt_from_desc( descriptor, STATE_S8 ) || __check_stmt_from_desc( descriptor, STATE_S9 ) || __check_stmt_from_desc( descriptor, STATE_S10 ) || __check_stmt_from_desc( descriptor, STATE_S11 ) || __check_stmt_from_desc( descriptor, STATE_S12 ) || __check_stmt_from_desc( descriptor, STATE_S13 ) || __check_stmt_from_desc( descriptor, STATE_S14 ) || __check_stmt_from_desc( descriptor, STATE_S15 )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( rec_number < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } switch ( field_identifier ) { /* Fixed-length fields: buffer_length is ignored */ case SQL_DESC_ALLOC_TYPE: case SQL_DESC_ARRAY_SIZE: case SQL_DESC_ARRAY_STATUS_PTR: case SQL_DESC_BIND_OFFSET_PTR: case SQL_DESC_BIND_TYPE: case SQL_DESC_COUNT: case SQL_DESC_ROWS_PROCESSED_PTR: case SQL_DESC_AUTO_UNIQUE_VALUE: case SQL_DESC_CASE_SENSITIVE: case SQL_DESC_CONCISE_TYPE: case SQL_DESC_DATA_PTR: case SQL_DESC_DATETIME_INTERVAL_CODE: case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_DISPLAY_SIZE: case SQL_DESC_FIXED_PREC_SCALE: case SQL_DESC_INDICATOR_PTR: case SQL_DESC_LENGTH: case SQL_DESC_NULLABLE: case SQL_DESC_NUM_PREC_RADIX: case SQL_DESC_OCTET_LENGTH: case SQL_DESC_OCTET_LENGTH_PTR: case SQL_DESC_PARAMETER_TYPE: case SQL_DESC_PRECISION: case SQL_DESC_ROWVER: case SQL_DESC_SCALE: case SQL_DESC_SEARCHABLE: case SQL_DESC_TYPE: case SQL_DESC_UNNAMED: case SQL_DESC_UNSIGNED: case SQL_DESC_UPDATABLE: isStrField = 0; break; /* Pointer to data: buffer_length must be valid */ case SQL_DESC_BASE_COLUMN_NAME: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_CATALOG_NAME: case SQL_DESC_LABEL: case SQL_DESC_LITERAL_PREFIX: case SQL_DESC_LITERAL_SUFFIX: case SQL_DESC_LOCAL_TYPE_NAME: case SQL_DESC_NAME: case SQL_DESC_SCHEMA_NAME: case SQL_DESC_TABLE_NAME: case SQL_DESC_TYPE_NAME: isStrField = 1; break; default: isStrField = buffer_length != SQL_IS_POINTER && buffer_length != SQL_IS_INTEGER && buffer_length != SQL_IS_UINTEGER && buffer_length != SQL_IS_SMALLINT && buffer_length != SQL_IS_USMALLINT; } if ( isStrField && buffer_length < 0 && buffer_length != SQL_NTS) { __post_internal_error( &descriptor -> error, ERROR_HY090, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_COUNT && (intptr_t)value < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_PARAMETER_TYPE && (intptr_t)value != SQL_PARAM_INPUT && (intptr_t)value != SQL_PARAM_OUTPUT && (intptr_t)value != SQL_PARAM_INPUT_OUTPUT && (intptr_t)value != SQL_PARAM_INPUT_OUTPUT_STREAM && (intptr_t)value != SQL_PARAM_OUTPUT_STREAM ) { __post_internal_error( &descriptor -> error, ERROR_HY105, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( CHECK_SQLSETDESCFIELD( descriptor -> connection )) { ret = SQLSETDESCFIELD( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); } else if ( CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { SQLWCHAR *s1 = NULL; if (isStrField) { s1 = ansi_to_unicode_alloc( value, buffer_length, descriptor -> connection, NULL ); if (SQL_NTS != buffer_length) { buffer_length *= sizeof(SQLWCHAR); } } else { s1 = value; } ret = SQLSETDESCFIELDW( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, s1, buffer_length ); if (isStrField) { if (s1) free(s1); } } else { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: IM001" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tExit:[%s]", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } return function_return( SQL_HANDLE_DESC, descriptor, ret ); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_634_2
crossvul-cpp_data_bad_3087_1
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Revised: 2/18/01 BAR -- added syntax for extracting single images from * multi-image TIFF files. * * New syntax is: sourceFileName,image# * * image# ranges from 0..<n-1> where n is the # of images in the file. * There may be no white space between the comma and the filename or * image number. * * Example: tiffcp source.tif,1 destination.tif * * Copies the 2nd image in source.tif to the destination. * ***** * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #include "tiffio.h" #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #if defined(VMS) # define unlink delete #endif #define streq(a,b) (strcmp(a,b) == 0) #define strneq(a,b,n) (strncmp(a,b,n) == 0) #define TRUE 1 #define FALSE 0 static int outtiled = -1; static uint32 tilewidth; static uint32 tilelength; static uint16 config; static uint16 compression; static uint16 predictor; static int preset; static uint16 fillorder; static uint16 orientation; static uint32 rowsperstrip; static uint32 g3opts; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 75; /* JPEG quality */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int defpreset = -1; static int tiffcp(TIFF*, TIFF*); static int processCompressOptions(char*); static void usage(void); static char comma = ','; /* (default) comma separator character */ static TIFF* bias = NULL; static int pageNum = 0; static int pageInSeq = 0; static int nextSrcImage (TIFF *tif, char **imageSpec) /* seek to the next image specified in *imageSpec returns 1 if success, 0 if no more images to process *imageSpec=NULL if subsequent images should be processed in sequence */ { if (**imageSpec == comma) { /* if not @comma, we've done all images */ char *start = *imageSpec + 1; tdir_t nextImage = (tdir_t)strtol(start, imageSpec, 0); if (start == *imageSpec) nextImage = TIFFCurrentDirectory (tif); if (**imageSpec) { if (**imageSpec == comma) { /* a trailing comma denotes remaining images in sequence */ if ((*imageSpec)[1] == '\0') *imageSpec = NULL; }else{ fprintf (stderr, "Expected a %c separated image # list after %s\n", comma, TIFFFileName (tif)); exit (-4); /* syntax error */ } } if (TIFFSetDirectory (tif, nextImage)) return 1; fprintf (stderr, "%s%c%d not found!\n", TIFFFileName(tif), comma, (int) nextImage); } return 0; } static TIFF* openSrcImage (char **imageSpec) /* imageSpec points to a pointer to a filename followed by optional ,image#'s Open the TIFF file and assign *imageSpec to either NULL if there are no images specified, or a pointer to the next image number text */ { TIFF *tif; char *fn = *imageSpec; *imageSpec = strchr (fn, comma); if (*imageSpec) { /* there is at least one image number specifier */ **imageSpec = '\0'; tif = TIFFOpen (fn, "r"); /* but, ignore any single trailing comma */ if (!(*imageSpec)[1]) {*imageSpec = NULL; return tif;} if (tif) { **imageSpec = comma; /* replace the comma */ if (!nextSrcImage(tif, imageSpec)) { TIFFClose (tif); tif = NULL; } } }else tif = TIFFOpen (fn, "r"); return tif; } int main(int argc, char* argv[]) { uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) -1; uint32 deftilelength = (uint32) -1; uint32 defrowsperstrip = (uint32) 0; uint64 diroff = 0; TIFF* in; TIFF* out; char mode[10]; char* mp = mode; int c; #if !HAVE_DECL_OPTARG extern int optind; extern char* optarg; #endif *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, ",:b:c:f:l:o:p:r:w:aistBLMC8x")) != -1) switch (c) { case ',': if (optarg[0] != '=') usage(); comma = optarg[1]; break; case 'b': /* this file is bias image subtracted from others */ if (bias) { fputs ("Only 1 bias image may be specified\n", stderr); exit (-2); } { uint16 samples = (uint16) -1; char **biasFn = &optarg; bias = openSrcImage (biasFn); if (!bias) exit (-5); if (TIFFIsTiled (bias)) { fputs ("Bias image must be organized in strips\n", stderr); exit (-7); } TIFFGetField(bias, TIFFTAG_SAMPLESPERPIXEL, &samples); if (samples != 1) { fputs ("Bias image must be monochrome\n", stderr); exit (-7); } } break; case 'a': /* append to output */ mode[0] = 'a'; break; case 'c': /* compression scheme */ if (!processCompressOptions(optarg)) usage(); break; case 'f': /* fill order */ if (streq(optarg, "lsb2msb")) deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) deffillorder = FILLORDER_MSB2LSB; else usage(); break; case 'i': /* ignore errors */ ignore = TRUE; break; case 'l': /* tile length */ outtiled = TRUE; deftilelength = atoi(optarg); break; case 'o': /* initial directory offset */ diroff = strtoul(optarg, NULL, 0); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) defconfig = PLANARCONFIG_CONTIG; else usage(); break; case 'r': /* rows/strip */ defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'w': /* tile width */ outtiled = TRUE; deftilewidth = atoi(optarg); break; case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; case '8': *mp++ = '8'; *mp = '\0'; break; case 'x': pageInSeq = 1; break; case '?': usage(); /*NOTREACHED*/ } if (argc - optind < 2) usage(); out = TIFFOpen(argv[argc-1], mode); if (out == NULL) return (-2); if ((argc - optind) == 2) pageNum = -1; for (; optind < argc-1 ; optind++) { char *imageCursor = argv[optind]; in = openSrcImage (&imageCursor); if (in == NULL) { (void) TIFFClose(out); return (-3); } if (diroff != 0 && !TIFFSetSubDirectory(in, diroff)) { TIFFError(TIFFFileName(in), "Error, setting subdirectory at " TIFF_UINT64_FORMAT, diroff); (void) TIFFClose(in); (void) TIFFClose(out); return (1); } for (;;) { config = defconfig; compression = defcompression; predictor = defpredictor; preset = defpreset; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (!tiffcp(in, out) || !TIFFWriteDirectory(out)) { (void) TIFFClose(in); (void) TIFFClose(out); return (1); } if (imageCursor) { /* seek next image directory */ if (!nextSrcImage(in, &imageCursor)) break; }else if (!TIFFReadDirectory(in)) break; } (void) TIFFClose(in); } (void) TIFFClose(out); return (0); } static void processZIPOptions(char* cp) { if ( (cp = strchr(cp, ':')) ) { do { cp++; if (isdigit((int)*cp)) defpredictor = atoi(cp); else if (*cp == 'p') defpreset = atoi(++cp); else usage(); } while( (cp = strchr(cp, ':')) ); } } static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { if (streq(opt, "none")) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { char* cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while( cp ) { if (isdigit((int)cp[1])) quality = atoi(cp+1); else if (cp[1] == 'r' ) jpegcolormode = JPEGCOLORMODE_RAW; else usage(); cp = strchr(cp+1,':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { char* cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { processZIPOptions(opt); defcompression = COMPRESSION_ADOBE_DEFLATE; } else if (strneq(opt, "lzma", 4)) { processZIPOptions(opt); defcompression = COMPRESSION_LZMA; } else if (strneq(opt, "jbig", 4)) { defcompression = COMPRESSION_JBIG; } else if (strneq(opt, "sgilog", 6)) { defcompression = COMPRESSION_SGILOG; } else return (0); return (1); } char* stuff[] = { "usage: tiffcp [options] input... output", "where options are:", " -a append to output instead of overwriting", " -o offset set initial directory offset", " -p contig pack samples contiguously (e.g. RGBRGB...)", " -p separate store samples separately (e.g. RRR...GGG...BBB...)", " -s write output in strips", " -t write output in tiles", " -x force the merged tiff pages in sequence", " -8 write BigTIFF instead of default ClassicTIFF", " -B write big-endian instead of native byte order", " -L write little-endian instead of native byte order", " -M disable use of memory-mapped files", " -C disable strip chopping", " -i ignore read errors", " -b file[,#] bias (dark) monochrome image to be subtracted from all others", " -,=% use % rather than , to separate image #'s (per Note below)", "", " -r # make each strip have no more than # rows", " -w # set output tile width (pixels)", " -l # set output tile length (pixels)", "", " -f lsb2msb force lsb-to-msb FillOrder for output", " -f msb2lsb force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] compress output with deflate encoding", " -c lzma[:opts] compress output with LZMA2 encoding", " -c jpeg[:opts] compress output with JPEG encoding", " -c jbig compress output with ISO JBIG encoding", " -c packbits compress output with packbits encoding", " -c g3[:opts] compress output with CCITT Group 3 encoding", " -c g4 compress output with CCITT Group 4 encoding", " -c sgilog compress output with SGILOG encoding", " -c none use no compression algorithm on output", "", "Group 3 options:", " 1d use default CCITT Group 3 1D-encoding", " 2d use optional CCITT Group 3 2D-encoding", " fill byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", "", "JPEG options:", " # set compression quality level (0-100, default 75)", " r output color image as RGB rather than YCbCr", "For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality", "", "LZW, Deflate (ZIP) and LZMA2 options:", " # set predictor value", " p# set compression level (preset)", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing,", "-c zip:3:p9 for Deflate encoding with maximum compression level and floating", "point predictor.", "", "Note that input filenames may be of the form filename,x,y,z", "where x, y, and z specify image numbers in the filename to copy.", "example: tiffcp -c none -b esp.tif,1 esp.tif,0 test.tif", " subtract 2nd image in esp.tif from 1st yielding uncompressed result test.tif", NULL }; static void usage(void) { char buf[BUFSIZ]; int i; setbuf(stderr, buf); fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i = 0; stuff[i] != NULL; i++) fprintf(stderr, "%s\n", stuff[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped.", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) typedef int (*copyFunc) (TIFF* in, TIFF* out, uint32 l, uint32 w, uint16 samplesperpixel); static copyFunc pickCopyFunc(TIFF*, TIFF*, uint16, uint16); /* PODD */ static int tiffcp(TIFF* in, TIFF* out) { uint16 bitspersample, samplesperpixel = 1; uint16 input_compression, input_photometric = PHOTOMETRIC_MINISBLACK; copyFunc cf; uint32 width, length; struct cpTag* p; CopyField(TIFFTAG_IMAGEWIDTH, width); CopyField(TIFFTAG_IMAGELENGTH, length); CopyField(TIFFTAG_BITSPERSAMPLE, bitspersample); CopyField(TIFFTAG_SAMPLESPERPIXEL, samplesperpixel); if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else CopyField(TIFFTAG_COMPRESSION, compression); TIFFGetFieldDefaulted(in, TIFFTAG_COMPRESSION, &input_compression); TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric); if (input_compression == COMPRESSION_JPEG) { /* Force conversion to RGB */ TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else if (input_photometric == PHOTOMETRIC_YCBCR) { /* Otherwise, can't handle subsampled input */ uint16 subsamplinghor,subsamplingver; TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor, &subsamplingver); if (subsamplinghor!=1 || subsamplingver!=1) { fprintf(stderr, "tiffcp: %s: Can't copy/convert subsampled image.\n", TIFFFileName(in)); return FALSE; } } if (compression == COMPRESSION_JPEG) { if (input_photometric == PHOTOMETRIC_RGB && jpegcolormode == JPEGCOLORMODE_RGB) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, samplesperpixel == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else if (input_compression == COMPRESSION_JPEG && samplesperpixel == 3 ) { /* RGB conversion was forced above hence the output will be of the same type */ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else CopyTag(TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT); if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* * Will copy `Orientation' tag from input image */ TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); switch (orientation) { case ORIENTATION_BOTRIGHT: case ORIENTATION_RIGHTBOT: /* XXX */ TIFFWarning(TIFFFileName(in), "using bottom-left orientation"); orientation = ORIENTATION_BOTLEFT; /* fall thru... */ case ORIENTATION_LEFTBOT: /* XXX */ case ORIENTATION_BOTLEFT: break; case ORIENTATION_TOPRIGHT: case ORIENTATION_RIGHTTOP: /* XXX */ default: TIFFWarning(TIFFFileName(in), "using top-left orientation"); orientation = ORIENTATION_TOPLEFT; /* fall thru... */ case ORIENTATION_LEFTTOP: /* XXX */ case ORIENTATION_TOPLEFT: break; } TIFFSetField(out, TIFFTAG_ORIENTATION, orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) -1) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) -1) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) { rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); } if (rowsperstrip > length && rowsperstrip != (uint32)-1) rowsperstrip = length; } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (samplesperpixel <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode); break; case COMPRESSION_JBIG: CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); CopyTag(TIFFTAG_FAXDCS, 1, TIFF_ASCII); break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: case COMPRESSION_LZMA: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); if (preset != -1) { if (compression == COMPRESSION_ADOBE_DEFLATE || compression == COMPRESSION_DEFLATE) TIFFSetField(out, TIFFTAG_ZIPQUALITY, preset); else if (compression == COMPRESSION_LZMA) TIFFSetField(out, TIFFTAG_LZMAPRESET, preset); } break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); cp++; inknameslen += (strlen(cp) + 1); ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (pageInSeq == 1) { if (pageNum < 0) /* only one input file */ { if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); } else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } else { if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); cf = pickCopyFunc(in, out, bitspersample, samplesperpixel); return (cf ? (*cf)(in, out, length, width, samplesperpixel) : FALSE); } /* * Copy Functions. */ #define DECLAREcpFunc(x) \ static int x(TIFF* in, TIFF* out, \ uint32 imagelength, uint32 imagewidth, tsample_t spp) #define DECLAREreadFunc(x) \ static int x(TIFF* in, \ uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) typedef int (*readFunc)(TIFF*, uint8*, uint32, uint32, tsample_t); #define DECLAREwriteFunc(x) \ static int x(TIFF* out, \ uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) typedef int (*writeFunc)(TIFF*, uint8*, uint32, uint32, tsample_t); /* * Contig -> contig by scanline for rows/strip change. */ DECLAREcpFunc(cpContig2ContigByRow) { tsize_t scanlinesize = TIFFScanlineSize(in); tdata_t buf; uint32 row; buf = _TIFFmalloc(scanlinesize); if (!buf) return 0; _TIFFmemset(buf, 0, scanlinesize); (void) imagewidth; (void) spp; for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFWriteScanline(out, buf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } _TIFFfree(buf); return 1; bad: _TIFFfree(buf); return 0; } typedef void biasFn (void *image, void *bias, uint32 pixels); #define subtract(bits) \ static void subtract##bits (void *i, void *b, uint32 pixels)\ {\ uint##bits *image = i;\ uint##bits *bias = b;\ while (pixels--) {\ *image = *image > *bias ? *image-*bias : 0;\ image++, bias++; \ } \ } subtract(8) subtract(16) subtract(32) static biasFn *lineSubtractFn (unsigned bits) { switch (bits) { case 8: return subtract8; case 16: return subtract16; case 32: return subtract32; } return NULL; } /* * Contig -> contig by scanline while subtracting a bias image. */ DECLAREcpFunc(cpBiasedContig2Contig) { if (spp == 1) { tsize_t biasSize = TIFFScanlineSize(bias); tsize_t bufSize = TIFFScanlineSize(in); tdata_t buf, biasBuf; uint32 biasWidth = 0, biasLength = 0; TIFFGetField(bias, TIFFTAG_IMAGEWIDTH, &biasWidth); TIFFGetField(bias, TIFFTAG_IMAGELENGTH, &biasLength); if (biasSize == bufSize && imagelength == biasLength && imagewidth == biasWidth) { uint16 sampleBits = 0; biasFn *subtractLine; TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &sampleBits); subtractLine = lineSubtractFn (sampleBits); if (subtractLine) { uint32 row; buf = _TIFFmalloc(bufSize); biasBuf = _TIFFmalloc(bufSize); for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFReadScanline(bias, biasBuf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read biased scanline %lu", (unsigned long) row); goto bad; } subtractLine (buf, biasBuf, imagewidth); if (TIFFWriteScanline(out, buf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } _TIFFfree(buf); _TIFFfree(biasBuf); TIFFSetDirectory(bias, TIFFCurrentDirectory(bias)); /* rewind */ return 1; bad: _TIFFfree(buf); _TIFFfree(biasBuf); return 0; } else { TIFFError(TIFFFileName(in), "No support for biasing %d bit pixels\n", sampleBits); return 0; } } TIFFError(TIFFFileName(in), "Bias image %s,%d\nis not the same size as %s,%d\n", TIFFFileName(bias), TIFFCurrentDirectory(bias), TIFFFileName(in), TIFFCurrentDirectory(in)); return 0; } else { TIFFError(TIFFFileName(in), "Can't bias %s,%d as it has >1 Sample/Pixel\n", TIFFFileName(in), TIFFCurrentDirectory(in)); return 0; } } /* * Strip -> strip for change in encoding. */ DECLAREcpFunc(cpDecodedStrips) { tsize_t stripsize = TIFFStripSize(in); tdata_t buf = _TIFFmalloc(stripsize); (void) imagewidth; (void) spp; if (buf) { tstrip_t s, ns = TIFFNumberOfStrips(in); uint32 row = 0; _TIFFmemset(buf, 0, stripsize); for (s = 0; s < ns && row < imagelength; s++) { tsize_t cc = (row + rowsperstrip > imagelength) ? TIFFVStripSize(in, imagelength - row) : stripsize; if (TIFFReadEncodedStrip(in, s, buf, cc) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu", (unsigned long) s); goto bad; } if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %lu", (unsigned long) s); goto bad; } row += rowsperstrip; } _TIFFfree(buf); return 1; } else { TIFFError(TIFFFileName(in), "Error, can't allocate memory buffer of size %lu " "to read strips", (unsigned long) stripsize); return 0; } bad: _TIFFfree(buf); return 0; } /* * Separate -> separate by row for rows/strip change. */ DECLAREcpFunc(cpSeparate2SeparateByRow) { tsize_t scanlinesize = TIFFScanlineSize(in); tdata_t buf; uint32 row; tsample_t s; (void) imagewidth; buf = _TIFFmalloc(scanlinesize); if (!buf) return 0; _TIFFmemset(buf, 0, scanlinesize); for (s = 0; s < spp; s++) { for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFWriteScanline(out, buf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } } _TIFFfree(buf); return 1; bad: _TIFFfree(buf); return 0; } /* * Contig -> separate by row. */ DECLAREcpFunc(cpContig2SeparateByRow) { tsize_t scanlinesizein = TIFFScanlineSize(in); tsize_t scanlinesizeout = TIFFScanlineSize(out); tdata_t inbuf; tdata_t outbuf; register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; inbuf = _TIFFmalloc(scanlinesizein); outbuf = _TIFFmalloc(scanlinesizeout); if (!inbuf || !outbuf) goto bad; _TIFFmemset(inbuf, 0, scanlinesizein); _TIFFmemset(outbuf, 0, scanlinesizeout); /* unpack channels */ for (s = 0; s < spp; s++) { for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = ((uint8*)inbuf) + s; outp = (uint8*)outbuf; for (n = imagewidth; n-- > 0;) { *outp++ = *inp; inp += spp; } if (TIFFWriteScanline(out, outbuf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; } /* * Separate -> contig by row. */ DECLAREcpFunc(cpSeparate2ContigByRow) { tsize_t scanlinesizein = TIFFScanlineSize(in); tsize_t scanlinesizeout = TIFFScanlineSize(out); tdata_t inbuf; tdata_t outbuf; register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; inbuf = _TIFFmalloc(scanlinesizein); outbuf = _TIFFmalloc(scanlinesizeout); if (!inbuf || !outbuf) goto bad; _TIFFmemset(inbuf, 0, scanlinesizein); _TIFFmemset(outbuf, 0, scanlinesizeout); for (row = 0; row < imagelength; row++) { /* merge channels */ for (s = 0; s < spp; s++) { if (TIFFReadScanline(in, inbuf, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = (uint8*)inbuf; outp = ((uint8*)outbuf) + s; for (n = imagewidth; n-- > 0;) { *outp = *inp++; outp += spp; } } if (TIFFWriteScanline(out, outbuf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; } static void cpStripToTile(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int64 inskew) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) *out++ = *in++; out += outskew; in += inskew; } } static void cpContigBufToSeparateBuf(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp, int bytes_per_sample ) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) { int n = bytes_per_sample; while( n-- ) { *out++ = *in++; } in += (spp-1) * bytes_per_sample; } out += outskew; in += inskew; } } static void cpSeparateBufToContigBuf(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp, int bytes_per_sample) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) { int n = bytes_per_sample; while( n-- ) { *out++ = *in++; } out += (spp-1)*bytes_per_sample; } out += outskew; in += inskew; } } static int cpImage(TIFF* in, TIFF* out, readFunc fin, writeFunc fout, uint32 imagelength, uint32 imagewidth, tsample_t spp) { int status = 0; tdata_t buf = NULL; tsize_t scanlinesize = TIFFRasterScanlineSize(in); tsize_t bytes = scanlinesize * (tsize_t)imagelength; /* * XXX: Check for integer overflow. */ if (scanlinesize && imagelength && bytes / (tsize_t)imagelength == scanlinesize) { buf = _TIFFmalloc(bytes); if (buf) { if ((*fin)(in, (uint8*)buf, imagelength, imagewidth, spp)) { status = (*fout)(out, (uint8*)buf, imagelength, imagewidth, spp); } _TIFFfree(buf); } else { TIFFError(TIFFFileName(in), "Error, can't allocate space for image buffer"); } } else { TIFFError(TIFFFileName(in), "Error, no space for image buffer"); } return status; } DECLAREreadFunc(readContigStripsIntoBuffer) { tsize_t scanlinesize = TIFFScanlineSize(in); uint8* bufp = buf; uint32 row; (void) imagewidth; (void) spp; for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, (tdata_t) bufp, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); return 0; } bufp += scanlinesize; } return 1; } DECLAREreadFunc(readSeparateStripsIntoBuffer) { int status = 1; tsize_t scanlinesize = TIFFScanlineSize(in); tdata_t scanline; if (!scanlinesize) return 0; scanline = _TIFFmalloc(scanlinesize); if (!scanline) return 0; _TIFFmemset(scanline, 0, scanlinesize); (void) imagewidth; if (scanline) { uint8* bufp = (uint8*) buf; uint32 row; tsample_t s; for (row = 0; row < imagelength; row++) { /* merge channels */ for (s = 0; s < spp; s++) { uint8* bp = bufp + s; tsize_t n = scanlinesize; uint8* sbuf = scanline; if (TIFFReadScanline(in, scanline, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); status = 0; goto done; } while (n-- > 0) *bp = *sbuf++, bp += spp; } bufp += scanlinesize * spp; } } done: _TIFFfree(scanline); return status; } DECLAREreadFunc(readContigTilesIntoBuffer) { int status = 1; tsize_t tilesize = TIFFTileSize(in); tdata_t tilebuf; uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int64 iskew = (int64)imagew - (int64)tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; tilebuf = _TIFFmalloc(tilesize); if (tilebuf == 0) return 0; _TIFFmemset(tilebuf, 0, tilesize); (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth && colb < imagew; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb > iskew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } DECLAREreadFunc(readSeparateTilesIntoBuffer) { int status = 1; uint32 imagew = TIFFRasterScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew*spp; tsize_t tilesize = TIFFTileSize(in); tdata_t tilebuf; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; uint16 bps = 0, bytes_per_sample; tilebuf = _TIFFmalloc(tilesize); if (tilebuf == 0) return 0; _TIFFmemset(tilebuf, 0, tilesize); (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); if( bps == 0 ) { TIFFError(TIFFFileName(in), "Error, cannot read BitsPerSample"); status = 0; goto done; } if( (bps % 8) != 0 ) { TIFFError(TIFFFileName(in), "Error, cannot handle BitsPerSample that is not a multiple of 8"); status = 0; goto done; } bytes_per_sample = bps/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { if (TIFFReadTile(in, tilebuf, col, row, 0, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; goto done; } /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew*spp > imagew) { uint32 width = imagew - colb; int oskew = tilew*spp - width; cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, width/(spp*bytes_per_sample), oskew + iskew, oskew/spp, spp, bytes_per_sample); } else cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, tw, iskew, 0, spp, bytes_per_sample); } colb += tilew*spp; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } DECLAREwriteFunc(writeBufferToContigStrips) { uint32 row, rowsperstrip; tstrip_t strip = 0; (void) imagewidth; (void) spp; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { uint32 nrows = (row+rowsperstrip > imagelength) ? imagelength-row : rowsperstrip; tsize_t stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 0; } buf += stripsize; } return 1; } DECLAREwriteFunc(writeBufferToSeparateStrips) { uint32 rowsize = imagewidth * spp; uint32 rowsperstrip; tsize_t stripsize = TIFFStripSize(out); tdata_t obuf; tstrip_t strip = 0; tsample_t s; obuf = _TIFFmalloc(stripsize); if (obuf == NULL) return (0); _TIFFmemset(obuf, 0, stripsize); (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (s = 0; s < spp; s++) { uint32 row; for (row = 0; row < imagelength; row += rowsperstrip) { uint32 nrows = (row+rowsperstrip > imagelength) ? imagelength-row : rowsperstrip; tsize_t stripsize = TIFFVStripSize(out, nrows); cpContigBufToSeparateBuf( obuf, (uint8*) buf + row*rowsize + s, nrows, imagewidth, 0, 0, spp, 1); if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 0; } } } _TIFFfree(obuf); return 1; } DECLAREwriteFunc(writeBufferToContigTiles) { uint32 imagew = TIFFScanlineSize(out); uint32 tilew = TIFFTileRowSize(out); int iskew = imagew - tilew; tsize_t tilesize = TIFFTileSize(out); tdata_t obuf; uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; (void) spp; obuf = _TIFFmalloc(TIFFTileSize(out)); if (obuf == NULL) return 0; _TIFFmemset(obuf, 0, tilesize); (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); for (row = 0; row < imagelength; row += tilelength) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth && colb < imagew; col += tw) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = imagew - colb; int oskew = tilew - width; cpStripToTile(obuf, bufp + colb, nrow, width, oskew, oskew + iskew); } else cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew); if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(obuf); return 0; } colb += tilew; } bufp += nrow * imagew; } _TIFFfree(obuf); return 1; } DECLAREwriteFunc(writeBufferToSeparateTiles) { uint32 imagew = TIFFScanlineSize(out); tsize_t tilew = TIFFTileRowSize(out); uint32 iimagew = TIFFRasterScanlineSize(out); int iskew = iimagew - tilew*spp; tsize_t tilesize = TIFFTileSize(out); tdata_t obuf; uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; uint16 bps = 0, bytes_per_sample; obuf = _TIFFmalloc(TIFFTileSize(out)); if (obuf == NULL) return 0; _TIFFmemset(obuf, 0, tilesize); (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); if( bps == 0 ) { TIFFError(TIFFFileName(out), "Error, cannot read BitsPerSample"); _TIFFfree(obuf); return 0; } if( (bps % 8) != 0 ) { TIFFError(TIFFFileName(out), "Error, cannot handle BitsPerSample that is not a multiple of 8"); _TIFFfree(obuf); return 0; } bytes_per_sample = bps/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = (imagew - colb); int oskew = tilew - width; cpContigBufToSeparateBuf(obuf, bufp + (colb*spp) + s, nrow, width/bytes_per_sample, oskew, (oskew*spp)+iskew, spp, bytes_per_sample); } else cpContigBufToSeparateBuf(obuf, bufp + (colb*spp) + s, nrow, tilewidth, 0, iskew, spp, bytes_per_sample); if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 0; } } colb += tilew; } bufp += nrow * iimagew; } _TIFFfree(obuf); return 1; } /* * Contig strips -> contig tiles. */ DECLAREcpFunc(cpContigStrips2ContigTiles) { return cpImage(in, out, readContigStripsIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Contig strips -> separate tiles. */ DECLAREcpFunc(cpContigStrips2SeparateTiles) { return cpImage(in, out, readContigStripsIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Separate strips -> contig tiles. */ DECLAREcpFunc(cpSeparateStrips2ContigTiles) { return cpImage(in, out, readSeparateStripsIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Separate strips -> separate tiles. */ DECLAREcpFunc(cpSeparateStrips2SeparateTiles) { return cpImage(in, out, readSeparateStripsIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Contig strips -> contig tiles. */ DECLAREcpFunc(cpContigTiles2ContigTiles) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Contig tiles -> separate tiles. */ DECLAREcpFunc(cpContigTiles2SeparateTiles) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Separate tiles -> contig tiles. */ DECLAREcpFunc(cpSeparateTiles2ContigTiles) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Separate tiles -> separate tiles (tile dimension change). */ DECLAREcpFunc(cpSeparateTiles2SeparateTiles) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Contig tiles -> contig tiles (tile dimension change). */ DECLAREcpFunc(cpContigTiles2ContigStrips) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToContigStrips, imagelength, imagewidth, spp); } /* * Contig tiles -> separate strips. */ DECLAREcpFunc(cpContigTiles2SeparateStrips) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToSeparateStrips, imagelength, imagewidth, spp); } /* * Separate tiles -> contig strips. */ DECLAREcpFunc(cpSeparateTiles2ContigStrips) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToContigStrips, imagelength, imagewidth, spp); } /* * Separate tiles -> separate strips. */ DECLAREcpFunc(cpSeparateTiles2SeparateStrips) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToSeparateStrips, imagelength, imagewidth, spp); } /* * Select the appropriate copy function to use. */ static copyFunc pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel) { uint16 shortv; uint32 w, l, tw, tl; int bychunk; (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv); if (shortv != config && bitspersample != 8 && samplesperpixel > 1) { fprintf(stderr, "%s: Cannot handle different planar configuration w/ bits/sample != 8\n", TIFFFileName(in)); return (NULL); } TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l); if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) { uint32 irps = (uint32) -1L; TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps); /* if biased, force decoded copying to allow image subtraction */ bychunk = !bias && (rowsperstrip == irps); }else{ /* either in or out is tiled */ if (bias) { fprintf(stderr, "%s: Cannot handle tiled configuration w/bias image\n", TIFFFileName(in)); return (NULL); } if (TIFFIsTiled(out)) { if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw)) tw = w; if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl)) tl = l; bychunk = (tw == tilewidth && tl == tilelength); } else { /* out's not, so in must be tiled */ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); bychunk = (tw == w && tl == rowsperstrip); } } #define T 1 #define F 0 #define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e))) switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) { /* Strips -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T): return cpContigStrips2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T): return cpContigStrips2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T): return cpSeparateStrips2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T): return cpSeparateStrips2SeparateTiles; /* Tiles -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T): return cpContigTiles2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T): return cpContigTiles2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T): return cpSeparateTiles2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T): return cpSeparateTiles2SeparateTiles; /* Tiles -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T): return cpContigTiles2ContigStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T): return cpContigTiles2SeparateStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T): return cpSeparateTiles2ContigStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T): return cpSeparateTiles2SeparateStrips; /* Strips -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F): return bias ? cpBiasedContig2Contig : cpContig2ContigByRow; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T): return cpDecodedStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T): return cpContig2SeparateByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T): return cpSeparate2ContigByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T): return cpSeparate2SeparateByRow; } #undef pack #undef F #undef T fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n", TIFFFileName(in)); return (NULL); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3087_1
crossvul-cpp_data_bad_339_6
/* * pkcs15-sc-hsm.c : Initialize PKCS#15 emulation * * Copyright (C) 2012 Andreas Schwier, CardContact, Minden, Germany * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #include "asn1.h" #include "common/compat_strlcpy.h" #include "common/compat_strnlen.h" #include "card-sc-hsm.h" extern struct sc_aid sc_hsm_aid; void sc_hsm_set_serialnr(sc_card_t *card, char *serial); static struct ec_curve curves[] = { { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x01", 8}, // secp192r1 aka prime192r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 24}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 24}, { (unsigned char *) "\x64\x21\x05\x19\xE5\x9C\x80\xE7\x0F\xA7\xE9\xAB\x72\x24\x30\x49\xFE\xB8\xDE\xEC\xC1\x46\xB9\xB1", 24}, { (unsigned char *) "\x04\x18\x8D\xA8\x0E\xB0\x30\x90\xF6\x7C\xBF\x20\xEB\x43\xA1\x88\x00\xF4\xFF\x0A\xFD\x82\xFF\x10\x12\x07\x19\x2B\x95\xFF\xC8\xDA\x78\x63\x10\x11\xED\x6B\x24\xCD\xD5\x73\xF9\x77\xA1\x1E\x79\x48\x11", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x99\xDE\xF8\x36\x14\x6B\xC9\xB1\xB4\xD2\x28\x31", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8}, // secp256r1 aka prime256r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 32}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 32}, { (unsigned char *) "\x5A\xC6\x35\xD8\xAA\x3A\x93\xE7\xB3\xEB\xBD\x55\x76\x98\x86\xBC\x65\x1D\x06\xB0\xCC\x53\xB0\xF6\x3B\xCE\x3C\x3E\x27\xD2\x60\x4B", 32}, { (unsigned char *) "\x04\x6B\x17\xD1\xF2\xE1\x2C\x42\x47\xF8\xBC\xE6\xE5\x63\xA4\x40\xF2\x77\x03\x7D\x81\x2D\xEB\x33\xA0\xF4\xA1\x39\x45\xD8\x98\xC2\x96\x4F\xE3\x42\xE2\xFE\x1A\x7F\x9B\x8E\xE7\xEB\x4A\x7C\x0F\x9E\x16\x2B\xCE\x33\x57\x6B\x31\x5E\xCE\xCB\xB6\x40\x68\x37\xBF\x51\xF5", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBC\xE6\xFA\xAD\xA7\x17\x9E\x84\xF3\xB9\xCA\xC2\xFC\x63\x25\x51", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x03", 9}, // brainpoolP192r1 { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x30\x93\xD1\x8D\xB7\x8F\xCE\x47\x6D\xE1\xA8\x62\x97", 24}, { (unsigned char *) "\x6A\x91\x17\x40\x76\xB1\xE0\xE1\x9C\x39\xC0\x31\xFE\x86\x85\xC1\xCA\xE0\x40\xE5\xC6\x9A\x28\xEF", 24}, { (unsigned char *) "\x46\x9A\x28\xEF\x7C\x28\xCC\xA3\xDC\x72\x1D\x04\x4F\x44\x96\xBC\xCA\x7E\xF4\x14\x6F\xBF\x25\xC9", 24}, { (unsigned char *) "\x04\xC0\xA0\x64\x7E\xAA\xB6\xA4\x87\x53\xB0\x33\xC5\x6C\xB0\xF0\x90\x0A\x2F\x5C\x48\x53\x37\x5F\xD6\x14\xB6\x90\x86\x6A\xBD\x5B\xB8\x8B\x5F\x48\x28\xC1\x49\x00\x02\xE6\x77\x3F\xA2\xFA\x29\x9B\x8F", 49}, { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x2F\x9E\x9E\x91\x6B\x5B\xE8\xF1\x02\x9A\xC4\xAC\xC1", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x05", 9}, // brainpoolP224r1 { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF", 28}, { (unsigned char *) "\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA\xD2\x9F\x43", 28}, { (unsigned char *) "\x25\x80\xF6\x3C\xCF\xE4\x41\x38\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66\xDB\xB3\x72\x38\x6C\x40\x0B", 28}, { (unsigned char *) "\x04\x0D\x90\x29\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02\xCD", 57}, { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD0\xFB\x98\xD1\x16\xBC\x4B\x6D\xDE\xBC\xA3\xA5\xA7\x93\x9F", 28}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x07", 9}, // brainpoolP256r1 { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x72\x6E\x3B\xF6\x23\xD5\x26\x20\x28\x20\x13\x48\x1D\x1F\x6E\x53\x77", 32}, { (unsigned char *) "\x7D\x5A\x09\x75\xFC\x2C\x30\x57\xEE\xF6\x75\x30\x41\x7A\xFF\xE7\xFB\x80\x55\xC1\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9", 32}, { (unsigned char *) "\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9\xBB\xD7\x7C\xBF\x95\x84\x16\x29\x5C\xF7\xE1\xCE\x6B\xCC\xDC\x18\xFF\x8C\x07\xB6", 32}, { (unsigned char *) "\x04\x8B\xD2\xAE\xB9\xCB\x7E\x57\xCB\x2C\x4B\x48\x2F\xFC\x81\xB7\xAF\xB9\xDE\x27\xE1\xE3\xBD\x23\xC2\x3A\x44\x53\xBD\x9A\xCE\x32\x62\x54\x7E\xF8\x35\xC3\xDA\xC4\xFD\x97\xF8\x46\x1A\x14\x61\x1D\xC9\xC2\x77\x45\x13\x2D\xED\x8E\x54\x5C\x1D\x54\xC7\x2F\x04\x69\x97", 65}, { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x71\x8C\x39\x7A\xA3\xB5\x61\xA6\xF7\x90\x1E\x0E\x82\x97\x48\x56\xA7", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x09", 9}, // brainpoolP320r1 { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA6\xF6\xF4\x0D\xEF\x4F\x92\xB9\xEC\x78\x93\xEC\x28\xFC\xD4\x12\xB1\xF1\xB3\x2E\x27", 40}, { (unsigned char *) "\x3E\xE3\x0B\x56\x8F\xBA\xB0\xF8\x83\xCC\xEB\xD4\x6D\x3F\x3B\xB8\xA2\xA7\x35\x13\xF5\xEB\x79\xDA\x66\x19\x0E\xB0\x85\xFF\xA9\xF4\x92\xF3\x75\xA9\x7D\x86\x0E\xB4", 40}, { (unsigned char *) "\x52\x08\x83\x94\x9D\xFD\xBC\x42\xD3\xAD\x19\x86\x40\x68\x8A\x6F\xE1\x3F\x41\x34\x95\x54\xB4\x9A\xCC\x31\xDC\xCD\x88\x45\x39\x81\x6F\x5E\xB4\xAC\x8F\xB1\xF1\xA6", 40}, { (unsigned char *) "\x04\x43\xBD\x7E\x9A\xFB\x53\xD8\xB8\x52\x89\xBC\xC4\x8E\xE5\xBF\xE6\xF2\x01\x37\xD1\x0A\x08\x7E\xB6\xE7\x87\x1E\x2A\x10\xA5\x99\xC7\x10\xAF\x8D\x0D\x39\xE2\x06\x11\x14\xFD\xD0\x55\x45\xEC\x1C\xC8\xAB\x40\x93\x24\x7F\x77\x27\x5E\x07\x43\xFF\xED\x11\x71\x82\xEA\xA9\xC7\x78\x77\xAA\xAC\x6A\xC7\xD3\x52\x45\xD1\x69\x2E\x8E\xE1", 81}, { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA5\xB6\x8F\x12\xA3\x2D\x48\x2E\xC7\xEE\x86\x58\xE9\x86\x91\x55\x5B\x44\xC5\x93\x11", 40}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x1F", 5}, // secp192k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xEE\x37", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03", 24}, { (unsigned char *) "\x04\xDB\x4F\xF1\x0E\xC0\x57\xE9\xAE\x26\xB0\x7D\x02\x80\xB7\xF4\x34\x1D\xA5\xD1\xB1\xEA\xE0\x6C\x7D\x9B\x2F\x2F\x6D\x9C\x56\x28\xA7\x84\x41\x63\xD0\x15\xBE\x86\x34\x40\x82\xAA\x88\xD9\x5E\x2F\x9D", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\x26\xF2\xFC\x17\x0F\x69\x46\x6A\x74\xDE\xFD\x8D", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x0A", 5}, // secp256k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFC\x2F", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07", 32}, { (unsigned char *) "\x04\x79\xBE\x66\x7E\xF9\xDC\xBB\xAC\x55\xA0\x62\x95\xCE\x87\x0B\x07\x02\x9B\xFC\xDB\x2D\xCE\x28\xD9\x59\xF2\x81\x5B\x16\xF8\x17\x98\x48\x3A\xDA\x77\x26\xA3\xC4\x65\x5D\xA4\xFB\xFC\x0E\x11\x08\xA8\xFD\x17\xB4\x48\xA6\x85\x54\x19\x9C\x47\xD0\x8F\xFB\x10\xD4\xB8", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B\xBF\xD2\x5E\x8C\xD0\x36\x41\x41", 32}, { (unsigned char *) "\x01", 1} }, { { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0} } }; #define C_ASN1_CVC_PUBKEY_SIZE 10 static const struct sc_asn1_entry c_asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE] = { { "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL }, { "primeOrModulus", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientAorExponent", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 2, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientB", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 3, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "basePointG", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 4, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "order", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 5, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "cofactor", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 7, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "modulusSize", SC_ASN1_INTEGER, SC_ASN1_UNI | SC_ASN1_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_BODY_SIZE 5 static const struct sc_asn1_entry c_asn1_cvc_body[C_ASN1_CVC_BODY_SIZE] = { { "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL }, { "certificationAuthorityReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL }, { "certificateHolderReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVCERT_SIZE 3 static const struct sc_asn1_entry c_asn1_cvcert[C_ASN1_CVCERT_SIZE] = { { "certificateBody", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F4E, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_SIZE 2 static const struct sc_asn1_entry c_asn1_cvc[C_ASN1_CVC_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_AUTHREQ_SIZE 4 static const struct sc_asn1_entry c_asn1_authreq[C_ASN1_AUTHREQ_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { "outerCAR", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_REQ_SIZE 2 static const struct sc_asn1_entry c_asn1_req[C_ASN1_REQ_SIZE] = { { "authenticatedrequest", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 7, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static int read_file(sc_pkcs15_card_t * p15card, u8 fid[2], u8 *efbin, size_t *len, int optional) { sc_path_t path; int r; sc_path_set(&path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); /* look this up with our AID */ path.aid = sc_hsm_aid; /* we don't have a pre-known size of the file */ path.count = -1; if (!p15card->opts.use_file_cache || !efbin || SC_SUCCESS != sc_pkcs15_read_cached_file(p15card, &path, &efbin, len)) { /* avoid re-selection of SC-HSM */ path.aid.len = 0; r = sc_select_file(p15card->card, &path, NULL); if (r < 0) { sc_log(p15card->card->ctx, "Could not select EF"); } else { r = sc_read_binary(p15card->card, 0, efbin, *len, 0); } if (r < 0) { sc_log(p15card->card->ctx, "Could not read EF"); if (!optional) { return r; } /* optional files are saved as empty files to avoid card * transactions. Parsing the file's data will reveal that they were * missing. */ *len = 0; } else { *len = r; } if (p15card->opts.use_file_cache) { /* save this with our AID */ path.aid = sc_hsm_aid; sc_pkcs15_cache_file(p15card, &path, efbin, *len); } } return SC_SUCCESS; } /* * Decode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_decode_cvc(sc_pkcs15_card_t * p15card, const u8 ** buf, size_t *buflen, sc_cvc_t *cvc) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_req[C_ASN1_REQ_SIZE]; struct sc_asn1_entry asn1_authreq[C_ASN1_AUTHREQ_SIZE]; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; unsigned int cla,tag; size_t taglen; size_t lenchr = sizeof(cvc->chr); size_t lencar = sizeof(cvc->car); size_t lenoutercar = sizeof(cvc->outer_car); const u8 *tbuf; int r; memset(cvc, 0, sizeof(*cvc)); sc_copy_asn1_entry(c_asn1_req, asn1_req); sc_copy_asn1_entry(c_asn1_authreq, asn1_authreq); sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 1, &cvc->primeOrModulus, &cvc->primeOrModuluslen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 2, &cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 3, &cvc->coefficientB, &cvc->coefficientBlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 4, &cvc->basePointG, &cvc->basePointGlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 5, &cvc->order, &cvc->orderlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 6, &cvc->publicPoint, &cvc->publicPointlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 7, &cvc->cofactor, &cvc->cofactorlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 0); sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 0); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 0); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 0); sc_format_asn1_entry(asn1_cvcert + 1, &cvc->signature, &cvc->signatureLen, 0); sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq + 1, &cvc->outer_car, &lenoutercar, 0); sc_format_asn1_entry(asn1_authreq + 2, &cvc->outerSignature, &cvc->outerSignatureLen, 0); sc_format_asn1_entry(asn1_req , &asn1_authreq, NULL, 0); /* sc_asn1_print_tags(*buf, *buflen); */ tbuf = *buf; r = sc_asn1_read_tag(&tbuf, *buflen, &cla, &tag, &taglen); LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); /* Determine if we deal with an authenticated request, plain request or certificate */ if ((cla == (SC_ASN1_TAG_APPLICATION|SC_ASN1_TAG_CONSTRUCTED)) && (tag == 7)) { r = sc_asn1_decode(card->ctx, asn1_req, *buf, *buflen, buf, buflen); } else { r = sc_asn1_decode(card->ctx, asn1_cvc, *buf, *buflen, buf, buflen); } LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Encode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_encode_cvc(sc_pkcs15_card_t * p15card, sc_cvc_t *cvc, u8 ** buf, size_t *buflen) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; size_t lenchr; size_t lencar; int r; sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); asn1_cvc_pubkey[1].flags = SC_ASN1_OPTIONAL; asn1_cvcert[1].flags = SC_ASN1_OPTIONAL; sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 1); if (cvc->primeOrModulus && (cvc->primeOrModuluslen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 1, cvc->primeOrModulus, &cvc->primeOrModuluslen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 2, cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 1); if (cvc->coefficientB && (cvc->coefficientBlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 3, cvc->coefficientB, &cvc->coefficientBlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 4, cvc->basePointG, &cvc->basePointGlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 5, cvc->order, &cvc->orderlen, 1); if (cvc->publicPoint && (cvc->publicPointlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 6, cvc->publicPoint, &cvc->publicPointlen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 7, cvc->cofactor, &cvc->cofactorlen, 1); } if (cvc->modulusSize > 0) { sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 1); } sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 1); lencar = strnlen(cvc->car, sizeof cvc->car); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 1); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 1); lenchr = strnlen(cvc->chr, sizeof cvc->chr); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 1); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 1); if (cvc->signature && (cvc->signatureLen > 0)) { sc_format_asn1_entry(asn1_cvcert + 1, cvc->signature, &cvc->signatureLen, 1); } sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 1); r = sc_asn1_encode(card->ctx, asn1_cvc, buf, buflen); LOG_TEST_RET(card->ctx, r, "Could not encode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_get_curve(struct ec_curve **curve, u8 *oid, size_t oidlen) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].oid.len == oidlen) && !memcmp(curves[i].oid.value, oid, oidlen)) { *curve = &curves[i]; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } int sc_pkcs15emu_sc_hsm_get_curve_oid(sc_cvc_t *cvc, const struct sc_lv_data **oid) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].prime.len == cvc->primeOrModuluslen) && !memcmp(curves[i].prime.value, cvc->primeOrModulus, cvc->primeOrModuluslen)) { *oid = &curves[i].oid; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } static int sc_pkcs15emu_sc_hsm_get_rsa_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { pubkey->algorithm = SC_ALGORITHM_RSA; pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) return SC_ERROR_OUT_OF_MEMORY; pubkey->alg_id->algorithm = SC_ALGORITHM_RSA; pubkey->u.rsa.modulus.len = cvc->primeOrModuluslen; pubkey->u.rsa.modulus.data = malloc(pubkey->u.rsa.modulus.len); pubkey->u.rsa.exponent.len = cvc->coefficientAorExponentlen; pubkey->u.rsa.exponent.data = malloc(pubkey->u.rsa.exponent.len); if (!pubkey->u.rsa.modulus.data || !pubkey->u.rsa.exponent.data) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.rsa.exponent.data, cvc->coefficientAorExponent, pubkey->u.rsa.exponent.len); memcpy(pubkey->u.rsa.modulus.data, cvc->primeOrModulus, pubkey->u.rsa.modulus.len); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_get_ec_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { struct sc_ec_parameters *ecp; const struct sc_lv_data *oid; int r; pubkey->algorithm = SC_ALGORITHM_EC; r = sc_pkcs15emu_sc_hsm_get_curve_oid(cvc, &oid); if (r != SC_SUCCESS) return r; ecp = calloc(1, sizeof(struct sc_ec_parameters)); if (!ecp) return SC_ERROR_OUT_OF_MEMORY; ecp->der.len = oid->len + 2; ecp->der.value = calloc(ecp->der.len, 1); if (!ecp->der.value) { free(ecp); return SC_ERROR_OUT_OF_MEMORY; } *(ecp->der.value + 0) = 0x06; *(ecp->der.value + 1) = (u8)oid->len; memcpy(ecp->der.value + 2, oid->value, oid->len); ecp->type = 1; // Named curve pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) { free(ecp->der.value); free(ecp); return SC_ERROR_OUT_OF_MEMORY; } pubkey->alg_id->algorithm = SC_ALGORITHM_EC; pubkey->alg_id->params = ecp; pubkey->u.ec.ecpointQ.value = malloc(cvc->publicPointlen); if (!pubkey->u.ec.ecpointQ.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.ecpointQ.value, cvc->publicPoint, cvc->publicPointlen); pubkey->u.ec.ecpointQ.len = cvc->publicPointlen; pubkey->u.ec.params.der.value = malloc(ecp->der.len); if (!pubkey->u.ec.params.der.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.params.der.value, ecp->der.value, ecp->der.len); pubkey->u.ec.params.der.len = ecp->der.len; /* FIXME: check return value? */ sc_pkcs15_fix_ec_parameters(ctx, &pubkey->u.ec.params); return SC_SUCCESS; } int sc_pkcs15emu_sc_hsm_get_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { if (cvc->publicPoint && cvc->publicPointlen) { return sc_pkcs15emu_sc_hsm_get_ec_public_key(ctx, cvc, pubkey); } else { return sc_pkcs15emu_sc_hsm_get_rsa_public_key(ctx, cvc, pubkey); } } void sc_pkcs15emu_sc_hsm_free_cvc(sc_cvc_t *cvc) { if (cvc->signature) { free(cvc->signature); cvc->signature = NULL; } if (cvc->primeOrModulus) { free(cvc->primeOrModulus); cvc->primeOrModulus = NULL; } if (cvc->coefficientAorExponent) { free(cvc->coefficientAorExponent); cvc->coefficientAorExponent = NULL; } if (cvc->coefficientB) { free(cvc->coefficientB); cvc->coefficientB = NULL; } if (cvc->basePointG) { free(cvc->basePointG); cvc->basePointG = NULL; } if (cvc->order) { free(cvc->order); cvc->order = NULL; } if (cvc->publicPoint) { free(cvc->publicPoint); cvc->publicPoint = NULL; } if (cvc->cofactor) { free(cvc->cofactor); cvc->cofactor = NULL; } } static int sc_pkcs15emu_sc_hsm_add_pubkey(sc_pkcs15_card_t *p15card, u8 *efbin, size_t len, sc_pkcs15_prkey_info_t *key_info, char *label) { struct sc_context *ctx = p15card->card->ctx; sc_card_t *card = p15card->card; sc_pkcs15_pubkey_info_t pubkey_info; sc_pkcs15_object_t pubkey_obj; struct sc_pkcs15_pubkey pubkey; sc_cvc_t cvc; u8 *cvcpo; int r; cvcpo = efbin; memset(&cvc, 0, sizeof(cvc)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&cvcpo, &len, &cvc); LOG_TEST_RET(ctx, r, "Could decode certificate signing request"); memset(&pubkey, 0, sizeof(pubkey)); r = sc_pkcs15emu_sc_hsm_get_public_key(ctx, &cvc, &pubkey); LOG_TEST_RET(card->ctx, r, "Could not extract public key"); memset(&pubkey_info, 0, sizeof(pubkey_info)); memset(&pubkey_obj, 0, sizeof(pubkey_obj)); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_obj.content.value, &pubkey_obj.content.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_info.direct.raw.value, &pubkey_info.direct.raw.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey_as_spki(ctx, &pubkey, &pubkey_info.direct.spki.value, &pubkey_info.direct.spki.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); pubkey_info.id = key_info->id; strlcpy(pubkey_obj.label, label, sizeof(pubkey_obj.label)); if (pubkey.algorithm == SC_ALGORITHM_RSA) { pubkey_info.modulus_length = pubkey.u.rsa.modulus.len << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_VERIFY|SC_PKCS15_PRKEY_USAGE_WRAP; r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info); } else { /* TODO fix if support of non multiple of 8 curves are added */ pubkey_info.field_length = cvc.primeOrModuluslen << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_VERIFY; r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info); } LOG_TEST_RET(ctx, r, "Could not add public key"); sc_pkcs15emu_sc_hsm_free_cvc(&cvc); sc_pkcs15_erase_pubkey(&pubkey); return SC_SUCCESS; } /* * Add a key and the key description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t cert_info; sc_pkcs15_object_t cert_obj; struct sc_pkcs15_object prkd; sc_pkcs15_prkey_info_t *key_info; u8 fid[2]; /* enough to hold a complete certificate */ u8 efbin[4096]; u8 *ptr; size_t len; int r; fid[0] = PRKD_PREFIX; fid[1] = keyid; /* Try to select a related EF containing the PKCS#15 description of the key */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); ptr = efbin; memset(&prkd, 0, sizeof(prkd)); r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); /* All keys require user PIN authentication */ prkd.auth_id.len = 1; prkd.auth_id.value[0] = 1; /* * Set private key flag as all keys are private anyway */ prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE; key_info = (sc_pkcs15_prkey_info_t *)prkd.data; key_info->key_reference = keyid; key_info->path.aid.len = 0; if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) { r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info); } else { r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info); } LOG_TEST_RET(card->ctx, r, "Could not add private key to framework"); /* Check if we also have a certificate for the private key */ fid[0] = EE_CERTIFICATE_PREFIX; len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 0); LOG_TEST_RET(card->ctx, r, "Could not read EF"); if (efbin[0] == 0x67) { /* Decode CSR and create public key object */ sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label); free(key_info); return SC_SUCCESS; /* Ignore any errors */ } if (efbin[0] != 0x30) { free(key_info); return SC_SUCCESS; } memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id = key_info->id; sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); cert_info.path.count = -1; if (p15card->opts.use_file_cache) { /* look this up with our AID, which should already be cached from the * call to `read_file`. This may have the side effect that OpenSC's * caching layer re-selects our applet *if the cached file cannot be * found/used* and we may loose the authentication status. We assume * that caching works perfectly without this side effect. */ cert_info.path.aid = sc_hsm_aid; } strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); free(key_info); LOG_TEST_RET(card->ctx, r, "Could not add certificate"); return SC_SUCCESS; } /* * Add a data object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_dcod(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_data_info_t *data_info; sc_pkcs15_object_t data_obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = DCOD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&data_obj, 0, sizeof(data_obj)); r = sc_pkcs15_decode_dodf_entry(p15card, &data_obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Could not decode optional EF.DCOD"); data_info = (sc_pkcs15_data_info_t *)data_obj.data; r = sc_pkcs15emu_add_data_object(p15card, &data_obj, data_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } /* * Add a unrelated certificate object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_cd(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t *cert_info; sc_pkcs15_object_t obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = CD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&obj, 0, sizeof(obj)); r = sc_pkcs15_decode_cdf_entry(p15card, &obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.CDOD"); cert_info = (sc_pkcs15_cert_info_t *)obj.data; r = sc_pkcs15emu_add_x509_cert(p15card, &obj, cert_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_read_tokeninfo (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; int r; u8 efbin[512]; size_t len; LOG_FUNC_CALLED(card->ctx); /* Read token info */ len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x03", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); r = sc_pkcs15_parse_tokeninfo(card->ctx, p15card->tokeninfo, efbin, len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Initialize PKCS#15 emulation with user PIN, private keys, certificate and data objects * */ static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data; sc_file_t *file = NULL; sc_path_t path; u8 filelist[MAX_EXT_APDU_LENGTH]; int filelistlength; int r, i; sc_cvc_t devcert; struct sc_app_info *appinfo; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; struct sc_pin_cmd_data pindata; u8 efbin[1024]; u8 *ptr; size_t len; LOG_FUNC_CALLED(card->ctx); appinfo = calloc(1, sizeof(struct sc_app_info)); if (appinfo == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->aid = sc_hsm_aid; appinfo->ddo.aid = sc_hsm_aid; p15card->app = appinfo; sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0); r = sc_select_file(card, &path, &file); LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application"); p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */ p15card->card->version.hw_minor = 13; if (file && file->prop_attr && file->prop_attr_len >= 2) { p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2]; p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1]; } sc_file_free(file); /* Read device certificate to determine serial number */ if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) { ptr = priv->EF_C_DevAut; len = priv->EF_C_DevAut_len; } else { len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut"); /* save EF_C_DevAut for further use */ ptr = realloc(priv->EF_C_DevAut, len); if (ptr) { memcpy(ptr, efbin, len); priv->EF_C_DevAut = ptr; priv->EF_C_DevAut_len = len; } ptr = efbin; } memset(&devcert, 0 ,sizeof(devcert)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert); LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut"); sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card); if (p15card->tokeninfo->label == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->label = strdup("GoID"); } else { p15card->tokeninfo->label = strdup("SmartCard-HSM"); } if (p15card->tokeninfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) { free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = NULL; } if (p15card->tokeninfo->manufacturer_id == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH"); } else { p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de"); } if (p15card->tokeninfo->manufacturer_id == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->label = strdup(p15card->tokeninfo->label); if (appinfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */ assert(len >= 8); len -= 5; p15card->tokeninfo->serial_number = calloc(len + 1, 1); if (p15card->tokeninfo->serial_number == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(p15card->tokeninfo->serial_number, devcert.chr, len); *(p15card->tokeninfo->serial_number + len) = 0; sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number); sc_pkcs15emu_sc_hsm_free_cvc(&devcert); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 1; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x81; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = 6; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 15; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 3; pin_info.max_tries = 3; pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 2; strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 2; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x88; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD; pin_info.attrs.pin.min_length = 16; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 16; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 15; pin_info.max_tries = 15; strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); if (card->type == SC_CARD_TYPE_SC_HSM_SOC || card->type == SC_CARD_TYPE_SC_HSM_GOID) { /* SC-HSM of this type always has a PIN-Pad */ r = SC_SUCCESS; } else { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x85; r = sc_pin_cmd(card, &pindata, NULL); } if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x86; r = sc_pin_cmd(card, &pindata, NULL); } if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS)) card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH; filelistlength = sc_list_files(card, filelist, sizeof(filelist)); LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier"); for (i = 0; i < filelistlength; i += 2) { switch(filelist[i]) { case KEY_PREFIX: r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]); break; case DCOD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]); break; case CD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]); break; } if (r != SC_SUCCESS) { sc_log(card->ctx, "Error %d adding elements to framework", r); } } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) { return sc_pkcs15emu_sc_hsm_init(p15card); } else { if (p15card->card->type != SC_CARD_TYPE_SC_HSM && p15card->card->type != SC_CARD_TYPE_SC_HSM_SOC && p15card->card->type != SC_CARD_TYPE_SC_HSM_GOID) { return SC_ERROR_WRONG_CARD; } return sc_pkcs15emu_sc_hsm_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_339_6
crossvul-cpp_data_bad_2820_0
/* * RTP H.264 Protocol (RFC3984) * Copyright (c) 2006 Ryan Martell * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @brief H.264 / RTP Code (RFC3984) * @author Ryan Martell <rdm4@martellventures.com> * * @note Notes: * Notes: * This currently supports packetization mode: * Single Nal Unit Mode (0), or * Non-Interleaved Mode (1). It currently does not support * Interleaved Mode (2). (This requires implementing STAP-B, MTAP16, MTAP24, * FU-B packet types) */ #include "libavutil/attributes.h" #include "libavutil/base64.h" #include "libavutil/intreadwrite.h" #include "libavutil/avstring.h" #include "avformat.h" #include "rtpdec.h" #include "rtpdec_formats.h" struct PayloadContext { // sdp setup parameters uint8_t profile_idc; uint8_t profile_iop; uint8_t level_idc; int packetization_mode; #ifdef DEBUG int packet_types_received[32]; #endif }; #ifdef DEBUG #define COUNT_NAL_TYPE(data, nal) data->packet_types_received[(nal) & 0x1f]++ #define NAL_COUNTERS data->packet_types_received #else #define COUNT_NAL_TYPE(data, nal) do { } while (0) #define NAL_COUNTERS NULL #endif #define NAL_MASK 0x1f static const uint8_t start_sequence[] = { 0, 0, 0, 1 }; static void parse_profile_level_id(AVFormatContext *s, PayloadContext *h264_data, const char *value) { char buffer[3]; // 6 characters=3 bytes, in hex. uint8_t profile_idc; uint8_t profile_iop; uint8_t level_idc; buffer[0] = value[0]; buffer[1] = value[1]; buffer[2] = '\0'; profile_idc = strtol(buffer, NULL, 16); buffer[0] = value[2]; buffer[1] = value[3]; profile_iop = strtol(buffer, NULL, 16); buffer[0] = value[4]; buffer[1] = value[5]; level_idc = strtol(buffer, NULL, 16); av_log(s, AV_LOG_DEBUG, "RTP Profile IDC: %x Profile IOP: %x Level: %x\n", profile_idc, profile_iop, level_idc); h264_data->profile_idc = profile_idc; h264_data->profile_iop = profile_iop; h264_data->level_idc = level_idc; } int ff_h264_parse_sprop_parameter_sets(AVFormatContext *s, uint8_t **data_ptr, int *size_ptr, const char *value) { char base64packet[1024]; uint8_t decoded_packet[1024]; int packet_size; while (*value) { char *dst = base64packet; while (*value && *value != ',' && (dst - base64packet) < sizeof(base64packet) - 1) { *dst++ = *value++; } *dst++ = '\0'; if (*value == ',') value++; packet_size = av_base64_decode(decoded_packet, base64packet, sizeof(decoded_packet)); if (packet_size > 0) { uint8_t *dest = av_realloc(*data_ptr, packet_size + sizeof(start_sequence) + *size_ptr + AV_INPUT_BUFFER_PADDING_SIZE); if (!dest) { av_log(s, AV_LOG_ERROR, "Unable to allocate memory for extradata!\n"); return AVERROR(ENOMEM); } *data_ptr = dest; memcpy(dest + *size_ptr, start_sequence, sizeof(start_sequence)); memcpy(dest + *size_ptr + sizeof(start_sequence), decoded_packet, packet_size); memset(dest + *size_ptr + sizeof(start_sequence) + packet_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); *size_ptr += sizeof(start_sequence) + packet_size; } } return 0; } static int sdp_parse_fmtp_config_h264(AVFormatContext *s, AVStream *stream, PayloadContext *h264_data, const char *attr, const char *value) { AVCodecParameters *par = stream->codecpar; if (!strcmp(attr, "packetization-mode")) { av_log(s, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value)); h264_data->packetization_mode = atoi(value); /* * Packetization Mode: * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed) * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed. * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A), * and 29 (FU-B) are allowed. */ if (h264_data->packetization_mode > 1) av_log(s, AV_LOG_ERROR, "Interleaved RTP mode is not supported yet.\n"); } else if (!strcmp(attr, "profile-level-id")) { if (strlen(value) == 6) parse_profile_level_id(s, h264_data, value); } else if (!strcmp(attr, "sprop-parameter-sets")) { int ret; if (value[strlen(value) - 1] == ',') { av_log(s, AV_LOG_WARNING, "Missing PPS in sprop-parameter-sets, ignoring\n"); return 0; } par->extradata_size = 0; av_freep(&par->extradata); ret = ff_h264_parse_sprop_parameter_sets(s, &par->extradata, &par->extradata_size, value); av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)\n", par->extradata, par->extradata_size); return ret; } return 0; } void ff_h264_parse_framesize(AVCodecParameters *par, const char *p) { char buf1[50]; char *dst = buf1; // remove the protocol identifier while (*p && *p == ' ') p++; // strip spaces. while (*p && *p != ' ') p++; // eat protocol identifier while (*p && *p == ' ') p++; // strip trailing spaces. while (*p && *p != '-' && (dst - buf1) < sizeof(buf1) - 1) *dst++ = *p++; *dst = '\0'; // a='framesize:96 320-240' // set our parameters par->width = atoi(buf1); par->height = atoi(p + 1); // skip the - } int ff_h264_handle_aggregated_packet(AVFormatContext *ctx, PayloadContext *data, AVPacket *pkt, const uint8_t *buf, int len, int skip_between, int *nal_counters, int nal_mask) { int pass = 0; int total_length = 0; uint8_t *dst = NULL; int ret; // first we are going to figure out the total size for (pass = 0; pass < 2; pass++) { const uint8_t *src = buf; int src_len = len; while (src_len > 2) { uint16_t nal_size = AV_RB16(src); // consume the length of the aggregate src += 2; src_len -= 2; if (nal_size <= src_len) { if (pass == 0) { // counting total_length += sizeof(start_sequence) + nal_size; } else { // copying memcpy(dst, start_sequence, sizeof(start_sequence)); dst += sizeof(start_sequence); memcpy(dst, src, nal_size); if (nal_counters) nal_counters[(*src) & nal_mask]++; dst += nal_size; } } else { av_log(ctx, AV_LOG_ERROR, "nal size exceeds length: %d %d\n", nal_size, src_len); return AVERROR_INVALIDDATA; } // eat what we handled src += nal_size + skip_between; src_len -= nal_size + skip_between; } if (pass == 0) { /* now we know the total size of the packet (with the * start sequences added) */ if ((ret = av_new_packet(pkt, total_length)) < 0) return ret; dst = pkt->data; } } return 0; } int ff_h264_handle_frag_packet(AVPacket *pkt, const uint8_t *buf, int len, int start_bit, const uint8_t *nal_header, int nal_header_len) { int ret; int tot_len = len; int pos = 0; if (start_bit) tot_len += sizeof(start_sequence) + nal_header_len; if ((ret = av_new_packet(pkt, tot_len)) < 0) return ret; if (start_bit) { memcpy(pkt->data + pos, start_sequence, sizeof(start_sequence)); pos += sizeof(start_sequence); memcpy(pkt->data + pos, nal_header, nal_header_len); pos += nal_header_len; } memcpy(pkt->data + pos, buf, len); return 0; } static int h264_handle_packet_fu_a(AVFormatContext *ctx, PayloadContext *data, AVPacket *pkt, const uint8_t *buf, int len, int *nal_counters, int nal_mask) { uint8_t fu_indicator, fu_header, start_bit, nal_type, nal; if (len < 3) { av_log(ctx, AV_LOG_ERROR, "Too short data for FU-A H.264 RTP packet\n"); return AVERROR_INVALIDDATA; } fu_indicator = buf[0]; fu_header = buf[1]; start_bit = fu_header >> 7; nal_type = fu_header & 0x1f; nal = fu_indicator & 0xe0 | nal_type; // skip the fu_indicator and fu_header buf += 2; len -= 2; if (start_bit && nal_counters) nal_counters[nal_type & nal_mask]++; return ff_h264_handle_frag_packet(pkt, buf, len, start_bit, &nal, 1); } // return 0 on packet, no more left, 1 on packet, 1 on partial packet static int h264_handle_packet(AVFormatContext *ctx, PayloadContext *data, AVStream *st, AVPacket *pkt, uint32_t *timestamp, const uint8_t *buf, int len, uint16_t seq, int flags) { uint8_t nal; uint8_t type; int result = 0; if (!len) { av_log(ctx, AV_LOG_ERROR, "Empty H.264 RTP packet\n"); return AVERROR_INVALIDDATA; } nal = buf[0]; type = nal & 0x1f; /* Simplify the case (these are all the NAL types used internally by * the H.264 codec). */ if (type >= 1 && type <= 23) type = 1; switch (type) { case 0: // undefined, but pass them through case 1: if ((result = av_new_packet(pkt, len + sizeof(start_sequence))) < 0) return result; memcpy(pkt->data, start_sequence, sizeof(start_sequence)); memcpy(pkt->data + sizeof(start_sequence), buf, len); COUNT_NAL_TYPE(data, nal); break; case 24: // STAP-A (one packet, multiple nals) // consume the STAP-A NAL buf++; len--; result = ff_h264_handle_aggregated_packet(ctx, data, pkt, buf, len, 0, NAL_COUNTERS, NAL_MASK); break; case 25: // STAP-B case 26: // MTAP-16 case 27: // MTAP-24 case 29: // FU-B avpriv_report_missing_feature(ctx, "RTP H.264 NAL unit type %d", type); result = AVERROR_PATCHWELCOME; break; case 28: // FU-A (fragmented nal) result = h264_handle_packet_fu_a(ctx, data, pkt, buf, len, NAL_COUNTERS, NAL_MASK); break; case 30: // undefined case 31: // undefined default: av_log(ctx, AV_LOG_ERROR, "Undefined type (%d)\n", type); result = AVERROR_INVALIDDATA; break; } pkt->stream_index = st->index; return result; } static void h264_close_context(PayloadContext *data) { #ifdef DEBUG int ii; for (ii = 0; ii < 32; ii++) { if (data->packet_types_received[ii]) av_log(NULL, AV_LOG_DEBUG, "Received %d packets of type %d\n", data->packet_types_received[ii], ii); } #endif } static int parse_h264_sdp_line(AVFormatContext *s, int st_index, PayloadContext *h264_data, const char *line) { AVStream *stream; const char *p = line; if (st_index < 0) return 0; stream = s->streams[st_index]; if (av_strstart(p, "framesize:", &p)) { ff_h264_parse_framesize(stream->codecpar, p); } else if (av_strstart(p, "fmtp:", &p)) { return ff_parse_fmtp(s, stream, h264_data, p, sdp_parse_fmtp_config_h264); } else if (av_strstart(p, "cliprect:", &p)) { // could use this if we wanted. } return 0; } RTPDynamicProtocolHandler ff_h264_dynamic_handler = { .enc_name = "H264", .codec_type = AVMEDIA_TYPE_VIDEO, .codec_id = AV_CODEC_ID_H264, .need_parsing = AVSTREAM_PARSE_FULL, .priv_data_size = sizeof(PayloadContext), .parse_sdp_a_line = parse_h264_sdp_line, .close = h264_close_context, .parse_packet = h264_handle_packet, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2820_0
crossvul-cpp_data_bad_345_5
/* * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Initially written by David Mattes <david.mattes@boeing.com> */ /* Support for multiple key containers by Lukas Wunner <lukas@wunner.de> */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #define MANU_ID "Gemplus" #define APPLET_NAME "GemSAFE V1" #define DRIVER_SERIAL_NUMBER "v0.9" #define GEMSAFE_APP_PATH "3F001600" #define GEMSAFE_PATH "3F0016000004" /* Apparently, the Applet max read "quanta" is 248 bytes * Gemalto ClassicClient reads files in chunks of 238 bytes */ #define GEMSAFE_READ_QUANTUM 248 #define GEMSAFE_MAX_OBJLEN 28672 int sc_pkcs15emu_gemsafeV1_init_ex(sc_pkcs15_card_t *, struct sc_aid *,sc_pkcs15emu_opt_t *); static int sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card, int type, int authority, const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label, int obj_flags); static int sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, const sc_path_t *path, int ref, int type, unsigned int min_length, unsigned int max_length, int flags, int tries_left, const char pad_char, int obj_flags); static int sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, int type, unsigned int modulus_length, int usage, const sc_path_t *path, int ref, const sc_pkcs15_id_t *auth_id, int obj_flags); typedef struct cdata_st { char *label; int authority; const char *path; size_t index; size_t count; const char *id; int obj_flags; } cdata; const unsigned int gemsafe_cert_max = 12; cdata gemsafe_cert[] = { {"DS certificate #1", 0, GEMSAFE_PATH, 0, 0, "45", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #2", 0, GEMSAFE_PATH, 0, 0, "46", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #3", 0, GEMSAFE_PATH, 0, 0, "47", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #4", 0, GEMSAFE_PATH, 0, 0, "48", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #5", 0, GEMSAFE_PATH, 0, 0, "49", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #6", 0, GEMSAFE_PATH, 0, 0, "50", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #7", 0, GEMSAFE_PATH, 0, 0, "51", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #8", 0, GEMSAFE_PATH, 0, 0, "52", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #9", 0, GEMSAFE_PATH, 0, 0, "53", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #10", 0, GEMSAFE_PATH, 0, 0, "54", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #11", 0, GEMSAFE_PATH, 0, 0, "55", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #12", 0, GEMSAFE_PATH, 0, 0, "56", SC_PKCS15_CO_FLAG_MODIFIABLE}, }; typedef struct pdata_st { const u8 atr[SC_MAX_ATR_SIZE]; const size_t atr_len; const char *id; const char *label; const char *path; const int ref; const int type; const unsigned int maxlen; const unsigned int minlen; const int flags; const int tries_left; const char pad_char; const int obj_flags; } pindata; const unsigned int gemsafe_pin_max = 2; const pindata gemsafe_pin[] = { /* ATR-specific PIN policies, first match found is used: */ { {0x3B, 0x7D, 0x96, 0x00, 0x00, 0x80, 0x31, 0x80, 0x65, 0xB0, 0x83, 0x11, 0x48, 0xC8, 0x83, 0x00, 0x90, 0x00}, 18, "01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_ASCII_NUMERIC, 8, 4, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL, 3, 0x00, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE }, /* default PIN policy comes last: */ { { 0 }, 0, "01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_BCD, 16, 6, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL, 3, 0xFF, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE } }; typedef struct prdata_st { const char *id; char *label; unsigned int modulus_len; int usage; const char *path; int ref; const char *auth_id; int obj_flags; } prdata; #define USAGE_NONREP SC_PKCS15_PRKEY_USAGE_NONREPUDIATION #define USAGE_KE SC_PKCS15_PRKEY_USAGE_ENCRYPT | \ SC_PKCS15_PRKEY_USAGE_DECRYPT | \ SC_PKCS15_PRKEY_USAGE_WRAP | \ SC_PKCS15_PRKEY_USAGE_UNWRAP #define USAGE_AUT SC_PKCS15_PRKEY_USAGE_ENCRYPT | \ SC_PKCS15_PRKEY_USAGE_DECRYPT | \ SC_PKCS15_PRKEY_USAGE_WRAP | \ SC_PKCS15_PRKEY_USAGE_UNWRAP | \ SC_PKCS15_PRKEY_USAGE_SIGN prdata gemsafe_prkeys[] = { { "45", "DS key #1", 1024, USAGE_AUT, GEMSAFE_PATH, 0x03, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "46", "DS key #2", 1024, USAGE_AUT, GEMSAFE_PATH, 0x04, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "47", "DS key #3", 1024, USAGE_AUT, GEMSAFE_PATH, 0x05, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "48", "DS key #4", 1024, USAGE_AUT, GEMSAFE_PATH, 0x06, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "49", "DS key #5", 1024, USAGE_AUT, GEMSAFE_PATH, 0x07, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "50", "DS key #6", 1024, USAGE_AUT, GEMSAFE_PATH, 0x08, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "51", "DS key #7", 1024, USAGE_AUT, GEMSAFE_PATH, 0x09, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "52", "DS key #8", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0a, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "53", "DS key #9", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0b, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "54", "DS key #10", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0c, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "55", "DS key #11", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0d, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "56", "DS key #12", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0e, "01", SC_PKCS15_CO_FLAG_PRIVATE}, }; static int gemsafe_get_cert_len(sc_card_t *card) { int r; u8 ibuf[GEMSAFE_MAX_OBJLEN]; u8 *iptr; struct sc_path path; struct sc_file *file; size_t objlen, certlen; unsigned int ind, i=0; sc_format_path(GEMSAFE_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* Initial read */ r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0); if (r < 0) return SC_ERROR_INTERNAL; /* Actual stored object size is encoded in first 2 bytes * (allocated EF space is much greater!) */ objlen = (((size_t) ibuf[0]) << 8) | ibuf[1]; sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) { sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); return SC_ERROR_INTERNAL; } /* It looks like the first thing in the block is a table of * which keys are allocated. The table is small and is in the * first 248 bytes. Example for a card with 10 key containers: * 01 f0 00 03 03 b0 00 03 <= 1st key unallocated * 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated * 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated * 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated * 01 f0 00 07 03 b0 00 07 <= 5th key unallocated * ... * 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated * For allocated keys, the fourth byte seems to indicate the * default key and the fifth byte indicates the key_ref of * the private key. */ ind = 2; /* skip length */ while (ibuf[ind] == 0x01) { if (ibuf[ind+1] == 0xFE) { gemsafe_prkeys[i].ref = ibuf[ind+4]; sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d", i+1, gemsafe_prkeys[i].ref); ind += 9; } else { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; sc_log(card->ctx, "Key container %d is unallocated", i+1); ind += 8; } i++; } /* Delete additional key containers from the data structures if * this card can't accommodate them. */ for (; i < gemsafe_cert_max; i++) { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } /* Read entire file, then dissect in memory. * Gemalto ClassicClient seems to do it the same way. */ iptr = ibuf + GEMSAFE_READ_QUANTUM; while ((size_t)(iptr - ibuf) < objlen) { r = sc_read_binary(card, iptr - ibuf, iptr, MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0); if (r < 0) { sc_log(card->ctx, "Could not read cert object"); return SC_ERROR_INTERNAL; } iptr += GEMSAFE_READ_QUANTUM; } /* Search buffer for certificates, they start with 0x3082. */ i = 0; while (ind < objlen - 1) { if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) { /* Find next allocated key container */ while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL) i++; if (i == gemsafe_cert_max) { sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind); return SC_SUCCESS; } /* DER cert len is encoded this way */ if (ind+3 >= sizeof ibuf) return SC_ERROR_INVALID_DATA; certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4; sc_log(card->ctx, "Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u", i+1, ind, certlen); gemsafe_cert[i].index = ind; gemsafe_cert[i].count = certlen; ind += certlen; i++; } else ind++; } /* Delete additional key containers from the data structures if * they're missing on the card. */ for (; i < gemsafe_cert_max; i++) { if (gemsafe_cert[i].label) { sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1); gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } } return SC_SUCCESS; } static int gemsafe_detect_card( sc_pkcs15_card_t *p15card) { if (strcmp(p15card->card->name, "GemSAFE V1")) return SC_ERROR_WRONG_CARD; return SC_SUCCESS; } static int sc_pkcs15emu_gemsafeV1_init( sc_pkcs15_card_t *p15card) { int r; unsigned int i; struct sc_path path; struct sc_file *file = NULL; struct sc_card *card = p15card->card; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_log(p15card->card->ctx, "Setting pkcs15 parameters"); if (p15card->tokeninfo->label) free(p15card->tokeninfo->label); p15card->tokeninfo->label = malloc(strlen(APPLET_NAME) + 1); if (!p15card->tokeninfo->label) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->label, APPLET_NAME); if (p15card->tokeninfo->serial_number) free(p15card->tokeninfo->serial_number); p15card->tokeninfo->serial_number = malloc(strlen(DRIVER_SERIAL_NUMBER) + 1); if (!p15card->tokeninfo->serial_number) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->serial_number, DRIVER_SERIAL_NUMBER); /* the GemSAFE applet version number */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0xdf, 0x03); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); /* Manual says Le=0x05, but should be 0x08 to return full version number */ apdu.le = 0x08; apdu.lc = 0; apdu.datalen = 0; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) return SC_ERROR_INTERNAL; if (r != SC_SUCCESS) return SC_ERROR_INTERNAL; /* the manufacturer ID, in this case GemPlus */ if (p15card->tokeninfo->manufacturer_id) free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = malloc(strlen(MANU_ID) + 1); if (!p15card->tokeninfo->manufacturer_id) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->manufacturer_id, MANU_ID); /* determine allocated key containers and length of certificates */ r = gemsafe_get_cert_len(card); if (r != SC_SUCCESS) return SC_ERROR_INTERNAL; /* set certs */ sc_log(p15card->card->ctx, "Setting certificates"); for (i = 0; i < gemsafe_cert_max; i++) { struct sc_pkcs15_id p15Id; struct sc_path path; if (gemsafe_cert[i].label == NULL) continue; sc_format_path(gemsafe_cert[i].path, &path); sc_pkcs15_format_id(gemsafe_cert[i].id, &p15Id); path.index = gemsafe_cert[i].index; path.count = gemsafe_cert[i].count; sc_pkcs15emu_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509, gemsafe_cert[i].authority, &path, &p15Id, gemsafe_cert[i].label, gemsafe_cert[i].obj_flags); } /* set gemsafe_pin */ sc_log(p15card->card->ctx, "Setting PIN"); for (i=0; i < gemsafe_pin_max; i++) { struct sc_pkcs15_id p15Id; struct sc_path path; sc_pkcs15_format_id(gemsafe_pin[i].id, &p15Id); sc_format_path(gemsafe_pin[i].path, &path); if (gemsafe_pin[i].atr_len == 0 || (gemsafe_pin[i].atr_len == p15card->card->atr.len && memcmp(p15card->card->atr.value, gemsafe_pin[i].atr, p15card->card->atr.len) == 0)) { sc_pkcs15emu_add_pin(p15card, &p15Id, gemsafe_pin[i].label, &path, gemsafe_pin[i].ref, gemsafe_pin[i].type, gemsafe_pin[i].minlen, gemsafe_pin[i].maxlen, gemsafe_pin[i].flags, gemsafe_pin[i].tries_left, gemsafe_pin[i].pad_char, gemsafe_pin[i].obj_flags); break; } }; /* set private keys */ sc_log(p15card->card->ctx, "Setting private keys"); for (i = 0; i < gemsafe_cert_max; i++) { struct sc_pkcs15_id p15Id, authId, *pauthId; struct sc_path path; int key_ref = 0x03; if (gemsafe_prkeys[i].label == NULL) continue; sc_pkcs15_format_id(gemsafe_prkeys[i].id, &p15Id); if (gemsafe_prkeys[i].auth_id) { sc_pkcs15_format_id(gemsafe_prkeys[i].auth_id, &authId); pauthId = &authId; } else pauthId = NULL; sc_format_path(gemsafe_prkeys[i].path, &path); /* * The key ref may be different for different sites; * by adding flags=n where the low order 4 bits can be * the key ref we can force it. */ if ( p15card->card->flags & 0x0F) { key_ref = p15card->card->flags & 0x0F; sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Overriding key_ref %d with %d\n", gemsafe_prkeys[i].ref, key_ref); } else key_ref = gemsafe_prkeys[i].ref; sc_pkcs15emu_add_prkey(p15card, &p15Id, gemsafe_prkeys[i].label, SC_PKCS15_TYPE_PRKEY_RSA, gemsafe_prkeys[i].modulus_len, gemsafe_prkeys[i].usage, &path, key_ref, pauthId, gemsafe_prkeys[i].obj_flags); } /* select the application DF */ sc_log(p15card->card->ctx, "Selecting application DF"); sc_format_path(GEMSAFE_APP_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* set the application DF */ if (p15card->file_app) free(p15card->file_app); p15card->file_app = file; return SC_SUCCESS; } int sc_pkcs15emu_gemsafeV1_init_ex( sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK) return sc_pkcs15emu_gemsafeV1_init(p15card); else { int r = gemsafe_detect_card(p15card); if (r) return SC_ERROR_WRONG_CARD; return sc_pkcs15emu_gemsafeV1_init(p15card); } } static sc_pkcs15_df_t * sc_pkcs15emu_get_df(sc_pkcs15_card_t *p15card, unsigned int type) { sc_pkcs15_df_t *df; sc_file_t *file; int created = 0; while (1) { for (df = p15card->df_list; df; df = df->next) { if (df->type == type) { if (created) df->enumerated = 1; return df; } } assert(created == 0); file = sc_file_new(); if (!file) return NULL; sc_format_path("11001101", &file->path); sc_pkcs15_add_df(p15card, type, &file->path); sc_file_free(file); created++; } } static int sc_pkcs15emu_add_object(sc_pkcs15_card_t *p15card, int type, const char *label, void *data, const sc_pkcs15_id_t *auth_id, int obj_flags) { sc_pkcs15_object_t *obj; int df_type; obj = calloc(1, sizeof(*obj)); obj->type = type; obj->data = data; if (label) strncpy(obj->label, label, sizeof(obj->label)-1); obj->flags = obj_flags; if (auth_id) obj->auth_id = *auth_id; switch (type & SC_PKCS15_TYPE_CLASS_MASK) { case SC_PKCS15_TYPE_AUTH: df_type = SC_PKCS15_AODF; break; case SC_PKCS15_TYPE_PRKEY: df_type = SC_PKCS15_PRKDF; break; case SC_PKCS15_TYPE_PUBKEY: df_type = SC_PKCS15_PUKDF; break; case SC_PKCS15_TYPE_CERT: df_type = SC_PKCS15_CDF; break; default: sc_log(p15card->card->ctx, "Unknown PKCS15 object type %d", type); free(obj); return SC_ERROR_INVALID_ARGUMENTS; } obj->df = sc_pkcs15emu_get_df(p15card, df_type); sc_pkcs15_add_object(p15card, obj); return 0; } static int sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, const sc_path_t *path, int ref, int type, unsigned int min_length, unsigned int max_length, int flags, int tries_left, const char pad_char, int obj_flags) { sc_pkcs15_auth_info_t *info; info = calloc(1, sizeof(*info)); if (!info) LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); info->auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; info->auth_method = SC_AC_CHV; info->auth_id = *id; info->attrs.pin.min_length = min_length; info->attrs.pin.max_length = max_length; info->attrs.pin.stored_length = max_length; info->attrs.pin.type = type; info->attrs.pin.reference = ref; info->attrs.pin.flags = flags; info->attrs.pin.pad_char = pad_char; info->tries_left = tries_left; info->logged_in = SC_PIN_STATE_UNKNOWN; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, SC_PKCS15_TYPE_AUTH_PIN, label, info, NULL, obj_flags); } static int sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card, int type, int authority, const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label, int obj_flags) { sc_pkcs15_cert_info_t *info; info = calloc(1, sizeof(*info)); if (!info) { LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); } info->id = *id; info->authority = authority; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, type, label, info, NULL, obj_flags); } static int sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, int type, unsigned int modulus_length, int usage, const sc_path_t *path, int ref, const sc_pkcs15_id_t *auth_id, int obj_flags) { sc_pkcs15_prkey_info_t *info; info = calloc(1, sizeof(*info)); if (!info) { LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); } info->id = *id; info->modulus_length = modulus_length; info->usage = usage; info->native = 1; info->access_flags = SC_PKCS15_PRKEY_ACCESS_SENSITIVE | SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE | SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE | SC_PKCS15_PRKEY_ACCESS_LOCAL; info->key_reference = ref; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, type, label, info, auth_id, obj_flags); } /* SC_IMPLEMENT_DRIVER_VERSION("0.9.4") */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_345_5
crossvul-cpp_data_bad_5733_2
/* * Copyright (c) 2012 Fredrik Mellbin * Copyright (c) 2013 Clément Bœsch * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Fieldmatching filter, ported from VFM filter (VapouSsynth) by Clément. * Fredrik Mellbin is the author of the VIVTC/VFM filter, which is itself a * light clone of the TIVTC/TFM (AviSynth) filter written by Kevin Stone * (tritical), the original author. * * @see http://bengal.missouri.edu/~kes25c/ * @see http://www.vapoursynth.com/about/ */ #include <inttypes.h> #include "libavutil/avassert.h" #include "libavutil/imgutils.h" #include "libavutil/opt.h" #include "libavutil/timestamp.h" #include "avfilter.h" #include "internal.h" #define INPUT_MAIN 0 #define INPUT_CLEANSRC 1 enum fieldmatch_parity { FM_PARITY_AUTO = -1, FM_PARITY_BOTTOM = 0, FM_PARITY_TOP = 1, }; enum matching_mode { MODE_PC, MODE_PC_N, MODE_PC_U, MODE_PC_N_UB, MODE_PCN, MODE_PCN_UB, NB_MODE }; enum comb_matching_mode { COMBMATCH_NONE, COMBMATCH_SC, COMBMATCH_FULL, NB_COMBMATCH }; enum comb_dbg { COMBDBG_NONE, COMBDBG_PCN, COMBDBG_PCNUB, NB_COMBDBG }; typedef struct { const AVClass *class; AVFrame *prv, *src, *nxt; ///< main sliding window of 3 frames AVFrame *prv2, *src2, *nxt2; ///< sliding window of the optional second stream int got_frame[2]; ///< frame request flag for each input stream int hsub, vsub; ///< chroma subsampling values uint32_t eof; ///< bitmask for end of stream int64_t lastscdiff; int64_t lastn; /* options */ int order; int ppsrc; enum matching_mode mode; int field; int mchroma; int y0, y1; int64_t scthresh; double scthresh_flt; enum comb_matching_mode combmatch; int combdbg; int cthresh; int chroma; int blockx, blocky; int combpel; /* misc buffers */ uint8_t *map_data[4]; int map_linesize[4]; uint8_t *cmask_data[4]; int cmask_linesize[4]; int *c_array; int tpitchy, tpitchuv; uint8_t *tbuffer; } FieldMatchContext; #define OFFSET(x) offsetof(FieldMatchContext, x) #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM static const AVOption fieldmatch_options[] = { { "order", "specify the assumed field order", OFFSET(order), AV_OPT_TYPE_INT, {.i64=FM_PARITY_AUTO}, -1, 1, FLAGS, "order" }, { "auto", "auto detect parity", 0, AV_OPT_TYPE_CONST, {.i64=FM_PARITY_AUTO}, INT_MIN, INT_MAX, FLAGS, "order" }, { "bff", "assume bottom field first", 0, AV_OPT_TYPE_CONST, {.i64=FM_PARITY_BOTTOM}, INT_MIN, INT_MAX, FLAGS, "order" }, { "tff", "assume top field first", 0, AV_OPT_TYPE_CONST, {.i64=FM_PARITY_TOP}, INT_MIN, INT_MAX, FLAGS, "order" }, { "mode", "set the matching mode or strategy to use", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=MODE_PC_N}, MODE_PC, NB_MODE-1, FLAGS, "mode" }, { "pc", "2-way match (p/c)", 0, AV_OPT_TYPE_CONST, {.i64=MODE_PC}, INT_MIN, INT_MAX, FLAGS, "mode" }, { "pc_n", "2-way match + 3rd match on combed (p/c + u)", 0, AV_OPT_TYPE_CONST, {.i64=MODE_PC_N}, INT_MIN, INT_MAX, FLAGS, "mode" }, { "pc_u", "2-way match + 3rd match (same order) on combed (p/c + u)", 0, AV_OPT_TYPE_CONST, {.i64=MODE_PC_U}, INT_MIN, INT_MAX, FLAGS, "mode" }, { "pc_n_ub", "2-way match + 3rd match on combed + 4th/5th matches if still combed (p/c + u + u/b)", 0, AV_OPT_TYPE_CONST, {.i64=MODE_PC_N_UB}, INT_MIN, INT_MAX, FLAGS, "mode" }, { "pcn", "3-way match (p/c/n)", 0, AV_OPT_TYPE_CONST, {.i64=MODE_PCN}, INT_MIN, INT_MAX, FLAGS, "mode" }, { "pcn_ub", "3-way match + 4th/5th matches on combed (p/c/n + u/b)", 0, AV_OPT_TYPE_CONST, {.i64=MODE_PCN_UB}, INT_MIN, INT_MAX, FLAGS, "mode" }, { "ppsrc", "mark main input as a pre-processed input and activate clean source input stream", OFFSET(ppsrc), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS }, { "field", "set the field to match from", OFFSET(field), AV_OPT_TYPE_INT, {.i64=FM_PARITY_AUTO}, -1, 1, FLAGS, "field" }, { "auto", "automatic (same value as 'order')", 0, AV_OPT_TYPE_CONST, {.i64=FM_PARITY_AUTO}, INT_MIN, INT_MAX, FLAGS, "field" }, { "bottom", "bottom field", 0, AV_OPT_TYPE_CONST, {.i64=FM_PARITY_BOTTOM}, INT_MIN, INT_MAX, FLAGS, "field" }, { "top", "top field", 0, AV_OPT_TYPE_CONST, {.i64=FM_PARITY_TOP}, INT_MIN, INT_MAX, FLAGS, "field" }, { "mchroma", "set whether or not chroma is included during the match comparisons", OFFSET(mchroma), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS }, { "y0", "define an exclusion band which excludes the lines between y0 and y1 from the field matching decision", OFFSET(y0), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS }, { "y1", "define an exclusion band which excludes the lines between y0 and y1 from the field matching decision", OFFSET(y1), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS }, { "scthresh", "set scene change detection threshold", OFFSET(scthresh_flt), AV_OPT_TYPE_DOUBLE, {.dbl=12}, 0, 100, FLAGS }, { "combmatch", "set combmatching mode", OFFSET(combmatch), AV_OPT_TYPE_INT, {.i64=COMBMATCH_SC}, COMBMATCH_NONE, NB_COMBMATCH-1, FLAGS, "combmatching" }, { "none", "disable combmatching", 0, AV_OPT_TYPE_CONST, {.i64=COMBMATCH_NONE}, INT_MIN, INT_MAX, FLAGS, "combmatching" }, { "sc", "enable combmatching only on scene change", 0, AV_OPT_TYPE_CONST, {.i64=COMBMATCH_SC}, INT_MIN, INT_MAX, FLAGS, "combmatching" }, { "full", "enable combmatching all the time", 0, AV_OPT_TYPE_CONST, {.i64=COMBMATCH_FULL}, INT_MIN, INT_MAX, FLAGS, "combmatching" }, { "combdbg", "enable comb debug", OFFSET(combdbg), AV_OPT_TYPE_INT, {.i64=COMBDBG_NONE}, COMBDBG_NONE, NB_COMBDBG-1, FLAGS, "dbglvl" }, { "none", "no forced calculation", 0, AV_OPT_TYPE_CONST, {.i64=COMBDBG_NONE}, INT_MIN, INT_MAX, FLAGS, "dbglvl" }, { "pcn", "calculate p/c/n", 0, AV_OPT_TYPE_CONST, {.i64=COMBDBG_PCN}, INT_MIN, INT_MAX, FLAGS, "dbglvl" }, { "pcnub", "calculate p/c/n/u/b", 0, AV_OPT_TYPE_CONST, {.i64=COMBDBG_PCNUB}, INT_MIN, INT_MAX, FLAGS, "dbglvl" }, { "cthresh", "set the area combing threshold used for combed frame detection", OFFSET(cthresh), AV_OPT_TYPE_INT, {.i64= 9}, -1, 0xff, FLAGS }, { "chroma", "set whether or not chroma is considered in the combed frame decision", OFFSET(chroma), AV_OPT_TYPE_INT, {.i64= 0}, 0, 1, FLAGS }, { "blockx", "set the x-axis size of the window used during combed frame detection", OFFSET(blockx), AV_OPT_TYPE_INT, {.i64=16}, 4, 1<<9, FLAGS }, { "blocky", "set the y-axis size of the window used during combed frame detection", OFFSET(blocky), AV_OPT_TYPE_INT, {.i64=16}, 4, 1<<9, FLAGS }, { "combpel", "set the number of combed pixels inside any of the blocky by blockx size blocks on the frame for the frame to be detected as combed", OFFSET(combpel), AV_OPT_TYPE_INT, {.i64=80}, 0, INT_MAX, FLAGS }, { NULL } }; AVFILTER_DEFINE_CLASS(fieldmatch); static int get_width(const FieldMatchContext *fm, const AVFrame *f, int plane) { return plane ? FF_CEIL_RSHIFT(f->width, fm->hsub) : f->width; } static int get_height(const FieldMatchContext *fm, const AVFrame *f, int plane) { return plane ? FF_CEIL_RSHIFT(f->height, fm->vsub) : f->height; } static int64_t luma_abs_diff(const AVFrame *f1, const AVFrame *f2) { int x, y; const uint8_t *srcp1 = f1->data[0]; const uint8_t *srcp2 = f2->data[0]; const int src1_linesize = f1->linesize[0]; const int src2_linesize = f2->linesize[0]; const int width = f1->width; const int height = f1->height; int64_t acc = 0; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) acc += abs(srcp1[x] - srcp2[x]); srcp1 += src1_linesize; srcp2 += src2_linesize; } return acc; } static void fill_buf(uint8_t *data, int w, int h, int linesize, uint8_t v) { int y; for (y = 0; y < h; y++) { memset(data, v, w); data += linesize; } } static int calc_combed_score(const FieldMatchContext *fm, const AVFrame *src) { int x, y, plane, max_v = 0; const int cthresh = fm->cthresh; const int cthresh6 = cthresh * 6; for (plane = 0; plane < (fm->chroma ? 3 : 1); plane++) { const uint8_t *srcp = src->data[plane]; const int src_linesize = src->linesize[plane]; const int width = get_width (fm, src, plane); const int height = get_height(fm, src, plane); uint8_t *cmkp = fm->cmask_data[plane]; const int cmk_linesize = fm->cmask_linesize[plane]; if (cthresh < 0) { fill_buf(cmkp, width, height, cmk_linesize, 0xff); continue; } fill_buf(cmkp, width, height, cmk_linesize, 0); /* [1 -3 4 -3 1] vertical filter */ #define FILTER(xm2, xm1, xp1, xp2) \ abs( 4 * srcp[x] \ -3 * (srcp[x + (xm1)*src_linesize] + srcp[x + (xp1)*src_linesize]) \ + (srcp[x + (xm2)*src_linesize] + srcp[x + (xp2)*src_linesize])) > cthresh6 /* first line */ for (x = 0; x < width; x++) { const int s1 = abs(srcp[x] - srcp[x + src_linesize]); if (s1 > cthresh && FILTER(2, 1, 1, 2)) cmkp[x] = 0xff; } srcp += src_linesize; cmkp += cmk_linesize; /* second line */ for (x = 0; x < width; x++) { const int s1 = abs(srcp[x] - srcp[x - src_linesize]); const int s2 = abs(srcp[x] - srcp[x + src_linesize]); if (s1 > cthresh && s2 > cthresh && FILTER(2, -1, 1, 2)) cmkp[x] = 0xff; } srcp += src_linesize; cmkp += cmk_linesize; /* all lines minus first two and last two */ for (y = 2; y < height-2; y++) { for (x = 0; x < width; x++) { const int s1 = abs(srcp[x] - srcp[x - src_linesize]); const int s2 = abs(srcp[x] - srcp[x + src_linesize]); if (s1 > cthresh && s2 > cthresh && FILTER(-2, -1, 1, 2)) cmkp[x] = 0xff; } srcp += src_linesize; cmkp += cmk_linesize; } /* before-last line */ for (x = 0; x < width; x++) { const int s1 = abs(srcp[x] - srcp[x - src_linesize]); const int s2 = abs(srcp[x] - srcp[x + src_linesize]); if (s1 > cthresh && s2 > cthresh && FILTER(-2, -1, 1, -2)) cmkp[x] = 0xff; } srcp += src_linesize; cmkp += cmk_linesize; /* last line */ for (x = 0; x < width; x++) { const int s1 = abs(srcp[x] - srcp[x - src_linesize]); if (s1 > cthresh && FILTER(-2, -1, -1, -2)) cmkp[x] = 0xff; } } if (fm->chroma) { uint8_t *cmkp = fm->cmask_data[0]; uint8_t *cmkpU = fm->cmask_data[1]; uint8_t *cmkpV = fm->cmask_data[2]; const int width = FF_CEIL_RSHIFT(src->width, fm->hsub); const int height = FF_CEIL_RSHIFT(src->height, fm->vsub); const int cmk_linesize = fm->cmask_linesize[0] << 1; const int cmk_linesizeUV = fm->cmask_linesize[2]; uint8_t *cmkpp = cmkp - (cmk_linesize>>1); uint8_t *cmkpn = cmkp + (cmk_linesize>>1); uint8_t *cmkpnn = cmkp + cmk_linesize; for (y = 1; y < height - 1; y++) { cmkpp += cmk_linesize; cmkp += cmk_linesize; cmkpn += cmk_linesize; cmkpnn += cmk_linesize; cmkpV += cmk_linesizeUV; cmkpU += cmk_linesizeUV; for (x = 1; x < width - 1; x++) { #define HAS_FF_AROUND(p, lz) (p[x-1 - lz] == 0xff || p[x - lz] == 0xff || p[x+1 - lz] == 0xff || \ p[x-1 ] == 0xff || p[x+1 ] == 0xff || \ p[x-1 + lz] == 0xff || p[x + lz] == 0xff || p[x+1 + lz] == 0xff) if ((cmkpV[x] == 0xff && HAS_FF_AROUND(cmkpV, cmk_linesizeUV)) || (cmkpU[x] == 0xff && HAS_FF_AROUND(cmkpU, cmk_linesizeUV))) { ((uint16_t*)cmkp)[x] = 0xffff; ((uint16_t*)cmkpn)[x] = 0xffff; if (y&1) ((uint16_t*)cmkpp)[x] = 0xffff; else ((uint16_t*)cmkpnn)[x] = 0xffff; } } } } { const int blockx = fm->blockx; const int blocky = fm->blocky; const int xhalf = blockx/2; const int yhalf = blocky/2; const int cmk_linesize = fm->cmask_linesize[0]; const uint8_t *cmkp = fm->cmask_data[0] + cmk_linesize; const int width = src->width; const int height = src->height; const int xblocks = ((width+xhalf)/blockx) + 1; const int xblocks4 = xblocks<<2; const int yblocks = ((height+yhalf)/blocky) + 1; int *c_array = fm->c_array; const int arraysize = (xblocks*yblocks)<<2; int heighta = (height/(blocky/2))*(blocky/2); const int widtha = (width /(blockx/2))*(blockx/2); if (heighta == height) heighta = height - yhalf; memset(c_array, 0, arraysize * sizeof(*c_array)); #define C_ARRAY_ADD(v) do { \ const int box1 = (x / blockx) * 4; \ const int box2 = ((x + xhalf) / blockx) * 4; \ c_array[temp1 + box1 ] += v; \ c_array[temp1 + box2 + 1] += v; \ c_array[temp2 + box1 + 2] += v; \ c_array[temp2 + box2 + 3] += v; \ } while (0) #define VERTICAL_HALF(y_start, y_end) do { \ for (y = y_start; y < y_end; y++) { \ const int temp1 = (y / blocky) * xblocks4; \ const int temp2 = ((y + yhalf) / blocky) * xblocks4; \ for (x = 0; x < width; x++) \ if (cmkp[x - cmk_linesize] == 0xff && \ cmkp[x ] == 0xff && \ cmkp[x + cmk_linesize] == 0xff) \ C_ARRAY_ADD(1); \ cmkp += cmk_linesize; \ } \ } while (0) VERTICAL_HALF(1, yhalf); for (y = yhalf; y < heighta; y += yhalf) { const int temp1 = (y / blocky) * xblocks4; const int temp2 = ((y + yhalf) / blocky) * xblocks4; for (x = 0; x < widtha; x += xhalf) { const uint8_t *cmkp_tmp = cmkp + x; int u, v, sum = 0; for (u = 0; u < yhalf; u++) { for (v = 0; v < xhalf; v++) if (cmkp_tmp[v - cmk_linesize] == 0xff && cmkp_tmp[v ] == 0xff && cmkp_tmp[v + cmk_linesize] == 0xff) sum++; cmkp_tmp += cmk_linesize; } if (sum) C_ARRAY_ADD(sum); } for (x = widtha; x < width; x++) { const uint8_t *cmkp_tmp = cmkp + x; int u, sum = 0; for (u = 0; u < yhalf; u++) { if (cmkp_tmp[-cmk_linesize] == 0xff && cmkp_tmp[ 0] == 0xff && cmkp_tmp[ cmk_linesize] == 0xff) sum++; cmkp_tmp += cmk_linesize; } if (sum) C_ARRAY_ADD(sum); } cmkp += cmk_linesize * yhalf; } VERTICAL_HALF(heighta, height - 1); for (x = 0; x < arraysize; x++) if (c_array[x] > max_v) max_v = c_array[x]; } return max_v; } // the secret is that tbuffer is an interlaced, offset subset of all the lines static void build_abs_diff_mask(const uint8_t *prvp, int prv_linesize, const uint8_t *nxtp, int nxt_linesize, uint8_t *tbuffer, int tbuf_linesize, int width, int height) { int y, x; prvp -= prv_linesize; nxtp -= nxt_linesize; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) tbuffer[x] = FFABS(prvp[x] - nxtp[x]); prvp += prv_linesize; nxtp += nxt_linesize; tbuffer += tbuf_linesize; } } /** * Build a map over which pixels differ a lot/a little */ static void build_diff_map(FieldMatchContext *fm, const uint8_t *prvp, int prv_linesize, const uint8_t *nxtp, int nxt_linesize, uint8_t *dstp, int dst_linesize, int height, int width, int plane) { int x, y, u, diff, count; int tpitch = plane ? fm->tpitchuv : fm->tpitchy; const uint8_t *dp = fm->tbuffer + tpitch; build_abs_diff_mask(prvp, prv_linesize, nxtp, nxt_linesize, fm->tbuffer, tpitch, width, height>>1); for (y = 2; y < height - 2; y += 2) { for (x = 1; x < width - 1; x++) { diff = dp[x]; if (diff > 3) { for (count = 0, u = x-1; u < x+2 && count < 2; u++) { count += dp[u-tpitch] > 3; count += dp[u ] > 3; count += dp[u+tpitch] > 3; } if (count > 1) { dstp[x] = 1; if (diff > 19) { int upper = 0, lower = 0; for (count = 0, u = x-1; u < x+2 && count < 6; u++) { if (dp[u-tpitch] > 19) { count++; upper = 1; } if (dp[u ] > 19) count++; if (dp[u+tpitch] > 19) { count++; lower = 1; } } if (count > 3) { if (upper && lower) { dstp[x] |= 1<<1; } else { int upper2 = 0, lower2 = 0; for (u = FFMAX(x-4,0); u < FFMIN(x+5,width); u++) { if (y != 2 && dp[u-2*tpitch] > 19) upper2 = 1; if ( dp[u- tpitch] > 19) upper = 1; if ( dp[u+ tpitch] > 19) lower = 1; if (y != height-4 && dp[u+2*tpitch] > 19) lower2 = 1; } if ((upper && (lower || upper2)) || (lower && (upper || lower2))) dstp[x] |= 1<<1; else if (count > 5) dstp[x] |= 1<<2; } } } } } } dp += tpitch; dstp += dst_linesize; } } enum { mP, mC, mN, mB, mU }; static int get_field_base(int match, int field) { return match < 3 ? 2 - field : 1 + field; } static AVFrame *select_frame(FieldMatchContext *fm, int match) { if (match == mP || match == mB) return fm->prv; else if (match == mN || match == mU) return fm->nxt; else /* match == mC */ return fm->src; } static int compare_fields(FieldMatchContext *fm, int match1, int match2, int field) { int plane, ret; uint64_t accumPc = 0, accumPm = 0, accumPml = 0; uint64_t accumNc = 0, accumNm = 0, accumNml = 0; int norm1, norm2, mtn1, mtn2; float c1, c2, mr; const AVFrame *src = fm->src; for (plane = 0; plane < (fm->mchroma ? 3 : 1); plane++) { int x, y, temp1, temp2, fbase; const AVFrame *prev, *next; uint8_t *mapp = fm->map_data[plane]; int map_linesize = fm->map_linesize[plane]; const uint8_t *srcp = src->data[plane]; const int src_linesize = src->linesize[plane]; const int srcf_linesize = src_linesize << 1; int prv_linesize, nxt_linesize; int prvf_linesize, nxtf_linesize; const int width = get_width (fm, src, plane); const int height = get_height(fm, src, plane); const int y0a = fm->y0 >> (plane != 0); const int y1a = fm->y1 >> (plane != 0); const int startx = (plane == 0 ? 8 : 4); const int stopx = width - startx; const uint8_t *srcpf, *srcf, *srcnf; const uint8_t *prvpf, *prvnf, *nxtpf, *nxtnf; fill_buf(mapp, width, height, map_linesize, 0); /* match1 */ fbase = get_field_base(match1, field); srcf = srcp + (fbase + 1) * src_linesize; srcpf = srcf - srcf_linesize; srcnf = srcf + srcf_linesize; mapp = mapp + fbase * map_linesize; prev = select_frame(fm, match1); prv_linesize = prev->linesize[plane]; prvf_linesize = prv_linesize << 1; prvpf = prev->data[plane] + fbase * prv_linesize; // previous frame, previous field prvnf = prvpf + prvf_linesize; // previous frame, next field /* match2 */ fbase = get_field_base(match2, field); next = select_frame(fm, match2); nxt_linesize = next->linesize[plane]; nxtf_linesize = nxt_linesize << 1; nxtpf = next->data[plane] + fbase * nxt_linesize; // next frame, previous field nxtnf = nxtpf + nxtf_linesize; // next frame, next field map_linesize <<= 1; if ((match1 >= 3 && field == 1) || (match1 < 3 && field != 1)) build_diff_map(fm, prvpf, prvf_linesize, nxtpf, nxtf_linesize, mapp, map_linesize, height, width, plane); else build_diff_map(fm, prvnf, prvf_linesize, nxtnf, nxtf_linesize, mapp + map_linesize, map_linesize, height, width, plane); for (y = 2; y < height - 2; y += 2) { if (y0a == y1a || y < y0a || y > y1a) { for (x = startx; x < stopx; x++) { if (mapp[x] > 0 || mapp[x + map_linesize] > 0) { temp1 = srcpf[x] + (srcf[x] << 2) + srcnf[x]; // [1 4 1] temp2 = abs(3 * (prvpf[x] + prvnf[x]) - temp1); if (temp2 > 23 && ((mapp[x]&1) || (mapp[x + map_linesize]&1))) accumPc += temp2; if (temp2 > 42) { if ((mapp[x]&2) || (mapp[x + map_linesize]&2)) accumPm += temp2; if ((mapp[x]&4) || (mapp[x + map_linesize]&4)) accumPml += temp2; } temp2 = abs(3 * (nxtpf[x] + nxtnf[x]) - temp1); if (temp2 > 23 && ((mapp[x]&1) || (mapp[x + map_linesize]&1))) accumNc += temp2; if (temp2 > 42) { if ((mapp[x]&2) || (mapp[x + map_linesize]&2)) accumNm += temp2; if ((mapp[x]&4) || (mapp[x + map_linesize]&4)) accumNml += temp2; } } } } prvpf += prvf_linesize; prvnf += prvf_linesize; srcpf += srcf_linesize; srcf += srcf_linesize; srcnf += srcf_linesize; nxtpf += nxtf_linesize; nxtnf += nxtf_linesize; mapp += map_linesize; } } if (accumPm < 500 && accumNm < 500 && (accumPml >= 500 || accumNml >= 500) && FFMAX(accumPml,accumNml) > 3*FFMIN(accumPml,accumNml)) { accumPm = accumPml; accumNm = accumNml; } norm1 = (int)((accumPc / 6.0f) + 0.5f); norm2 = (int)((accumNc / 6.0f) + 0.5f); mtn1 = (int)((accumPm / 6.0f) + 0.5f); mtn2 = (int)((accumNm / 6.0f) + 0.5f); c1 = ((float)FFMAX(norm1,norm2)) / ((float)FFMAX(FFMIN(norm1,norm2),1)); c2 = ((float)FFMAX(mtn1, mtn2)) / ((float)FFMAX(FFMIN(mtn1, mtn2), 1)); mr = ((float)FFMAX(mtn1, mtn2)) / ((float)FFMAX(FFMAX(norm1,norm2),1)); if (((mtn1 >= 500 || mtn2 >= 500) && (mtn1*2 < mtn2*1 || mtn2*2 < mtn1*1)) || ((mtn1 >= 1000 || mtn2 >= 1000) && (mtn1*3 < mtn2*2 || mtn2*3 < mtn1*2)) || ((mtn1 >= 2000 || mtn2 >= 2000) && (mtn1*5 < mtn2*4 || mtn2*5 < mtn1*4)) || ((mtn1 >= 4000 || mtn2 >= 4000) && c2 > c1)) ret = mtn1 > mtn2 ? match2 : match1; else if (mr > 0.005 && FFMAX(mtn1, mtn2) > 150 && (mtn1*2 < mtn2*1 || mtn2*2 < mtn1*1)) ret = mtn1 > mtn2 ? match2 : match1; else ret = norm1 > norm2 ? match2 : match1; return ret; } static void copy_fields(const FieldMatchContext *fm, AVFrame *dst, const AVFrame *src, int field) { int plane; for (plane = 0; plane < 4 && src->data[plane]; plane++) av_image_copy_plane(dst->data[plane] + field*dst->linesize[plane], dst->linesize[plane] << 1, src->data[plane] + field*src->linesize[plane], src->linesize[plane] << 1, get_width(fm, src, plane), get_height(fm, src, plane) / 2); } static AVFrame *create_weave_frame(AVFilterContext *ctx, int match, int field, const AVFrame *prv, AVFrame *src, const AVFrame *nxt) { AVFrame *dst; FieldMatchContext *fm = ctx->priv; if (match == mC) { dst = av_frame_clone(src); } else { AVFilterLink *outlink = ctx->outputs[0]; dst = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!dst) return NULL; av_frame_copy_props(dst, src); switch (match) { case mP: copy_fields(fm, dst, src, 1-field); copy_fields(fm, dst, prv, field); break; case mN: copy_fields(fm, dst, src, 1-field); copy_fields(fm, dst, nxt, field); break; case mB: copy_fields(fm, dst, src, field); copy_fields(fm, dst, prv, 1-field); break; case mU: copy_fields(fm, dst, src, field); copy_fields(fm, dst, nxt, 1-field); break; default: av_assert0(0); } } return dst; } static int checkmm(AVFilterContext *ctx, int *combs, int m1, int m2, AVFrame **gen_frames, int field) { const FieldMatchContext *fm = ctx->priv; #define LOAD_COMB(mid) do { \ if (combs[mid] < 0) { \ if (!gen_frames[mid]) \ gen_frames[mid] = create_weave_frame(ctx, mid, field, \ fm->prv, fm->src, fm->nxt); \ combs[mid] = calc_combed_score(fm, gen_frames[mid]); \ } \ } while (0) LOAD_COMB(m1); LOAD_COMB(m2); if ((combs[m2] * 3 < combs[m1] || (combs[m2] * 2 < combs[m1] && combs[m1] > fm->combpel)) && abs(combs[m2] - combs[m1]) >= 30 && combs[m2] < fm->combpel) return m2; else return m1; } static const int fxo0m[] = { mP, mC, mN, mB, mU }; static const int fxo1m[] = { mN, mC, mP, mU, mB }; static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; AVFilterLink *outlink = ctx->outputs[0]; FieldMatchContext *fm = ctx->priv; int combs[] = { -1, -1, -1, -1, -1 }; int order, field, i, match, sc = 0; const int *fxo; AVFrame *gen_frames[] = { NULL, NULL, NULL, NULL, NULL }; AVFrame *dst; /* update frames queue(s) */ #define SLIDING_FRAME_WINDOW(prv, src, nxt) do { \ if (prv != src) /* 2nd loop exception (1st has prv==src and we don't want to loose src) */ \ av_frame_free(&prv); \ prv = src; \ src = nxt; \ if (in) \ nxt = in; \ if (!prv) \ prv = src; \ if (!prv) /* received only one frame at that point */ \ return 0; \ av_assert0(prv && src && nxt); \ } while (0) if (FF_INLINK_IDX(inlink) == INPUT_MAIN) { SLIDING_FRAME_WINDOW(fm->prv, fm->src, fm->nxt); fm->got_frame[INPUT_MAIN] = 1; } else { SLIDING_FRAME_WINDOW(fm->prv2, fm->src2, fm->nxt2); fm->got_frame[INPUT_CLEANSRC] = 1; } if (!fm->got_frame[INPUT_MAIN] || (fm->ppsrc && !fm->got_frame[INPUT_CLEANSRC])) return 0; fm->got_frame[INPUT_MAIN] = fm->got_frame[INPUT_CLEANSRC] = 0; in = fm->src; /* parity */ order = fm->order != FM_PARITY_AUTO ? fm->order : (in->interlaced_frame ? in->top_field_first : 1); field = fm->field != FM_PARITY_AUTO ? fm->field : order; av_assert0(order == 0 || order == 1 || field == 0 || field == 1); fxo = field ^ order ? fxo1m : fxo0m; /* debug mode: we generate all the fields combinations and their associated * combed score. XXX: inject as frame metadata? */ if (fm->combdbg) { for (i = 0; i < FF_ARRAY_ELEMS(combs); i++) { if (i > mN && fm->combdbg == COMBDBG_PCN) break; gen_frames[i] = create_weave_frame(ctx, i, field, fm->prv, fm->src, fm->nxt); if (!gen_frames[i]) return AVERROR(ENOMEM); combs[i] = calc_combed_score(fm, gen_frames[i]); } av_log(ctx, AV_LOG_INFO, "COMBS: %3d %3d %3d %3d %3d\n", combs[0], combs[1], combs[2], combs[3], combs[4]); } else { gen_frames[mC] = av_frame_clone(fm->src); if (!gen_frames[mC]) return AVERROR(ENOMEM); } /* p/c selection and optional 3-way p/c/n matches */ match = compare_fields(fm, fxo[mC], fxo[mP], field); if (fm->mode == MODE_PCN || fm->mode == MODE_PCN_UB) match = compare_fields(fm, match, fxo[mN], field); /* scene change check */ if (fm->combmatch == COMBMATCH_SC) { if (fm->lastn == outlink->frame_count - 1) { if (fm->lastscdiff > fm->scthresh) sc = 1; } else if (luma_abs_diff(fm->prv, fm->src) > fm->scthresh) { sc = 1; } if (!sc) { fm->lastn = outlink->frame_count; fm->lastscdiff = luma_abs_diff(fm->src, fm->nxt); sc = fm->lastscdiff > fm->scthresh; } } if (fm->combmatch == COMBMATCH_FULL || (fm->combmatch == COMBMATCH_SC && sc)) { switch (fm->mode) { /* 2-way p/c matches */ case MODE_PC: match = checkmm(ctx, combs, match, match == fxo[mP] ? fxo[mC] : fxo[mP], gen_frames, field); break; case MODE_PC_N: match = checkmm(ctx, combs, match, fxo[mN], gen_frames, field); break; case MODE_PC_U: match = checkmm(ctx, combs, match, fxo[mU], gen_frames, field); break; case MODE_PC_N_UB: match = checkmm(ctx, combs, match, fxo[mN], gen_frames, field); match = checkmm(ctx, combs, match, fxo[mU], gen_frames, field); match = checkmm(ctx, combs, match, fxo[mB], gen_frames, field); break; /* 3-way p/c/n matches */ case MODE_PCN: match = checkmm(ctx, combs, match, match == fxo[mP] ? fxo[mC] : fxo[mP], gen_frames, field); break; case MODE_PCN_UB: match = checkmm(ctx, combs, match, fxo[mU], gen_frames, field); match = checkmm(ctx, combs, match, fxo[mB], gen_frames, field); break; default: av_assert0(0); } } /* get output frame and drop the others */ if (fm->ppsrc) { /* field matching was based on a filtered/post-processed input, we now * pick the untouched fields from the clean source */ dst = create_weave_frame(ctx, match, field, fm->prv2, fm->src2, fm->nxt2); } else { if (!gen_frames[match]) { // XXX: is that possible? dst = create_weave_frame(ctx, match, field, fm->prv, fm->src, fm->nxt); } else { dst = gen_frames[match]; gen_frames[match] = NULL; } } if (!dst) return AVERROR(ENOMEM); for (i = 0; i < FF_ARRAY_ELEMS(gen_frames); i++) av_frame_free(&gen_frames[i]); /* mark the frame we are unable to match properly as interlaced so a proper * de-interlacer can take the relay */ dst->interlaced_frame = combs[match] >= fm->combpel; if (dst->interlaced_frame) { av_log(ctx, AV_LOG_WARNING, "Frame #%"PRId64" at %s is still interlaced\n", outlink->frame_count, av_ts2timestr(in->pts, &inlink->time_base)); dst->top_field_first = field; } av_log(ctx, AV_LOG_DEBUG, "SC:%d | COMBS: %3d %3d %3d %3d %3d (combpel=%d)" " match=%d combed=%s\n", sc, combs[0], combs[1], combs[2], combs[3], combs[4], fm->combpel, match, dst->interlaced_frame ? "YES" : "NO"); return ff_filter_frame(outlink, dst); } static int request_inlink(AVFilterContext *ctx, int lid) { int ret = 0; FieldMatchContext *fm = ctx->priv; if (!fm->got_frame[lid]) { AVFilterLink *inlink = ctx->inputs[lid]; ret = ff_request_frame(inlink); if (ret == AVERROR_EOF) { // flushing fm->eof |= 1 << lid; ret = filter_frame(inlink, NULL); } } return ret; } static int request_frame(AVFilterLink *outlink) { int ret; AVFilterContext *ctx = outlink->src; FieldMatchContext *fm = ctx->priv; const uint32_t eof_mask = 1<<INPUT_MAIN | fm->ppsrc<<INPUT_CLEANSRC; if ((fm->eof & eof_mask) == eof_mask) // flush done? return AVERROR_EOF; if ((ret = request_inlink(ctx, INPUT_MAIN)) < 0) return ret; if (fm->ppsrc && (ret = request_inlink(ctx, INPUT_CLEANSRC)) < 0) return ret; return 0; } static int query_formats(AVFilterContext *ctx) { // TODO: second input source can support >8bit depth static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_NONE }; ff_set_common_formats(ctx, ff_make_format_list(pix_fmts)); return 0; } static int config_input(AVFilterLink *inlink) { int ret; AVFilterContext *ctx = inlink->dst; FieldMatchContext *fm = ctx->priv; const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format); const int w = inlink->w; const int h = inlink->h; fm->scthresh = (int64_t)((w * h * 255.0 * fm->scthresh_flt) / 100.0); if ((ret = av_image_alloc(fm->map_data, fm->map_linesize, w, h, inlink->format, 32)) < 0 || (ret = av_image_alloc(fm->cmask_data, fm->cmask_linesize, w, h, inlink->format, 32)) < 0) return ret; fm->hsub = pix_desc->log2_chroma_w; fm->vsub = pix_desc->log2_chroma_h; fm->tpitchy = FFALIGN(w, 16); fm->tpitchuv = FFALIGN(w >> 1, 16); fm->tbuffer = av_malloc(h/2 * fm->tpitchy); fm->c_array = av_malloc((((w + fm->blockx/2)/fm->blockx)+1) * (((h + fm->blocky/2)/fm->blocky)+1) * 4 * sizeof(*fm->c_array)); if (!fm->tbuffer || !fm->c_array) return AVERROR(ENOMEM); return 0; } static av_cold int fieldmatch_init(AVFilterContext *ctx) { const FieldMatchContext *fm = ctx->priv; AVFilterPad pad = { .name = av_strdup("main"), .type = AVMEDIA_TYPE_VIDEO, .filter_frame = filter_frame, .config_props = config_input, }; if (!pad.name) return AVERROR(ENOMEM); ff_insert_inpad(ctx, INPUT_MAIN, &pad); if (fm->ppsrc) { pad.name = av_strdup("clean_src"); pad.config_props = NULL; if (!pad.name) return AVERROR(ENOMEM); ff_insert_inpad(ctx, INPUT_CLEANSRC, &pad); } if ((fm->blockx & (fm->blockx - 1)) || (fm->blocky & (fm->blocky - 1))) { av_log(ctx, AV_LOG_ERROR, "blockx and blocky settings must be power of two\n"); return AVERROR(EINVAL); } if (fm->combpel > fm->blockx * fm->blocky) { av_log(ctx, AV_LOG_ERROR, "Combed pixel should not be larger than blockx x blocky\n"); return AVERROR(EINVAL); } return 0; } static av_cold void fieldmatch_uninit(AVFilterContext *ctx) { int i; FieldMatchContext *fm = ctx->priv; if (fm->prv != fm->src) av_frame_free(&fm->prv); if (fm->nxt != fm->src) av_frame_free(&fm->nxt); av_frame_free(&fm->src); av_freep(&fm->map_data[0]); av_freep(&fm->cmask_data[0]); av_freep(&fm->tbuffer); av_freep(&fm->c_array); for (i = 0; i < ctx->nb_inputs; i++) av_freep(&ctx->input_pads[i].name); } static int config_output(AVFilterLink *outlink) { AVFilterContext *ctx = outlink->src; const FieldMatchContext *fm = ctx->priv; const AVFilterLink *inlink = ctx->inputs[fm->ppsrc ? INPUT_CLEANSRC : INPUT_MAIN]; outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP; outlink->time_base = inlink->time_base; outlink->sample_aspect_ratio = inlink->sample_aspect_ratio; outlink->frame_rate = inlink->frame_rate; outlink->w = inlink->w; outlink->h = inlink->h; return 0; } static const AVFilterPad fieldmatch_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .request_frame = request_frame, .config_props = config_output, }, { NULL } }; AVFilter avfilter_vf_fieldmatch = { .name = "fieldmatch", .description = NULL_IF_CONFIG_SMALL("Field matching for inverse telecine."), .query_formats = query_formats, .priv_size = sizeof(FieldMatchContext), .init = fieldmatch_init, .uninit = fieldmatch_uninit, .inputs = NULL, .outputs = fieldmatch_outputs, .priv_class = &fieldmatch_class, .flags = AVFILTER_FLAG_DYNAMIC_INPUTS, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5733_2
crossvul-cpp_data_good_2040_0
/*- * Copyright (c) 2008 Christos Zoulas * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Parse Composite Document Files, the format used in Microsoft Office * document files before they switched to zipped XML. * Info from: http://sc.openoffice.org/compdocfileformat.pdf * * N.B. This is the "Composite Document File" format, and not the * "Compound Document Format", nor the "Channel Definition Format". */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: cdf.c,v 1.59 2014/05/14 23:22:48 christos Exp $") #endif #include <assert.h> #ifdef CDF_DEBUG #include <err.h> #endif #include <stdlib.h> #include <unistd.h> #include <string.h> #include <time.h> #include <ctype.h> #ifdef HAVE_LIMITS_H #include <limits.h> #endif #ifndef EFTYPE #define EFTYPE EINVAL #endif #include "cdf.h" #ifdef CDF_DEBUG #define DPRINTF(a) printf a, fflush(stdout) #else #define DPRINTF(a) #endif static union { char s[4]; uint32_t u; } cdf_bo; #define NEED_SWAP (cdf_bo.u == (uint32_t)0x01020304) #define CDF_TOLE8(x) ((uint64_t)(NEED_SWAP ? _cdf_tole8(x) : (uint64_t)(x))) #define CDF_TOLE4(x) ((uint32_t)(NEED_SWAP ? _cdf_tole4(x) : (uint32_t)(x))) #define CDF_TOLE2(x) ((uint16_t)(NEED_SWAP ? _cdf_tole2(x) : (uint16_t)(x))) #define CDF_GETUINT32(x, y) cdf_getuint32(x, y) /* * swap a short */ static uint16_t _cdf_tole2(uint16_t sv) { uint16_t rv; uint8_t *s = (uint8_t *)(void *)&sv; uint8_t *d = (uint8_t *)(void *)&rv; d[0] = s[1]; d[1] = s[0]; return rv; } /* * swap an int */ static uint32_t _cdf_tole4(uint32_t sv) { uint32_t rv; uint8_t *s = (uint8_t *)(void *)&sv; uint8_t *d = (uint8_t *)(void *)&rv; d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0]; return rv; } /* * swap a quad */ static uint64_t _cdf_tole8(uint64_t sv) { uint64_t rv; uint8_t *s = (uint8_t *)(void *)&sv; uint8_t *d = (uint8_t *)(void *)&rv; d[0] = s[7]; d[1] = s[6]; d[2] = s[5]; d[3] = s[4]; d[4] = s[3]; d[5] = s[2]; d[6] = s[1]; d[7] = s[0]; return rv; } /* * grab a uint32_t from a possibly unaligned address, and return it in * the native host order. */ static uint32_t cdf_getuint32(const uint8_t *p, size_t offs) { uint32_t rv; (void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv)); return CDF_TOLE4(rv); } #define CDF_UNPACK(a) \ (void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a) #define CDF_UNPACKA(a) \ (void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a) uint16_t cdf_tole2(uint16_t sv) { return CDF_TOLE2(sv); } uint32_t cdf_tole4(uint32_t sv) { return CDF_TOLE4(sv); } uint64_t cdf_tole8(uint64_t sv) { return CDF_TOLE8(sv); } void cdf_swap_header(cdf_header_t *h) { size_t i; h->h_magic = CDF_TOLE8(h->h_magic); h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]); h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]); h->h_revision = CDF_TOLE2(h->h_revision); h->h_version = CDF_TOLE2(h->h_version); h->h_byte_order = CDF_TOLE2(h->h_byte_order); h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2); h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2); h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat); h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory); h->h_min_size_standard_stream = CDF_TOLE4(h->h_min_size_standard_stream); h->h_secid_first_sector_in_short_sat = CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_short_sat); h->h_num_sectors_in_short_sat = CDF_TOLE4(h->h_num_sectors_in_short_sat); h->h_secid_first_sector_in_master_sat = CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_master_sat); h->h_num_sectors_in_master_sat = CDF_TOLE4(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) h->h_master_sat[i] = CDF_TOLE4((uint32_t)h->h_master_sat[i]); } void cdf_unpack_header(cdf_header_t *h, char *buf) { size_t i; size_t len = 0; CDF_UNPACK(h->h_magic); CDF_UNPACKA(h->h_uuid); CDF_UNPACK(h->h_revision); CDF_UNPACK(h->h_version); CDF_UNPACK(h->h_byte_order); CDF_UNPACK(h->h_sec_size_p2); CDF_UNPACK(h->h_short_sec_size_p2); CDF_UNPACKA(h->h_unused0); CDF_UNPACK(h->h_num_sectors_in_sat); CDF_UNPACK(h->h_secid_first_directory); CDF_UNPACKA(h->h_unused1); CDF_UNPACK(h->h_min_size_standard_stream); CDF_UNPACK(h->h_secid_first_sector_in_short_sat); CDF_UNPACK(h->h_num_sectors_in_short_sat); CDF_UNPACK(h->h_secid_first_sector_in_master_sat); CDF_UNPACK(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) CDF_UNPACK(h->h_master_sat[i]); } void cdf_swap_dir(cdf_directory_t *d) { d->d_namelen = CDF_TOLE2(d->d_namelen); d->d_left_child = CDF_TOLE4((uint32_t)d->d_left_child); d->d_right_child = CDF_TOLE4((uint32_t)d->d_right_child); d->d_storage = CDF_TOLE4((uint32_t)d->d_storage); d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]); d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]); d->d_flags = CDF_TOLE4(d->d_flags); d->d_created = CDF_TOLE8((uint64_t)d->d_created); d->d_modified = CDF_TOLE8((uint64_t)d->d_modified); d->d_stream_first_sector = CDF_TOLE4((uint32_t)d->d_stream_first_sector); d->d_size = CDF_TOLE4(d->d_size); } void cdf_swap_class(cdf_classid_t *d) { d->cl_dword = CDF_TOLE4(d->cl_dword); d->cl_word[0] = CDF_TOLE2(d->cl_word[0]); d->cl_word[1] = CDF_TOLE2(d->cl_word[1]); } void cdf_unpack_dir(cdf_directory_t *d, char *buf) { size_t len = 0; CDF_UNPACKA(d->d_name); CDF_UNPACK(d->d_namelen); CDF_UNPACK(d->d_type); CDF_UNPACK(d->d_color); CDF_UNPACK(d->d_left_child); CDF_UNPACK(d->d_right_child); CDF_UNPACK(d->d_storage); CDF_UNPACKA(d->d_storage_uuid); CDF_UNPACK(d->d_flags); CDF_UNPACK(d->d_created); CDF_UNPACK(d->d_modified); CDF_UNPACK(d->d_stream_first_sector); CDF_UNPACK(d->d_size); CDF_UNPACK(d->d_unused0); } static int cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = (const char *)sst->sst_tab; const char *e = ((const char *)p) + tail; (void)&line; if (e >= b && (size_t)(e - b) <= CDF_SEC_SIZE(h) * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u" " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), CDF_SEC_SIZE(h) * sst->sst_len, CDF_SEC_SIZE(h), sst->sst_len)); errno = EFTYPE; return -1; } static ssize_t cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len) { size_t siz = (size_t)off + len; if ((off_t)(off + len) != (off_t)siz) { errno = EINVAL; return -1; } if (info->i_buf != NULL && info->i_len >= siz) { (void)memcpy(buf, &info->i_buf[off], len); return (ssize_t)len; } if (info->i_fd == -1) return -1; if (pread(info->i_fd, buf, len, off) != (ssize_t)len) return -1; return (ssize_t)len; } int cdf_read_header(const cdf_info_t *info, cdf_header_t *h) { char buf[512]; (void)memcpy(cdf_bo.s, "\01\02\03\04", 4); if (cdf_read(info, (off_t)0, buf, sizeof(buf)) == -1) return -1; cdf_unpack_header(h, buf); cdf_swap_header(h); if (h->h_magic != CDF_MAGIC) { DPRINTF(("Bad magic 0x%" INT64_T_FORMAT "x != 0x%" INT64_T_FORMAT "x\n", (unsigned long long)h->h_magic, (unsigned long long)CDF_MAGIC)); goto out; } if (h->h_sec_size_p2 > 20) { DPRINTF(("Bad sector size 0x%u\n", h->h_sec_size_p2)); goto out; } if (h->h_short_sec_size_p2 > 20) { DPRINTF(("Bad short sector size 0x%u\n", h->h_short_sec_size_p2)); goto out; } return 0; out: errno = EFTYPE; return -1; } ssize_t cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SEC_SIZE(h); size_t pos = CDF_SEC_POS(h, id); assert(ss == len); return cdf_read(info, (off_t)pos, ((char *)buf) + offs, len); } ssize_t cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) { DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", pos + len, CDF_SEC_SIZE(h) * sst->sst_len)); return -1; } (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + pos, len); return len; } /* * Read the sector allocation table. */ int cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat) { size_t i, j, k; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t *msa, mid, sec; size_t nsatpersec = (ss / sizeof(mid)) - 1; for (i = 0; i < __arraycount(h->h_master_sat); i++) if (h->h_master_sat[i] == CDF_SECID_FREE) break; #define CDF_SEC_LIMIT (UINT32_MAX / (4 * ss)) if ((nsatpersec > 0 && h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) || i > CDF_SEC_LIMIT) { DPRINTF(("Number of sectors in master SAT too big %u %" SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i)); errno = EFTYPE; return -1; } sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i; DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n", sat->sat_len, ss)); if ((sat->sat_tab = CAST(cdf_secid_t *, calloc(sat->sat_len, ss))) == NULL) return -1; for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] < 0) break; if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, h->h_master_sat[i]) != (ssize_t)ss) { DPRINTF(("Reading sector %d", h->h_master_sat[i])); goto out1; } } if ((msa = CAST(cdf_secid_t *, calloc(1, ss))) == NULL) goto out1; mid = h->h_secid_first_sector_in_master_sat; for (j = 0; j < h->h_num_sectors_in_master_sat; j++) { if (mid < 0) goto out; if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Reading master sector loop limit")); errno = EFTYPE; goto out2; } if (cdf_read_sector(info, msa, 0, ss, h, mid) != (ssize_t)ss) { DPRINTF(("Reading master sector %d", mid)); goto out2; } for (k = 0; k < nsatpersec; k++, i++) { sec = CDF_TOLE4((uint32_t)msa[k]); if (sec < 0) goto out; if (i >= sat->sat_len) { DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT "u >= %" SIZE_T_FORMAT "u", i, sat->sat_len)); errno = EFTYPE; goto out2; } if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, sec) != (ssize_t)ss) { DPRINTF(("Reading sector %d", CDF_TOLE4(msa[k]))); goto out2; } } mid = CDF_TOLE4((uint32_t)msa[nsatpersec]); } out: sat->sat_len = i; free(msa); return 0; out2: free(msa); out1: free(sat->sat_tab); return -1; } size_t cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size) { size_t i, j; cdf_secid_t maxsector = (cdf_secid_t)(sat->sat_len * size); DPRINTF(("Chain:")); for (j = i = 0; sid >= 0; i++, j++) { DPRINTF((" %d", sid)); if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Counting chain loop limit")); errno = EFTYPE; return (size_t)-1; } if (sid > maxsector) { DPRINTF(("Sector %d > %d\n", sid, maxsector)); errno = EFTYPE; return (size_t)-1; } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } if (i == 0) { DPRINTF((" none, sid: %d\n", sid)); return (size_t)-1; } DPRINTF(("\n")); return i; } int cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SEC_SIZE(h), i, j; ssize_t nr; scn->sst_len = cdf_count_chain(sat, sid, ss); scn->sst_dirlen = len; if (scn->sst_len == (size_t)-1) return -1; scn->sst_tab = calloc(scn->sst_len, ss); if (scn->sst_tab == NULL) return -1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read long sector chain loop limit")); errno = EFTYPE; goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading long sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); errno = EFTYPE; goto out; } if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h, sid)) != (ssize_t)ss) { if (i == scn->sst_len - 1 && nr > 0) { /* Last sector might be truncated */ return 0; } DPRINTF(("Reading long sector chain %d", sid)); goto out; } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } return 0; out: free(scn->sst_tab); return -1; } int cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SHORT_SEC_SIZE(h), i, j; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1) return -1; scn->sst_tab = calloc(scn->sst_len, ss); if (scn->sst_tab == NULL) return -1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); errno = EFTYPE; goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); errno = EFTYPE; goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != (ssize_t)ss) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]); } return 0; out: free(scn->sst_tab); return -1; } int cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL) return cdf_read_short_sector_chain(h, ssat, sst, sid, len, scn); else return cdf_read_long_sector_chain(info, h, sat, sid, len, scn); } int cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_dir_t *dir) { size_t i, j; size_t ss = CDF_SEC_SIZE(h), ns, nd; char *buf; cdf_secid_t sid = h->h_secid_first_directory; ns = cdf_count_chain(sat, sid, ss); if (ns == (size_t)-1) return -1; nd = ss / CDF_DIRECTORY_SIZE; dir->dir_len = ns * nd; dir->dir_tab = CAST(cdf_directory_t *, calloc(dir->dir_len, sizeof(dir->dir_tab[0]))); if (dir->dir_tab == NULL) return -1; if ((buf = CAST(char *, malloc(ss))) == NULL) { free(dir->dir_tab); return -1; } for (j = i = 0; i < ns; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read dir loop limit")); errno = EFTYPE; goto out; } if (cdf_read_sector(info, buf, 0, ss, h, sid) != (ssize_t)ss) { DPRINTF(("Reading directory sector %d", sid)); goto out; } for (j = 0; j < nd; j++) { cdf_unpack_dir(&dir->dir_tab[i * nd + j], &buf[j * CDF_DIRECTORY_SIZE]); } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } if (NEED_SWAP) for (i = 0; i < dir->dir_len; i++) cdf_swap_dir(&dir->dir_tab[i]); free(buf); return 0; out: free(dir->dir_tab); free(buf); return -1; } int cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_sat_t *ssat) { size_t i, j; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t sid = h->h_secid_first_sector_in_short_sat; ssat->sat_len = cdf_count_chain(sat, sid, CDF_SEC_SIZE(h)); if (ssat->sat_len == (size_t)-1) return -1; ssat->sat_tab = CAST(cdf_secid_t *, calloc(ssat->sat_len, ss)); if (ssat->sat_tab == NULL) return -1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sat sector loop limit")); errno = EFTYPE; goto out; } if (i >= ssat->sat_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, ssat->sat_len)); errno = EFTYPE; goto out; } if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) != (ssize_t)ss) { DPRINTF(("Reading short sat sector %d", sid)); goto out; } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } return 0; out: free(ssat->sat_tab); return -1; } int cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn, const cdf_directory_t **root) { size_t i; const cdf_directory_t *d; *root = NULL; for (i = 0; i < dir->dir_len; i++) if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE) break; /* If the it is not there, just fake it; some docs don't have it */ if (i == dir->dir_len) goto out; d = &dir->dir_tab[i]; *root = d; /* If the it is not there, just fake it; some docs don't have it */ if (d->d_stream_first_sector < 0) goto out; return cdf_read_long_sector_chain(info, h, sat, d->d_stream_first_sector, d->d_size, scn); out: scn->sst_tab = NULL; scn->sst_len = 0; scn->sst_dirlen = 0; return 0; } static int cdf_namecmp(const char *d, const uint16_t *s, size_t l) { for (; l--; d++, s++) if (*d != CDF_TOLE2(*s)) return (unsigned char)*d - CDF_TOLE2(*s); return 0; } int cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05SummaryInformation", scn); } int cdf_read_user_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, const char *name, cdf_stream_t *scn) { size_t i; const cdf_directory_t *d; size_t name_len = strlen(name) + 1; for (i = dir->dir_len; i > 0; i--) if (dir->dir_tab[i - 1].d_type == CDF_DIR_TYPE_USER_STREAM && cdf_namecmp(name, dir->dir_tab[i - 1].d_name, name_len) == 0) break; if (i == 0) { DPRINTF(("Cannot find user stream `%s'\n", name)); errno = ESRCH; return -1; } d = &dir->dir_tab[i - 1]; return cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, scn); } int cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { size_t ofs = CDF_GETUINT32(p, (i << 1) + 1); q = (const uint8_t *)(const void *) ((const char *)(const void *)p + ofs - 2 * sizeof(uint32_t)); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); if (nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == 0\n")); goto out; } o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_FLOAT: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); u32 = CDF_TOLE4(u32); memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f)); break; case CDF_DOUBLE: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); u64 = CDF_TOLE8((uint64_t)u64); memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d)); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %" SIZE_T_FORMAT "u, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); if (l & 1) l++; o += l >> 1; if (q + o >= e) goto out; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); return -1; } int cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h, cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count) { size_t maxcount; const cdf_summary_info_header_t *si = CAST(const cdf_summary_info_header_t *, sst->sst_tab); const cdf_section_declaration_t *sd = CAST(const cdf_section_declaration_t *, (const void *) ((const char *)sst->sst_tab + CDF_SECTION_DECLARATION_OFFSET)); if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 || cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1) return -1; ssi->si_byte_order = CDF_TOLE2(si->si_byte_order); ssi->si_os_version = CDF_TOLE2(si->si_os_version); ssi->si_os = CDF_TOLE2(si->si_os); ssi->si_class = si->si_class; cdf_swap_class(&ssi->si_class); ssi->si_count = CDF_TOLE4(si->si_count); *count = 0; maxcount = 0; *info = NULL; if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info, count, &maxcount) == -1) return -1; return 0; } int cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id) { return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-" "%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0], id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0], id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4], id->cl_six[5]); } static const struct { uint32_t v; const char *n; } vn[] = { { CDF_PROPERTY_CODE_PAGE, "Code page" }, { CDF_PROPERTY_TITLE, "Title" }, { CDF_PROPERTY_SUBJECT, "Subject" }, { CDF_PROPERTY_AUTHOR, "Author" }, { CDF_PROPERTY_KEYWORDS, "Keywords" }, { CDF_PROPERTY_COMMENTS, "Comments" }, { CDF_PROPERTY_TEMPLATE, "Template" }, { CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" }, { CDF_PROPERTY_REVISION_NUMBER, "Revision Number" }, { CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" }, { CDF_PROPERTY_LAST_PRINTED, "Last Printed" }, { CDF_PROPERTY_CREATE_TIME, "Create Time/Date" }, { CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" }, { CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" }, { CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" }, { CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" }, { CDF_PROPERTY_THUMBNAIL, "Thumbnail" }, { CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" }, { CDF_PROPERTY_SECURITY, "Security" }, { CDF_PROPERTY_LOCALE_ID, "Locale ID" }, }; int cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p) { size_t i; for (i = 0; i < __arraycount(vn); i++) if (vn[i].v == p) return snprintf(buf, bufsiz, "%s", vn[i].n); return snprintf(buf, bufsiz, "0x%x", p); } int cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts) { int len = 0; int days, hours, mins, secs; ts /= CDF_TIME_PREC; secs = (int)(ts % 60); ts /= 60; mins = (int)(ts % 60); ts /= 60; hours = (int)(ts % 24); ts /= 24; days = (int)ts; if (days) { len += snprintf(buf + len, bufsiz - len, "%dd+", days); if ((size_t)len >= bufsiz) return len; } if (days || hours) { len += snprintf(buf + len, bufsiz - len, "%.2d:", hours); if ((size_t)len >= bufsiz) return len; } len += snprintf(buf + len, bufsiz - len, "%.2d:", mins); if ((size_t)len >= bufsiz) return len; len += snprintf(buf + len, bufsiz - len, "%.2d", secs); return len; } #ifdef CDF_DEBUG void cdf_dump_header(const cdf_header_t *h) { size_t i; #define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b) #define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \ h->h_ ## b, 1 << h->h_ ## b) DUMP("%d", revision); DUMP("%d", version); DUMP("0x%x", byte_order); DUMP2("%d", sec_size_p2); DUMP2("%d", short_sec_size_p2); DUMP("%d", num_sectors_in_sat); DUMP("%d", secid_first_directory); DUMP("%d", min_size_standard_stream); DUMP("%d", secid_first_sector_in_short_sat); DUMP("%d", num_sectors_in_short_sat); DUMP("%d", secid_first_sector_in_master_sat); DUMP("%d", num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] == CDF_SECID_FREE) break; (void)fprintf(stderr, "%35.35s[%.3zu] = %d\n", "master_sat", i, h->h_master_sat[i]); } } void cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size) { size_t i, j, s = size / sizeof(cdf_secid_t); for (i = 0; i < sat->sat_len; i++) { (void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6" SIZE_T_FORMAT "u: ", prefix, i, i * s); for (j = 0; j < s; j++) { (void)fprintf(stderr, "%5d, ", CDF_TOLE4(sat->sat_tab[s * i + j])); if ((j + 1) % 10 == 0) (void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT "u: ", i * s + j + 1); } (void)fprintf(stderr, "\n"); } } void cdf_dump(void *v, size_t len) { size_t i, j; unsigned char *p = v; char abuf[16]; (void)fprintf(stderr, "%.4x: ", 0); for (i = 0, j = 0; i < len; i++, p++) { (void)fprintf(stderr, "%.2x ", *p); abuf[j++] = isprint(*p) ? *p : '.'; if (j == 16) { j = 0; abuf[15] = '\0'; (void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ", abuf, i + 1); } } (void)fprintf(stderr, "\n"); } void cdf_dump_stream(const cdf_header_t *h, const cdf_stream_t *sst) { size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ? CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h); cdf_dump(sst->sst_tab, ss * sst->sst_len); } void cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir) { size_t i, j; cdf_directory_t *d; char name[__arraycount(d->d_name)]; cdf_stream_t scn; struct timespec ts; static const char *types[] = { "empty", "user storage", "user stream", "lockbytes", "property", "root storage" }; for (i = 0; i < dir->dir_len; i++) { char buf[26]; d = &dir->dir_tab[i]; for (j = 0; j < sizeof(name); j++) name[j] = (char)CDF_TOLE2(d->d_name[j]); (void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n", i, name); if (d->d_type < __arraycount(types)) (void)fprintf(stderr, "Type: %s\n", types[d->d_type]); else (void)fprintf(stderr, "Type: %d\n", d->d_type); (void)fprintf(stderr, "Color: %s\n", d->d_color ? "black" : "red"); (void)fprintf(stderr, "Left child: %d\n", d->d_left_child); (void)fprintf(stderr, "Right child: %d\n", d->d_right_child); (void)fprintf(stderr, "Flags: 0x%x\n", d->d_flags); cdf_timestamp_to_timespec(&ts, d->d_created); (void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec, buf)); cdf_timestamp_to_timespec(&ts, d->d_modified); (void)fprintf(stderr, "Modified %s", cdf_ctime(&ts.tv_sec, buf)); (void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector); (void)fprintf(stderr, "Size %d\n", d->d_size); switch (d->d_type) { case CDF_DIR_TYPE_USER_STORAGE: (void)fprintf(stderr, "Storage: %d\n", d->d_storage); break; case CDF_DIR_TYPE_USER_STREAM: if (sst == NULL) break; if (cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, &scn) == -1) { warn("Can't read stream for %s at %d len %d", name, d->d_stream_first_sector, d->d_size); break; } cdf_dump_stream(h, &scn); free(scn.sst_tab); break; default: break; } } } void cdf_dump_property_info(const cdf_property_info_t *info, size_t count) { cdf_timestamp_t tp; struct timespec ts; char buf[64]; size_t i, j; for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); (void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: (void)fprintf(stderr, "signed 16 [%hd]\n", info[i].pi_s16); break; case CDF_SIGNED32: (void)fprintf(stderr, "signed 32 [%d]\n", info[i].pi_s32); break; case CDF_UNSIGNED32: (void)fprintf(stderr, "unsigned 32 [%u]\n", info[i].pi_u32); break; case CDF_FLOAT: (void)fprintf(stderr, "float [%g]\n", info[i].pi_f); break; case CDF_DOUBLE: (void)fprintf(stderr, "double [%g]\n", info[i].pi_d); break; case CDF_LENGTH32_STRING: (void)fprintf(stderr, "string %u [%.*s]\n", info[i].pi_str.s_len, info[i].pi_str.s_len, info[i].pi_str.s_buf); break; case CDF_LENGTH32_WSTRING: (void)fprintf(stderr, "string %u [", info[i].pi_str.s_len); for (j = 0; j < info[i].pi_str.s_len - 1; j++) (void)fputc(info[i].pi_str.s_buf[j << 1], stderr); (void)fprintf(stderr, "]\n"); break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp < 1000000000000000LL) { cdf_print_elapsed_time(buf, sizeof(buf), tp); (void)fprintf(stderr, "timestamp %s\n", buf); } else { char buf[26]; cdf_timestamp_to_timespec(&ts, tp); (void)fprintf(stderr, "timestamp %s", cdf_ctime(&ts.tv_sec, buf)); } break; case CDF_CLIPBOARD: (void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32); break; default: DPRINTF(("Don't know how to deal with %x\n", info[i].pi_type)); break; } } } void cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst) { char buf[128]; cdf_summary_info_header_t ssi; cdf_property_info_t *info; size_t count; (void)&h; if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1) return; (void)fprintf(stderr, "Endian: %x\n", ssi.si_byte_order); (void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff, ssi.si_os_version >> 8); (void)fprintf(stderr, "Os %d\n", ssi.si_os); cdf_print_classid(buf, sizeof(buf), &ssi.si_class); (void)fprintf(stderr, "Class %s\n", buf); (void)fprintf(stderr, "Count %d\n", ssi.si_count); cdf_dump_property_info(info, count); free(info); } #endif #ifdef TEST int main(int argc, char *argv[]) { int i; cdf_header_t h; cdf_sat_t sat, ssat; cdf_stream_t sst, scn; cdf_dir_t dir; cdf_info_t info; if (argc < 2) { (void)fprintf(stderr, "Usage: %s <filename>\n", getprogname()); return -1; } info.i_buf = NULL; info.i_len = 0; for (i = 1; i < argc; i++) { if ((info.i_fd = open(argv[1], O_RDONLY)) == -1) err(1, "Cannot open `%s'", argv[1]); if (cdf_read_header(&info, &h) == -1) err(1, "Cannot read header"); #ifdef CDF_DEBUG cdf_dump_header(&h); #endif if (cdf_read_sat(&info, &h, &sat) == -1) err(1, "Cannot read sat"); #ifdef CDF_DEBUG cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h)); #endif if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1) err(1, "Cannot read ssat"); #ifdef CDF_DEBUG cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h)); #endif if (cdf_read_dir(&info, &h, &sat, &dir) == -1) err(1, "Cannot read dir"); if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst) == -1) err(1, "Cannot read short stream"); #ifdef CDF_DEBUG cdf_dump_stream(&h, &sst); #endif #ifdef CDF_DEBUG cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir); #endif if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir, &scn) == -1) err(1, "Cannot read summary info"); #ifdef CDF_DEBUG cdf_dump_summary_info(&h, &scn); #endif (void)close(info.i_fd); } return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-119/c/good_2040_0
crossvul-cpp_data_bad_4819_0
/* Unix SMB/Netbios implementation. Version 1.9. SMB parameters and setup Copyright (C) Andrew Tridgell 1992-2000 Copyright (C) Luke Kenneth Casson Leighton 1996-2000 Modified by Jeremy Allison 1995. Copyright (C) Andrew Bartlett <abartlet@samba.org> 2002-2003 Modified by Steve French (sfrench@us.ibm.com) 2002-2003 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <crypto/skcipher.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/string.h> #include <linux/kernel.h> #include <linux/random.h> #include "cifs_fs_sb.h" #include "cifs_unicode.h" #include "cifspdu.h" #include "cifsglob.h" #include "cifs_debug.h" #include "cifsproto.h" #ifndef false #define false 0 #endif #ifndef true #define true 1 #endif /* following came from the other byteorder.h to avoid include conflicts */ #define CVAL(buf,pos) (((unsigned char *)(buf))[pos]) #define SSVALX(buf,pos,val) (CVAL(buf,pos)=(val)&0xFF,CVAL(buf,pos+1)=(val)>>8) #define SSVAL(buf,pos,val) SSVALX((buf),(pos),((__u16)(val))) static void str_to_key(unsigned char *str, unsigned char *key) { int i; key[0] = str[0] >> 1; key[1] = ((str[0] & 0x01) << 6) | (str[1] >> 2); key[2] = ((str[1] & 0x03) << 5) | (str[2] >> 3); key[3] = ((str[2] & 0x07) << 4) | (str[3] >> 4); key[4] = ((str[3] & 0x0F) << 3) | (str[4] >> 5); key[5] = ((str[4] & 0x1F) << 2) | (str[5] >> 6); key[6] = ((str[5] & 0x3F) << 1) | (str[6] >> 7); key[7] = str[6] & 0x7F; for (i = 0; i < 8; i++) key[i] = (key[i] << 1); } static int smbhash(unsigned char *out, const unsigned char *in, unsigned char *key) { int rc; unsigned char key2[8]; struct crypto_skcipher *tfm_des; struct scatterlist sgin, sgout; struct skcipher_request *req; str_to_key(key, key2); tfm_des = crypto_alloc_skcipher("ecb(des)", 0, CRYPTO_ALG_ASYNC); if (IS_ERR(tfm_des)) { rc = PTR_ERR(tfm_des); cifs_dbg(VFS, "could not allocate des crypto API\n"); goto smbhash_err; } req = skcipher_request_alloc(tfm_des, GFP_KERNEL); if (!req) { rc = -ENOMEM; cifs_dbg(VFS, "could not allocate des crypto API\n"); goto smbhash_free_skcipher; } crypto_skcipher_setkey(tfm_des, key2, 8); sg_init_one(&sgin, in, 8); sg_init_one(&sgout, out, 8); skcipher_request_set_callback(req, 0, NULL, NULL); skcipher_request_set_crypt(req, &sgin, &sgout, 8, NULL); rc = crypto_skcipher_encrypt(req); if (rc) cifs_dbg(VFS, "could not encrypt crypt key rc: %d\n", rc); skcipher_request_free(req); smbhash_free_skcipher: crypto_free_skcipher(tfm_des); smbhash_err: return rc; } static int E_P16(unsigned char *p14, unsigned char *p16) { int rc; unsigned char sp8[8] = { 0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25 }; rc = smbhash(p16, sp8, p14); if (rc) return rc; rc = smbhash(p16 + 8, sp8, p14 + 7); return rc; } static int E_P24(unsigned char *p21, const unsigned char *c8, unsigned char *p24) { int rc; rc = smbhash(p24, c8, p21); if (rc) return rc; rc = smbhash(p24 + 8, c8, p21 + 7); if (rc) return rc; rc = smbhash(p24 + 16, c8, p21 + 14); return rc; } /* produce a md4 message digest from data of length n bytes */ int mdfour(unsigned char *md4_hash, unsigned char *link_str, int link_len) { int rc; unsigned int size; struct crypto_shash *md4; struct sdesc *sdescmd4; md4 = crypto_alloc_shash("md4", 0, 0); if (IS_ERR(md4)) { rc = PTR_ERR(md4); cifs_dbg(VFS, "%s: Crypto md4 allocation error %d\n", __func__, rc); return rc; } size = sizeof(struct shash_desc) + crypto_shash_descsize(md4); sdescmd4 = kmalloc(size, GFP_KERNEL); if (!sdescmd4) { rc = -ENOMEM; goto mdfour_err; } sdescmd4->shash.tfm = md4; sdescmd4->shash.flags = 0x0; rc = crypto_shash_init(&sdescmd4->shash); if (rc) { cifs_dbg(VFS, "%s: Could not init md4 shash\n", __func__); goto mdfour_err; } rc = crypto_shash_update(&sdescmd4->shash, link_str, link_len); if (rc) { cifs_dbg(VFS, "%s: Could not update with link_str\n", __func__); goto mdfour_err; } rc = crypto_shash_final(&sdescmd4->shash, md4_hash); if (rc) cifs_dbg(VFS, "%s: Could not generate md4 hash\n", __func__); mdfour_err: crypto_free_shash(md4); kfree(sdescmd4); return rc; } /* This implements the X/Open SMB password encryption It takes a password, a 8 byte "crypt key" and puts 24 bytes of encrypted password into p24 */ /* Note that password must be uppercased and null terminated */ int SMBencrypt(unsigned char *passwd, const unsigned char *c8, unsigned char *p24) { int rc; unsigned char p14[14], p16[16], p21[21]; memset(p14, '\0', 14); memset(p16, '\0', 16); memset(p21, '\0', 21); memcpy(p14, passwd, 14); rc = E_P16(p14, p16); if (rc) return rc; memcpy(p21, p16, 16); rc = E_P24(p21, c8, p24); return rc; } /* * Creates the MD4 Hash of the users password in NT UNICODE. */ int E_md4hash(const unsigned char *passwd, unsigned char *p16, const struct nls_table *codepage) { int rc; int len; __le16 wpwd[129]; /* Password cannot be longer than 128 characters */ if (passwd) /* Password must be converted to NT unicode */ len = cifs_strtoUTF16(wpwd, passwd, 128, codepage); else { len = 0; *wpwd = 0; /* Ensure string is null terminated */ } rc = mdfour(p16, (unsigned char *) wpwd, len * sizeof(__le16)); memzero_explicit(wpwd, sizeof(wpwd)); return rc; } /* Does the NT MD4 hash then des encryption. */ int SMBNTencrypt(unsigned char *passwd, unsigned char *c8, unsigned char *p24, const struct nls_table *codepage) { int rc; unsigned char p16[16], p21[21]; memset(p16, '\0', 16); memset(p21, '\0', 21); rc = E_md4hash(passwd, p16, codepage); if (rc) { cifs_dbg(FYI, "%s Can't generate NT hash, error: %d\n", __func__, rc); return rc; } memcpy(p21, p16, 16); rc = E_P24(p21, c8, p24); return rc; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4819_0
crossvul-cpp_data_bad_4946_5
#include "cache.h" #include "commit.h" #include "tag.h" #include "diff.h" #include "revision.h" #include "progress.h" #include "list-objects.h" #include "pack.h" #include "pack-bitmap.h" #include "pack-revindex.h" #include "pack-objects.h" /* * An entry on the bitmap index, representing the bitmap for a given * commit. */ struct stored_bitmap { unsigned char sha1[20]; struct ewah_bitmap *root; struct stored_bitmap *xor; int flags; }; /* * The currently active bitmap index. By design, repositories only have * a single bitmap index available (the index for the biggest packfile in * the repository), since bitmap indexes need full closure. * * If there is more than one bitmap index available (e.g. because of alternates), * the active bitmap index is the largest one. */ static struct bitmap_index { /* Packfile to which this bitmap index belongs to */ struct packed_git *pack; /* * Mark the first `reuse_objects` in the packfile as reused: * they will be sent as-is without using them for repacking * calculations */ uint32_t reuse_objects; /* mmapped buffer of the whole bitmap index */ unsigned char *map; size_t map_size; /* size of the mmaped buffer */ size_t map_pos; /* current position when loading the index */ /* * Type indexes. * * Each bitmap marks which objects in the packfile are of the given * type. This provides type information when yielding the objects from * the packfile during a walk, which allows for better delta bases. */ struct ewah_bitmap *commits; struct ewah_bitmap *trees; struct ewah_bitmap *blobs; struct ewah_bitmap *tags; /* Map from SHA1 -> `stored_bitmap` for all the bitmapped commits */ khash_sha1 *bitmaps; /* Number of bitmapped commits */ uint32_t entry_count; /* Name-hash cache (or NULL if not present). */ uint32_t *hashes; /* * Extended index. * * When trying to perform bitmap operations with objects that are not * packed in `pack`, these objects are added to this "fake index" and * are assumed to appear at the end of the packfile for all operations */ struct eindex { struct object **objects; uint32_t *hashes; uint32_t count, alloc; khash_sha1_pos *positions; } ext_index; /* Bitmap result of the last performed walk */ struct bitmap *result; /* Version of the bitmap index */ unsigned int version; unsigned loaded : 1; } bitmap_git; static struct ewah_bitmap *lookup_stored_bitmap(struct stored_bitmap *st) { struct ewah_bitmap *parent; struct ewah_bitmap *composed; if (st->xor == NULL) return st->root; composed = ewah_pool_new(); parent = lookup_stored_bitmap(st->xor); ewah_xor(st->root, parent, composed); ewah_pool_free(st->root); st->root = composed; st->xor = NULL; return composed; } /* * Read a bitmap from the current read position on the mmaped * index, and increase the read position accordingly */ static struct ewah_bitmap *read_bitmap_1(struct bitmap_index *index) { struct ewah_bitmap *b = ewah_pool_new(); int bitmap_size = ewah_read_mmap(b, index->map + index->map_pos, index->map_size - index->map_pos); if (bitmap_size < 0) { error("Failed to load bitmap index (corrupted?)"); ewah_pool_free(b); return NULL; } index->map_pos += bitmap_size; return b; } static int load_bitmap_header(struct bitmap_index *index) { struct bitmap_disk_header *header = (void *)index->map; if (index->map_size < sizeof(*header) + 20) return error("Corrupted bitmap index (missing header data)"); if (memcmp(header->magic, BITMAP_IDX_SIGNATURE, sizeof(BITMAP_IDX_SIGNATURE)) != 0) return error("Corrupted bitmap index file (wrong header)"); index->version = ntohs(header->version); if (index->version != 1) return error("Unsupported version for bitmap index file (%d)", index->version); /* Parse known bitmap format options */ { uint32_t flags = ntohs(header->options); if ((flags & BITMAP_OPT_FULL_DAG) == 0) return error("Unsupported options for bitmap index file " "(Git requires BITMAP_OPT_FULL_DAG)"); if (flags & BITMAP_OPT_HASH_CACHE) { unsigned char *end = index->map + index->map_size - 20; index->hashes = ((uint32_t *)end) - index->pack->num_objects; } } index->entry_count = ntohl(header->entry_count); index->map_pos += sizeof(*header); return 0; } static struct stored_bitmap *store_bitmap(struct bitmap_index *index, struct ewah_bitmap *root, const unsigned char *sha1, struct stored_bitmap *xor_with, int flags) { struct stored_bitmap *stored; khiter_t hash_pos; int ret; stored = xmalloc(sizeof(struct stored_bitmap)); stored->root = root; stored->xor = xor_with; stored->flags = flags; hashcpy(stored->sha1, sha1); hash_pos = kh_put_sha1(index->bitmaps, stored->sha1, &ret); /* a 0 return code means the insertion succeeded with no changes, * because the SHA1 already existed on the map. this is bad, there * shouldn't be duplicated commits in the index */ if (ret == 0) { error("Duplicate entry in bitmap index: %s", sha1_to_hex(sha1)); return NULL; } kh_value(index->bitmaps, hash_pos) = stored; return stored; } static inline uint32_t read_be32(const unsigned char *buffer, size_t *pos) { uint32_t result = get_be32(buffer + *pos); (*pos) += sizeof(result); return result; } static inline uint8_t read_u8(const unsigned char *buffer, size_t *pos) { return buffer[(*pos)++]; } #define MAX_XOR_OFFSET 160 static int load_bitmap_entries_v1(struct bitmap_index *index) { uint32_t i; struct stored_bitmap *recent_bitmaps[MAX_XOR_OFFSET] = { NULL }; for (i = 0; i < index->entry_count; ++i) { int xor_offset, flags; struct ewah_bitmap *bitmap = NULL; struct stored_bitmap *xor_bitmap = NULL; uint32_t commit_idx_pos; const unsigned char *sha1; commit_idx_pos = read_be32(index->map, &index->map_pos); xor_offset = read_u8(index->map, &index->map_pos); flags = read_u8(index->map, &index->map_pos); sha1 = nth_packed_object_sha1(index->pack, commit_idx_pos); bitmap = read_bitmap_1(index); if (!bitmap) return -1; if (xor_offset > MAX_XOR_OFFSET || xor_offset > i) return error("Corrupted bitmap pack index"); if (xor_offset > 0) { xor_bitmap = recent_bitmaps[(i - xor_offset) % MAX_XOR_OFFSET]; if (xor_bitmap == NULL) return error("Invalid XOR offset in bitmap pack index"); } recent_bitmaps[i % MAX_XOR_OFFSET] = store_bitmap( index, bitmap, sha1, xor_bitmap, flags); } return 0; } static char *pack_bitmap_filename(struct packed_git *p) { size_t len; if (!strip_suffix(p->pack_name, ".pack", &len)) die("BUG: pack_name does not end in .pack"); return xstrfmt("%.*s.bitmap", (int)len, p->pack_name); } static int open_pack_bitmap_1(struct packed_git *packfile) { int fd; struct stat st; char *idx_name; if (open_pack_index(packfile)) return -1; idx_name = pack_bitmap_filename(packfile); fd = git_open_noatime(idx_name); free(idx_name); if (fd < 0) return -1; if (fstat(fd, &st)) { close(fd); return -1; } if (bitmap_git.pack) { warning("ignoring extra bitmap file: %s", packfile->pack_name); close(fd); return -1; } bitmap_git.pack = packfile; bitmap_git.map_size = xsize_t(st.st_size); bitmap_git.map = xmmap(NULL, bitmap_git.map_size, PROT_READ, MAP_PRIVATE, fd, 0); bitmap_git.map_pos = 0; close(fd); if (load_bitmap_header(&bitmap_git) < 0) { munmap(bitmap_git.map, bitmap_git.map_size); bitmap_git.map = NULL; bitmap_git.map_size = 0; return -1; } return 0; } static int load_pack_bitmap(void) { assert(bitmap_git.map && !bitmap_git.loaded); bitmap_git.bitmaps = kh_init_sha1(); bitmap_git.ext_index.positions = kh_init_sha1_pos(); load_pack_revindex(bitmap_git.pack); if (!(bitmap_git.commits = read_bitmap_1(&bitmap_git)) || !(bitmap_git.trees = read_bitmap_1(&bitmap_git)) || !(bitmap_git.blobs = read_bitmap_1(&bitmap_git)) || !(bitmap_git.tags = read_bitmap_1(&bitmap_git))) goto failed; if (load_bitmap_entries_v1(&bitmap_git) < 0) goto failed; bitmap_git.loaded = 1; return 0; failed: munmap(bitmap_git.map, bitmap_git.map_size); bitmap_git.map = NULL; bitmap_git.map_size = 0; return -1; } static int open_pack_bitmap(void) { struct packed_git *p; int ret = -1; assert(!bitmap_git.map && !bitmap_git.loaded); prepare_packed_git(); for (p = packed_git; p; p = p->next) { if (open_pack_bitmap_1(p) == 0) ret = 0; } return ret; } int prepare_bitmap_git(void) { if (bitmap_git.loaded) return 0; if (!open_pack_bitmap()) return load_pack_bitmap(); return -1; } struct include_data { struct bitmap *base; struct bitmap *seen; }; static inline int bitmap_position_extended(const unsigned char *sha1) { khash_sha1_pos *positions = bitmap_git.ext_index.positions; khiter_t pos = kh_get_sha1_pos(positions, sha1); if (pos < kh_end(positions)) { int bitmap_pos = kh_value(positions, pos); return bitmap_pos + bitmap_git.pack->num_objects; } return -1; } static inline int bitmap_position_packfile(const unsigned char *sha1) { off_t offset = find_pack_entry_one(sha1, bitmap_git.pack); if (!offset) return -1; return find_revindex_position(bitmap_git.pack, offset); } static int bitmap_position(const unsigned char *sha1) { int pos = bitmap_position_packfile(sha1); return (pos >= 0) ? pos : bitmap_position_extended(sha1); } static int ext_index_add_object(struct object *object, const char *name) { struct eindex *eindex = &bitmap_git.ext_index; khiter_t hash_pos; int hash_ret; int bitmap_pos; hash_pos = kh_put_sha1_pos(eindex->positions, object->oid.hash, &hash_ret); if (hash_ret > 0) { if (eindex->count >= eindex->alloc) { eindex->alloc = (eindex->alloc + 16) * 3 / 2; REALLOC_ARRAY(eindex->objects, eindex->alloc); REALLOC_ARRAY(eindex->hashes, eindex->alloc); } bitmap_pos = eindex->count; eindex->objects[eindex->count] = object; eindex->hashes[eindex->count] = pack_name_hash(name); kh_value(eindex->positions, hash_pos) = bitmap_pos; eindex->count++; } else { bitmap_pos = kh_value(eindex->positions, hash_pos); } return bitmap_pos + bitmap_git.pack->num_objects; } static void show_object(struct object *object, struct strbuf *path, const char *last, void *data) { struct bitmap *base = data; int bitmap_pos; bitmap_pos = bitmap_position(object->oid.hash); if (bitmap_pos < 0) { char *name = path_name(path, last); bitmap_pos = ext_index_add_object(object, name); free(name); } bitmap_set(base, bitmap_pos); } static void show_commit(struct commit *commit, void *data) { } static int add_to_include_set(struct include_data *data, const unsigned char *sha1, int bitmap_pos) { khiter_t hash_pos; if (data->seen && bitmap_get(data->seen, bitmap_pos)) return 0; if (bitmap_get(data->base, bitmap_pos)) return 0; hash_pos = kh_get_sha1(bitmap_git.bitmaps, sha1); if (hash_pos < kh_end(bitmap_git.bitmaps)) { struct stored_bitmap *st = kh_value(bitmap_git.bitmaps, hash_pos); bitmap_or_ewah(data->base, lookup_stored_bitmap(st)); return 0; } bitmap_set(data->base, bitmap_pos); return 1; } static int should_include(struct commit *commit, void *_data) { struct include_data *data = _data; int bitmap_pos; bitmap_pos = bitmap_position(commit->object.oid.hash); if (bitmap_pos < 0) bitmap_pos = ext_index_add_object((struct object *)commit, NULL); if (!add_to_include_set(data, commit->object.oid.hash, bitmap_pos)) { struct commit_list *parent = commit->parents; while (parent) { parent->item->object.flags |= SEEN; parent = parent->next; } return 0; } return 1; } static struct bitmap *find_objects(struct rev_info *revs, struct object_list *roots, struct bitmap *seen) { struct bitmap *base = NULL; int needs_walk = 0; struct object_list *not_mapped = NULL; /* * Go through all the roots for the walk. The ones that have bitmaps * on the bitmap index will be `or`ed together to form an initial * global reachability analysis. * * The ones without bitmaps in the index will be stored in the * `not_mapped_list` for further processing. */ while (roots) { struct object *object = roots->item; roots = roots->next; if (object->type == OBJ_COMMIT) { khiter_t pos = kh_get_sha1(bitmap_git.bitmaps, object->oid.hash); if (pos < kh_end(bitmap_git.bitmaps)) { struct stored_bitmap *st = kh_value(bitmap_git.bitmaps, pos); struct ewah_bitmap *or_with = lookup_stored_bitmap(st); if (base == NULL) base = ewah_to_bitmap(or_with); else bitmap_or_ewah(base, or_with); object->flags |= SEEN; continue; } } object_list_insert(object, &not_mapped); } /* * Best case scenario: We found bitmaps for all the roots, * so the resulting `or` bitmap has the full reachability analysis */ if (not_mapped == NULL) return base; roots = not_mapped; /* * Let's iterate through all the roots that don't have bitmaps to * check if we can determine them to be reachable from the existing * global bitmap. * * If we cannot find them in the existing global bitmap, we'll need * to push them to an actual walk and run it until we can confirm * they are reachable */ while (roots) { struct object *object = roots->item; int pos; roots = roots->next; pos = bitmap_position(object->oid.hash); if (pos < 0 || base == NULL || !bitmap_get(base, pos)) { object->flags &= ~UNINTERESTING; add_pending_object(revs, object, ""); needs_walk = 1; } else { object->flags |= SEEN; } } if (needs_walk) { struct include_data incdata; if (base == NULL) base = bitmap_new(); incdata.base = base; incdata.seen = seen; revs->include_check = should_include; revs->include_check_data = &incdata; if (prepare_revision_walk(revs)) die("revision walk setup failed"); traverse_commit_list(revs, show_commit, show_object, base); } return base; } static void show_extended_objects(struct bitmap *objects, show_reachable_fn show_reach) { struct eindex *eindex = &bitmap_git.ext_index; uint32_t i; for (i = 0; i < eindex->count; ++i) { struct object *obj; if (!bitmap_get(objects, bitmap_git.pack->num_objects + i)) continue; obj = eindex->objects[i]; show_reach(obj->oid.hash, obj->type, 0, eindex->hashes[i], NULL, 0); } } static void show_objects_for_type( struct bitmap *objects, struct ewah_bitmap *type_filter, enum object_type object_type, show_reachable_fn show_reach) { size_t pos = 0, i = 0; uint32_t offset; struct ewah_iterator it; eword_t filter; if (bitmap_git.reuse_objects == bitmap_git.pack->num_objects) return; ewah_iterator_init(&it, type_filter); while (i < objects->word_alloc && ewah_iterator_next(&filter, &it)) { eword_t word = objects->words[i] & filter; for (offset = 0; offset < BITS_IN_EWORD; ++offset) { const unsigned char *sha1; struct revindex_entry *entry; uint32_t hash = 0; if ((word >> offset) == 0) break; offset += ewah_bit_ctz64(word >> offset); if (pos + offset < bitmap_git.reuse_objects) continue; entry = &bitmap_git.pack->revindex[pos + offset]; sha1 = nth_packed_object_sha1(bitmap_git.pack, entry->nr); if (bitmap_git.hashes) hash = ntohl(bitmap_git.hashes[entry->nr]); show_reach(sha1, object_type, 0, hash, bitmap_git.pack, entry->offset); } pos += BITS_IN_EWORD; i++; } } static int in_bitmapped_pack(struct object_list *roots) { while (roots) { struct object *object = roots->item; roots = roots->next; if (find_pack_entry_one(object->oid.hash, bitmap_git.pack) > 0) return 1; } return 0; } int prepare_bitmap_walk(struct rev_info *revs) { unsigned int i; unsigned int pending_nr = revs->pending.nr; struct object_array_entry *pending_e = revs->pending.objects; struct object_list *wants = NULL; struct object_list *haves = NULL; struct bitmap *wants_bitmap = NULL; struct bitmap *haves_bitmap = NULL; if (!bitmap_git.loaded) { /* try to open a bitmapped pack, but don't parse it yet * because we may not need to use it */ if (open_pack_bitmap() < 0) return -1; } for (i = 0; i < pending_nr; ++i) { struct object *object = pending_e[i].item; if (object->type == OBJ_NONE) parse_object_or_die(object->oid.hash, NULL); while (object->type == OBJ_TAG) { struct tag *tag = (struct tag *) object; if (object->flags & UNINTERESTING) object_list_insert(object, &haves); else object_list_insert(object, &wants); if (!tag->tagged) die("bad tag"); object = parse_object_or_die(tag->tagged->oid.hash, NULL); } if (object->flags & UNINTERESTING) object_list_insert(object, &haves); else object_list_insert(object, &wants); } /* * if we have a HAVES list, but none of those haves is contained * in the packfile that has a bitmap, we don't have anything to * optimize here */ if (haves && !in_bitmapped_pack(haves)) return -1; /* if we don't want anything, we're done here */ if (!wants) return -1; /* * now we're going to use bitmaps, so load the actual bitmap entries * from disk. this is the point of no return; after this the rev_list * becomes invalidated and we must perform the revwalk through bitmaps */ if (!bitmap_git.loaded && load_pack_bitmap() < 0) return -1; revs->pending.nr = 0; revs->pending.alloc = 0; revs->pending.objects = NULL; if (haves) { revs->ignore_missing_links = 1; haves_bitmap = find_objects(revs, haves, NULL); reset_revision_walk(); revs->ignore_missing_links = 0; if (haves_bitmap == NULL) die("BUG: failed to perform bitmap walk"); } wants_bitmap = find_objects(revs, wants, haves_bitmap); if (!wants_bitmap) die("BUG: failed to perform bitmap walk"); if (haves_bitmap) bitmap_and_not(wants_bitmap, haves_bitmap); bitmap_git.result = wants_bitmap; bitmap_free(haves_bitmap); return 0; } int reuse_partial_packfile_from_bitmap(struct packed_git **packfile, uint32_t *entries, off_t *up_to) { /* * Reuse the packfile content if we need more than * 90% of its objects */ static const double REUSE_PERCENT = 0.9; struct bitmap *result = bitmap_git.result; uint32_t reuse_threshold; uint32_t i, reuse_objects = 0; assert(result); for (i = 0; i < result->word_alloc; ++i) { if (result->words[i] != (eword_t)~0) { reuse_objects += ewah_bit_ctz64(~result->words[i]); break; } reuse_objects += BITS_IN_EWORD; } #ifdef GIT_BITMAP_DEBUG { const unsigned char *sha1; struct revindex_entry *entry; entry = &bitmap_git.reverse_index->revindex[reuse_objects]; sha1 = nth_packed_object_sha1(bitmap_git.pack, entry->nr); fprintf(stderr, "Failed to reuse at %d (%016llx)\n", reuse_objects, result->words[i]); fprintf(stderr, " %s\n", sha1_to_hex(sha1)); } #endif if (!reuse_objects) return -1; if (reuse_objects >= bitmap_git.pack->num_objects) { bitmap_git.reuse_objects = *entries = bitmap_git.pack->num_objects; *up_to = -1; /* reuse the full pack */ *packfile = bitmap_git.pack; return 0; } reuse_threshold = bitmap_popcount(bitmap_git.result) * REUSE_PERCENT; if (reuse_objects < reuse_threshold) return -1; bitmap_git.reuse_objects = *entries = reuse_objects; *up_to = bitmap_git.pack->revindex[reuse_objects].offset; *packfile = bitmap_git.pack; return 0; } void traverse_bitmap_commit_list(show_reachable_fn show_reachable) { assert(bitmap_git.result); show_objects_for_type(bitmap_git.result, bitmap_git.commits, OBJ_COMMIT, show_reachable); show_objects_for_type(bitmap_git.result, bitmap_git.trees, OBJ_TREE, show_reachable); show_objects_for_type(bitmap_git.result, bitmap_git.blobs, OBJ_BLOB, show_reachable); show_objects_for_type(bitmap_git.result, bitmap_git.tags, OBJ_TAG, show_reachable); show_extended_objects(bitmap_git.result, show_reachable); bitmap_free(bitmap_git.result); bitmap_git.result = NULL; } static uint32_t count_object_type(struct bitmap *objects, enum object_type type) { struct eindex *eindex = &bitmap_git.ext_index; uint32_t i = 0, count = 0; struct ewah_iterator it; eword_t filter; switch (type) { case OBJ_COMMIT: ewah_iterator_init(&it, bitmap_git.commits); break; case OBJ_TREE: ewah_iterator_init(&it, bitmap_git.trees); break; case OBJ_BLOB: ewah_iterator_init(&it, bitmap_git.blobs); break; case OBJ_TAG: ewah_iterator_init(&it, bitmap_git.tags); break; default: return 0; } while (i < objects->word_alloc && ewah_iterator_next(&filter, &it)) { eword_t word = objects->words[i++] & filter; count += ewah_bit_popcount64(word); } for (i = 0; i < eindex->count; ++i) { if (eindex->objects[i]->type == type && bitmap_get(objects, bitmap_git.pack->num_objects + i)) count++; } return count; } void count_bitmap_commit_list(uint32_t *commits, uint32_t *trees, uint32_t *blobs, uint32_t *tags) { assert(bitmap_git.result); if (commits) *commits = count_object_type(bitmap_git.result, OBJ_COMMIT); if (trees) *trees = count_object_type(bitmap_git.result, OBJ_TREE); if (blobs) *blobs = count_object_type(bitmap_git.result, OBJ_BLOB); if (tags) *tags = count_object_type(bitmap_git.result, OBJ_TAG); } struct bitmap_test_data { struct bitmap *base; struct progress *prg; size_t seen; }; static void test_show_object(struct object *object, struct strbuf *path, const char *last, void *data) { struct bitmap_test_data *tdata = data; int bitmap_pos; bitmap_pos = bitmap_position(object->oid.hash); if (bitmap_pos < 0) die("Object not in bitmap: %s\n", oid_to_hex(&object->oid)); bitmap_set(tdata->base, bitmap_pos); display_progress(tdata->prg, ++tdata->seen); } static void test_show_commit(struct commit *commit, void *data) { struct bitmap_test_data *tdata = data; int bitmap_pos; bitmap_pos = bitmap_position(commit->object.oid.hash); if (bitmap_pos < 0) die("Object not in bitmap: %s\n", oid_to_hex(&commit->object.oid)); bitmap_set(tdata->base, bitmap_pos); display_progress(tdata->prg, ++tdata->seen); } void test_bitmap_walk(struct rev_info *revs) { struct object *root; struct bitmap *result = NULL; khiter_t pos; size_t result_popcnt; struct bitmap_test_data tdata; if (prepare_bitmap_git()) die("failed to load bitmap indexes"); if (revs->pending.nr != 1) die("you must specify exactly one commit to test"); fprintf(stderr, "Bitmap v%d test (%d entries loaded)\n", bitmap_git.version, bitmap_git.entry_count); root = revs->pending.objects[0].item; pos = kh_get_sha1(bitmap_git.bitmaps, root->oid.hash); if (pos < kh_end(bitmap_git.bitmaps)) { struct stored_bitmap *st = kh_value(bitmap_git.bitmaps, pos); struct ewah_bitmap *bm = lookup_stored_bitmap(st); fprintf(stderr, "Found bitmap for %s. %d bits / %08x checksum\n", oid_to_hex(&root->oid), (int)bm->bit_size, ewah_checksum(bm)); result = ewah_to_bitmap(bm); } if (result == NULL) die("Commit %s doesn't have an indexed bitmap", oid_to_hex(&root->oid)); revs->tag_objects = 1; revs->tree_objects = 1; revs->blob_objects = 1; result_popcnt = bitmap_popcount(result); if (prepare_revision_walk(revs)) die("revision walk setup failed"); tdata.base = bitmap_new(); tdata.prg = start_progress("Verifying bitmap entries", result_popcnt); tdata.seen = 0; traverse_commit_list(revs, &test_show_commit, &test_show_object, &tdata); stop_progress(&tdata.prg); if (bitmap_equals(result, tdata.base)) fprintf(stderr, "OK!\n"); else fprintf(stderr, "Mismatch!\n"); bitmap_free(result); } static int rebuild_bitmap(uint32_t *reposition, struct ewah_bitmap *source, struct bitmap *dest) { uint32_t pos = 0; struct ewah_iterator it; eword_t word; ewah_iterator_init(&it, source); while (ewah_iterator_next(&word, &it)) { uint32_t offset, bit_pos; for (offset = 0; offset < BITS_IN_EWORD; ++offset) { if ((word >> offset) == 0) break; offset += ewah_bit_ctz64(word >> offset); bit_pos = reposition[pos + offset]; if (bit_pos > 0) bitmap_set(dest, bit_pos - 1); else /* can't reuse, we don't have the object */ return -1; } pos += BITS_IN_EWORD; } return 0; } int rebuild_existing_bitmaps(struct packing_data *mapping, khash_sha1 *reused_bitmaps, int show_progress) { uint32_t i, num_objects; uint32_t *reposition; struct bitmap *rebuild; struct stored_bitmap *stored; struct progress *progress = NULL; khiter_t hash_pos; int hash_ret; if (prepare_bitmap_git() < 0) return -1; num_objects = bitmap_git.pack->num_objects; reposition = xcalloc(num_objects, sizeof(uint32_t)); for (i = 0; i < num_objects; ++i) { const unsigned char *sha1; struct revindex_entry *entry; struct object_entry *oe; entry = &bitmap_git.pack->revindex[i]; sha1 = nth_packed_object_sha1(bitmap_git.pack, entry->nr); oe = packlist_find(mapping, sha1, NULL); if (oe) reposition[i] = oe->in_pack_pos + 1; } rebuild = bitmap_new(); i = 0; if (show_progress) progress = start_progress("Reusing bitmaps", 0); kh_foreach_value(bitmap_git.bitmaps, stored, { if (stored->flags & BITMAP_FLAG_REUSE) { if (!rebuild_bitmap(reposition, lookup_stored_bitmap(stored), rebuild)) { hash_pos = kh_put_sha1(reused_bitmaps, stored->sha1, &hash_ret); kh_value(reused_bitmaps, hash_pos) = bitmap_to_ewah(rebuild); } bitmap_reset(rebuild); display_progress(progress, ++i); } }); stop_progress(&progress); free(reposition); bitmap_free(rebuild); return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4946_5
crossvul-cpp_data_bad_5590_1
/* * linux/fs/vfat/namei.c * * Written 1992,1993 by Werner Almesberger * * Windows95/Windows NT compatible extended MSDOS filesystem * by Gordon Chaffee Copyright (C) 1995. Send bug reports for the * VFAT filesystem to <chaffee@cs.berkeley.edu>. Specify * what file operation caused you trouble and if you can duplicate * the problem, send a script that demonstrates it. * * Short name translation 1999, 2001 by Wolfram Pienkoss <wp@bszh.de> * * Support Multibyte characters and cleanup by * OGAWA Hirofumi <hirofumi@mail.parknet.co.jp> */ #include <linux/module.h> #include <linux/jiffies.h> #include <linux/ctype.h> #include <linux/slab.h> #include <linux/buffer_head.h> #include <linux/namei.h> #include "fat.h" /* * If new entry was created in the parent, it could create the 8.3 * alias (the shortname of logname). So, the parent may have the * negative-dentry which matches the created 8.3 alias. * * If it happened, the negative dentry isn't actually negative * anymore. So, drop it. */ static int vfat_revalidate_shortname(struct dentry *dentry) { int ret = 1; spin_lock(&dentry->d_lock); if (dentry->d_time != dentry->d_parent->d_inode->i_version) ret = 0; spin_unlock(&dentry->d_lock); return ret; } static int vfat_revalidate(struct dentry *dentry, struct nameidata *nd) { if (nd && nd->flags & LOOKUP_RCU) return -ECHILD; /* This is not negative dentry. Always valid. */ if (dentry->d_inode) return 1; return vfat_revalidate_shortname(dentry); } static int vfat_revalidate_ci(struct dentry *dentry, struct nameidata *nd) { if (nd && nd->flags & LOOKUP_RCU) return -ECHILD; /* * This is not negative dentry. Always valid. * * Note, rename() to existing directory entry will have ->d_inode, * and will use existing name which isn't specified name by user. * * We may be able to drop this positive dentry here. But dropping * positive dentry isn't good idea. So it's unsupported like * rename("filename", "FILENAME") for now. */ if (dentry->d_inode) return 1; /* * This may be nfsd (or something), anyway, we can't see the * intent of this. So, since this can be for creation, drop it. */ if (!nd) return 0; /* * Drop the negative dentry, in order to make sure to use the * case sensitive name which is specified by user if this is * for creation. */ if (nd->flags & (LOOKUP_CREATE | LOOKUP_RENAME_TARGET)) return 0; return vfat_revalidate_shortname(dentry); } /* returns the length of a struct qstr, ignoring trailing dots */ static unsigned int __vfat_striptail_len(unsigned int len, const char *name) { while (len && name[len - 1] == '.') len--; return len; } static unsigned int vfat_striptail_len(const struct qstr *qstr) { return __vfat_striptail_len(qstr->len, qstr->name); } /* * Compute the hash for the vfat name corresponding to the dentry. * Note: if the name is invalid, we leave the hash code unchanged so * that the existing dentry can be used. The vfat fs routines will * return ENOENT or EINVAL as appropriate. */ static int vfat_hash(const struct dentry *dentry, const struct inode *inode, struct qstr *qstr) { qstr->hash = full_name_hash(qstr->name, vfat_striptail_len(qstr)); return 0; } /* * Compute the hash for the vfat name corresponding to the dentry. * Note: if the name is invalid, we leave the hash code unchanged so * that the existing dentry can be used. The vfat fs routines will * return ENOENT or EINVAL as appropriate. */ static int vfat_hashi(const struct dentry *dentry, const struct inode *inode, struct qstr *qstr) { struct nls_table *t = MSDOS_SB(dentry->d_sb)->nls_io; const unsigned char *name; unsigned int len; unsigned long hash; name = qstr->name; len = vfat_striptail_len(qstr); hash = init_name_hash(); while (len--) hash = partial_name_hash(nls_tolower(t, *name++), hash); qstr->hash = end_name_hash(hash); return 0; } /* * Case insensitive compare of two vfat names. */ static int vfat_cmpi(const struct dentry *parent, const struct inode *pinode, const struct dentry *dentry, const struct inode *inode, unsigned int len, const char *str, const struct qstr *name) { struct nls_table *t = MSDOS_SB(parent->d_sb)->nls_io; unsigned int alen, blen; /* A filename cannot end in '.' or we treat it like it has none */ alen = vfat_striptail_len(name); blen = __vfat_striptail_len(len, str); if (alen == blen) { if (nls_strnicmp(t, name->name, str, alen) == 0) return 0; } return 1; } /* * Case sensitive compare of two vfat names. */ static int vfat_cmp(const struct dentry *parent, const struct inode *pinode, const struct dentry *dentry, const struct inode *inode, unsigned int len, const char *str, const struct qstr *name) { unsigned int alen, blen; /* A filename cannot end in '.' or we treat it like it has none */ alen = vfat_striptail_len(name); blen = __vfat_striptail_len(len, str); if (alen == blen) { if (strncmp(name->name, str, alen) == 0) return 0; } return 1; } static const struct dentry_operations vfat_ci_dentry_ops = { .d_revalidate = vfat_revalidate_ci, .d_hash = vfat_hashi, .d_compare = vfat_cmpi, }; static const struct dentry_operations vfat_dentry_ops = { .d_revalidate = vfat_revalidate, .d_hash = vfat_hash, .d_compare = vfat_cmp, }; /* Characters that are undesirable in an MS-DOS file name */ static inline wchar_t vfat_bad_char(wchar_t w) { return (w < 0x0020) || (w == '*') || (w == '?') || (w == '<') || (w == '>') || (w == '|') || (w == '"') || (w == ':') || (w == '/') || (w == '\\'); } static inline wchar_t vfat_replace_char(wchar_t w) { return (w == '[') || (w == ']') || (w == ';') || (w == ',') || (w == '+') || (w == '='); } static wchar_t vfat_skip_char(wchar_t w) { return (w == '.') || (w == ' '); } static inline int vfat_is_used_badchars(const wchar_t *s, int len) { int i; for (i = 0; i < len; i++) if (vfat_bad_char(s[i])) return -EINVAL; if (s[i - 1] == ' ') /* last character cannot be space */ return -EINVAL; return 0; } static int vfat_find_form(struct inode *dir, unsigned char *name) { struct fat_slot_info sinfo; int err = fat_scan(dir, name, &sinfo); if (err) return -ENOENT; brelse(sinfo.bh); return 0; } /* * 1) Valid characters for the 8.3 format alias are any combination of * letters, uppercase alphabets, digits, any of the * following special characters: * $ % ' ` - @ { } ~ ! # ( ) & _ ^ * In this case Longfilename is not stored in disk. * * WinNT's Extension: * File name and extension name is contain uppercase/lowercase * only. And it is expressed by CASE_LOWER_BASE and CASE_LOWER_EXT. * * 2) File name is 8.3 format, but it contain the uppercase and * lowercase char, muliti bytes char, etc. In this case numtail is not * added, but Longfilename is stored. * * 3) When the one except for the above, or the following special * character are contained: * . [ ] ; , + = * numtail is added, and Longfilename must be stored in disk . */ struct shortname_info { unsigned char lower:1, upper:1, valid:1; }; #define INIT_SHORTNAME_INFO(x) do { \ (x)->lower = 1; \ (x)->upper = 1; \ (x)->valid = 1; \ } while (0) static inline int to_shortname_char(struct nls_table *nls, unsigned char *buf, int buf_size, wchar_t *src, struct shortname_info *info) { int len; if (vfat_skip_char(*src)) { info->valid = 0; return 0; } if (vfat_replace_char(*src)) { info->valid = 0; buf[0] = '_'; return 1; } len = nls->uni2char(*src, buf, buf_size); if (len <= 0) { info->valid = 0; buf[0] = '_'; len = 1; } else if (len == 1) { unsigned char prev = buf[0]; if (buf[0] >= 0x7F) { info->lower = 0; info->upper = 0; } buf[0] = nls_toupper(nls, buf[0]); if (isalpha(buf[0])) { if (buf[0] == prev) info->lower = 0; else info->upper = 0; } } else { info->lower = 0; info->upper = 0; } return len; } /* * Given a valid longname, create a unique shortname. Make sure the * shortname does not exist * Returns negative number on error, 0 for a normal * return, and 1 for valid shortname */ static int vfat_create_shortname(struct inode *dir, struct nls_table *nls, wchar_t *uname, int ulen, unsigned char *name_res, unsigned char *lcase) { struct fat_mount_options *opts = &MSDOS_SB(dir->i_sb)->options; wchar_t *ip, *ext_start, *end, *name_start; unsigned char base[9], ext[4], buf[5], *p; unsigned char charbuf[NLS_MAX_CHARSET_SIZE]; int chl, chi; int sz = 0, extlen, baselen, i, numtail_baselen, numtail2_baselen; int is_shortname; struct shortname_info base_info, ext_info; is_shortname = 1; INIT_SHORTNAME_INFO(&base_info); INIT_SHORTNAME_INFO(&ext_info); /* Now, we need to create a shortname from the long name */ ext_start = end = &uname[ulen]; while (--ext_start >= uname) { if (*ext_start == 0x002E) { /* is `.' */ if (ext_start == end - 1) { sz = ulen; ext_start = NULL; } break; } } if (ext_start == uname - 1) { sz = ulen; ext_start = NULL; } else if (ext_start) { /* * Names which start with a dot could be just * an extension eg. "...test". In this case Win95 * uses the extension as the name and sets no extension. */ name_start = &uname[0]; while (name_start < ext_start) { if (!vfat_skip_char(*name_start)) break; name_start++; } if (name_start != ext_start) { sz = ext_start - uname; ext_start++; } else { sz = ulen; ext_start = NULL; } } numtail_baselen = 6; numtail2_baselen = 2; for (baselen = i = 0, p = base, ip = uname; i < sz; i++, ip++) { chl = to_shortname_char(nls, charbuf, sizeof(charbuf), ip, &base_info); if (chl == 0) continue; if (baselen < 2 && (baselen + chl) > 2) numtail2_baselen = baselen; if (baselen < 6 && (baselen + chl) > 6) numtail_baselen = baselen; for (chi = 0; chi < chl; chi++) { *p++ = charbuf[chi]; baselen++; if (baselen >= 8) break; } if (baselen >= 8) { if ((chi < chl - 1) || (ip + 1) - uname < sz) is_shortname = 0; break; } } if (baselen == 0) { return -EINVAL; } extlen = 0; if (ext_start) { for (p = ext, ip = ext_start; extlen < 3 && ip < end; ip++) { chl = to_shortname_char(nls, charbuf, sizeof(charbuf), ip, &ext_info); if (chl == 0) continue; if ((extlen + chl) > 3) { is_shortname = 0; break; } for (chi = 0; chi < chl; chi++) { *p++ = charbuf[chi]; extlen++; } if (extlen >= 3) { if (ip + 1 != end) is_shortname = 0; break; } } } ext[extlen] = '\0'; base[baselen] = '\0'; /* Yes, it can happen. ".\xe5" would do it. */ if (base[0] == DELETED_FLAG) base[0] = 0x05; /* OK, at this point we know that base is not longer than 8 symbols, * ext is not longer than 3, base is nonempty, both don't contain * any bad symbols (lowercase transformed to uppercase). */ memset(name_res, ' ', MSDOS_NAME); memcpy(name_res, base, baselen); memcpy(name_res + 8, ext, extlen); *lcase = 0; if (is_shortname && base_info.valid && ext_info.valid) { if (vfat_find_form(dir, name_res) == 0) return -EEXIST; if (opts->shortname & VFAT_SFN_CREATE_WIN95) { return (base_info.upper && ext_info.upper); } else if (opts->shortname & VFAT_SFN_CREATE_WINNT) { if ((base_info.upper || base_info.lower) && (ext_info.upper || ext_info.lower)) { if (!base_info.upper && base_info.lower) *lcase |= CASE_LOWER_BASE; if (!ext_info.upper && ext_info.lower) *lcase |= CASE_LOWER_EXT; return 1; } return 0; } else { BUG(); } } if (opts->numtail == 0) if (vfat_find_form(dir, name_res) < 0) return 0; /* * Try to find a unique extension. This used to * iterate through all possibilities sequentially, * but that gave extremely bad performance. Windows * only tries a few cases before using random * values for part of the base. */ if (baselen > 6) { baselen = numtail_baselen; name_res[7] = ' '; } name_res[baselen] = '~'; for (i = 1; i < 10; i++) { name_res[baselen + 1] = i + '0'; if (vfat_find_form(dir, name_res) < 0) return 0; } i = jiffies; sz = (jiffies >> 16) & 0x7; if (baselen > 2) { baselen = numtail2_baselen; name_res[7] = ' '; } name_res[baselen + 4] = '~'; name_res[baselen + 5] = '1' + sz; while (1) { snprintf(buf, sizeof(buf), "%04X", i & 0xffff); memcpy(&name_res[baselen], buf, 4); if (vfat_find_form(dir, name_res) < 0) break; i -= 11; } return 0; } /* Translate a string, including coded sequences into Unicode */ static int xlate_to_uni(const unsigned char *name, int len, unsigned char *outname, int *longlen, int *outlen, int escape, int utf8, struct nls_table *nls) { const unsigned char *ip; unsigned char nc; unsigned char *op; unsigned int ec; int i, k, fill; int charlen; if (utf8) { *outlen = utf8s_to_utf16s(name, len, (wchar_t *)outname); if (*outlen < 0) return *outlen; else if (*outlen > FAT_LFN_LEN) return -ENAMETOOLONG; op = &outname[*outlen * sizeof(wchar_t)]; } else { if (nls) { for (i = 0, ip = name, op = outname, *outlen = 0; i < len && *outlen <= FAT_LFN_LEN; *outlen += 1) { if (escape && (*ip == ':')) { if (i > len - 5) return -EINVAL; ec = 0; for (k = 1; k < 5; k++) { nc = ip[k]; ec <<= 4; if (nc >= '0' && nc <= '9') { ec |= nc - '0'; continue; } if (nc >= 'a' && nc <= 'f') { ec |= nc - ('a' - 10); continue; } if (nc >= 'A' && nc <= 'F') { ec |= nc - ('A' - 10); continue; } return -EINVAL; } *op++ = ec & 0xFF; *op++ = ec >> 8; ip += 5; i += 5; } else { if ((charlen = nls->char2uni(ip, len - i, (wchar_t *)op)) < 0) return -EINVAL; ip += charlen; i += charlen; op += 2; } } if (i < len) return -ENAMETOOLONG; } else { for (i = 0, ip = name, op = outname, *outlen = 0; i < len && *outlen <= FAT_LFN_LEN; i++, *outlen += 1) { *op++ = *ip++; *op++ = 0; } if (i < len) return -ENAMETOOLONG; } } *longlen = *outlen; if (*outlen % 13) { *op++ = 0; *op++ = 0; *outlen += 1; if (*outlen % 13) { fill = 13 - (*outlen % 13); for (i = 0; i < fill; i++) { *op++ = 0xff; *op++ = 0xff; } *outlen += fill; } } return 0; } static int vfat_build_slots(struct inode *dir, const unsigned char *name, int len, int is_dir, int cluster, struct timespec *ts, struct msdos_dir_slot *slots, int *nr_slots) { struct msdos_sb_info *sbi = MSDOS_SB(dir->i_sb); struct fat_mount_options *opts = &sbi->options; struct msdos_dir_slot *ps; struct msdos_dir_entry *de; unsigned char cksum, lcase; unsigned char msdos_name[MSDOS_NAME]; wchar_t *uname; __le16 time, date; u8 time_cs; int err, ulen, usize, i; loff_t offset; *nr_slots = 0; uname = __getname(); if (!uname) return -ENOMEM; err = xlate_to_uni(name, len, (unsigned char *)uname, &ulen, &usize, opts->unicode_xlate, opts->utf8, sbi->nls_io); if (err) goto out_free; err = vfat_is_used_badchars(uname, ulen); if (err) goto out_free; err = vfat_create_shortname(dir, sbi->nls_disk, uname, ulen, msdos_name, &lcase); if (err < 0) goto out_free; else if (err == 1) { de = (struct msdos_dir_entry *)slots; err = 0; goto shortname; } /* build the entry of long file name */ cksum = fat_checksum(msdos_name); *nr_slots = usize / 13; for (ps = slots, i = *nr_slots; i > 0; i--, ps++) { ps->id = i; ps->attr = ATTR_EXT; ps->reserved = 0; ps->alias_checksum = cksum; ps->start = 0; offset = (i - 1) * 13; fatwchar_to16(ps->name0_4, uname + offset, 5); fatwchar_to16(ps->name5_10, uname + offset + 5, 6); fatwchar_to16(ps->name11_12, uname + offset + 11, 2); } slots[0].id |= 0x40; de = (struct msdos_dir_entry *)ps; shortname: /* build the entry of 8.3 alias name */ (*nr_slots)++; memcpy(de->name, msdos_name, MSDOS_NAME); de->attr = is_dir ? ATTR_DIR : ATTR_ARCH; de->lcase = lcase; fat_time_unix2fat(sbi, ts, &time, &date, &time_cs); de->time = de->ctime = time; de->date = de->cdate = de->adate = date; de->ctime_cs = time_cs; de->start = cpu_to_le16(cluster); de->starthi = cpu_to_le16(cluster >> 16); de->size = 0; out_free: __putname(uname); return err; } static int vfat_add_entry(struct inode *dir, struct qstr *qname, int is_dir, int cluster, struct timespec *ts, struct fat_slot_info *sinfo) { struct msdos_dir_slot *slots; unsigned int len; int err, nr_slots; len = vfat_striptail_len(qname); if (len == 0) return -ENOENT; slots = kmalloc(sizeof(*slots) * MSDOS_SLOTS, GFP_NOFS); if (slots == NULL) return -ENOMEM; err = vfat_build_slots(dir, qname->name, len, is_dir, cluster, ts, slots, &nr_slots); if (err) goto cleanup; err = fat_add_entries(dir, slots, nr_slots, sinfo); if (err) goto cleanup; /* update timestamp */ dir->i_ctime = dir->i_mtime = dir->i_atime = *ts; if (IS_DIRSYNC(dir)) (void)fat_sync_inode(dir); else mark_inode_dirty(dir); cleanup: kfree(slots); return err; } static int vfat_find(struct inode *dir, struct qstr *qname, struct fat_slot_info *sinfo) { unsigned int len = vfat_striptail_len(qname); if (len == 0) return -ENOENT; return fat_search_long(dir, qname->name, len, sinfo); } /* * (nfsd's) anonymous disconnected dentry? * NOTE: !IS_ROOT() is not anonymous (I.e. d_splice_alias() did the job). */ static int vfat_d_anon_disconn(struct dentry *dentry) { return IS_ROOT(dentry) && (dentry->d_flags & DCACHE_DISCONNECTED); } static struct dentry *vfat_lookup(struct inode *dir, struct dentry *dentry, struct nameidata *nd) { struct super_block *sb = dir->i_sb; struct fat_slot_info sinfo; struct inode *inode; struct dentry *alias; int err; lock_super(sb); err = vfat_find(dir, &dentry->d_name, &sinfo); if (err) { if (err == -ENOENT) { inode = NULL; goto out; } goto error; } inode = fat_build_inode(sb, sinfo.de, sinfo.i_pos); brelse(sinfo.bh); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto error; } alias = d_find_alias(inode); if (alias && !vfat_d_anon_disconn(alias)) { /* * This inode has non anonymous-DCACHE_DISCONNECTED * dentry. This means, the user did ->lookup() by an * another name (longname vs 8.3 alias of it) in past. * * Switch to new one for reason of locality if possible. */ BUG_ON(d_unhashed(alias)); if (!S_ISDIR(inode->i_mode)) d_move(alias, dentry); iput(inode); unlock_super(sb); return alias; } else dput(alias); out: unlock_super(sb); dentry->d_time = dentry->d_parent->d_inode->i_version; dentry = d_splice_alias(inode, dentry); if (dentry) dentry->d_time = dentry->d_parent->d_inode->i_version; return dentry; error: unlock_super(sb); return ERR_PTR(err); } static int vfat_create(struct inode *dir, struct dentry *dentry, int mode, struct nameidata *nd) { struct super_block *sb = dir->i_sb; struct inode *inode; struct fat_slot_info sinfo; struct timespec ts; int err; lock_super(sb); ts = CURRENT_TIME_SEC; err = vfat_add_entry(dir, &dentry->d_name, 0, 0, &ts, &sinfo); if (err) goto out; dir->i_version++; inode = fat_build_inode(sb, sinfo.de, sinfo.i_pos); brelse(sinfo.bh); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out; } inode->i_version++; inode->i_mtime = inode->i_atime = inode->i_ctime = ts; /* timestamp is already written, so mark_inode_dirty() is unneeded. */ dentry->d_time = dentry->d_parent->d_inode->i_version; d_instantiate(dentry, inode); out: unlock_super(sb); return err; } static int vfat_rmdir(struct inode *dir, struct dentry *dentry) { struct inode *inode = dentry->d_inode; struct super_block *sb = dir->i_sb; struct fat_slot_info sinfo; int err; lock_super(sb); err = fat_dir_empty(inode); if (err) goto out; err = vfat_find(dir, &dentry->d_name, &sinfo); if (err) goto out; err = fat_remove_entries(dir, &sinfo); /* and releases bh */ if (err) goto out; drop_nlink(dir); clear_nlink(inode); inode->i_mtime = inode->i_atime = CURRENT_TIME_SEC; fat_detach(inode); out: unlock_super(sb); return err; } static int vfat_unlink(struct inode *dir, struct dentry *dentry) { struct inode *inode = dentry->d_inode; struct super_block *sb = dir->i_sb; struct fat_slot_info sinfo; int err; lock_super(sb); err = vfat_find(dir, &dentry->d_name, &sinfo); if (err) goto out; err = fat_remove_entries(dir, &sinfo); /* and releases bh */ if (err) goto out; clear_nlink(inode); inode->i_mtime = inode->i_atime = CURRENT_TIME_SEC; fat_detach(inode); out: unlock_super(sb); return err; } static int vfat_mkdir(struct inode *dir, struct dentry *dentry, int mode) { struct super_block *sb = dir->i_sb; struct inode *inode; struct fat_slot_info sinfo; struct timespec ts; int err, cluster; lock_super(sb); ts = CURRENT_TIME_SEC; cluster = fat_alloc_new_dir(dir, &ts); if (cluster < 0) { err = cluster; goto out; } err = vfat_add_entry(dir, &dentry->d_name, 1, cluster, &ts, &sinfo); if (err) goto out_free; dir->i_version++; inc_nlink(dir); inode = fat_build_inode(sb, sinfo.de, sinfo.i_pos); brelse(sinfo.bh); if (IS_ERR(inode)) { err = PTR_ERR(inode); /* the directory was completed, just return a error */ goto out; } inode->i_version++; set_nlink(inode, 2); inode->i_mtime = inode->i_atime = inode->i_ctime = ts; /* timestamp is already written, so mark_inode_dirty() is unneeded. */ dentry->d_time = dentry->d_parent->d_inode->i_version; d_instantiate(dentry, inode); unlock_super(sb); return 0; out_free: fat_free_clusters(dir, cluster); out: unlock_super(sb); return err; } static int vfat_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { struct buffer_head *dotdot_bh; struct msdos_dir_entry *dotdot_de; struct inode *old_inode, *new_inode; struct fat_slot_info old_sinfo, sinfo; struct timespec ts; loff_t dotdot_i_pos, new_i_pos; int err, is_dir, update_dotdot, corrupt = 0; struct super_block *sb = old_dir->i_sb; old_sinfo.bh = sinfo.bh = dotdot_bh = NULL; old_inode = old_dentry->d_inode; new_inode = new_dentry->d_inode; lock_super(sb); err = vfat_find(old_dir, &old_dentry->d_name, &old_sinfo); if (err) goto out; is_dir = S_ISDIR(old_inode->i_mode); update_dotdot = (is_dir && old_dir != new_dir); if (update_dotdot) { if (fat_get_dotdot_entry(old_inode, &dotdot_bh, &dotdot_de, &dotdot_i_pos) < 0) { err = -EIO; goto out; } } ts = CURRENT_TIME_SEC; if (new_inode) { if (is_dir) { err = fat_dir_empty(new_inode); if (err) goto out; } new_i_pos = MSDOS_I(new_inode)->i_pos; fat_detach(new_inode); } else { err = vfat_add_entry(new_dir, &new_dentry->d_name, is_dir, 0, &ts, &sinfo); if (err) goto out; new_i_pos = sinfo.i_pos; } new_dir->i_version++; fat_detach(old_inode); fat_attach(old_inode, new_i_pos); if (IS_DIRSYNC(new_dir)) { err = fat_sync_inode(old_inode); if (err) goto error_inode; } else mark_inode_dirty(old_inode); if (update_dotdot) { int start = MSDOS_I(new_dir)->i_logstart; dotdot_de->start = cpu_to_le16(start); dotdot_de->starthi = cpu_to_le16(start >> 16); mark_buffer_dirty_inode(dotdot_bh, old_inode); if (IS_DIRSYNC(new_dir)) { err = sync_dirty_buffer(dotdot_bh); if (err) goto error_dotdot; } drop_nlink(old_dir); if (!new_inode) inc_nlink(new_dir); } err = fat_remove_entries(old_dir, &old_sinfo); /* and releases bh */ old_sinfo.bh = NULL; if (err) goto error_dotdot; old_dir->i_version++; old_dir->i_ctime = old_dir->i_mtime = ts; if (IS_DIRSYNC(old_dir)) (void)fat_sync_inode(old_dir); else mark_inode_dirty(old_dir); if (new_inode) { drop_nlink(new_inode); if (is_dir) drop_nlink(new_inode); new_inode->i_ctime = ts; } out: brelse(sinfo.bh); brelse(dotdot_bh); brelse(old_sinfo.bh); unlock_super(sb); return err; error_dotdot: /* data cluster is shared, serious corruption */ corrupt = 1; if (update_dotdot) { int start = MSDOS_I(old_dir)->i_logstart; dotdot_de->start = cpu_to_le16(start); dotdot_de->starthi = cpu_to_le16(start >> 16); mark_buffer_dirty_inode(dotdot_bh, old_inode); corrupt |= sync_dirty_buffer(dotdot_bh); } error_inode: fat_detach(old_inode); fat_attach(old_inode, old_sinfo.i_pos); if (new_inode) { fat_attach(new_inode, new_i_pos); if (corrupt) corrupt |= fat_sync_inode(new_inode); } else { /* * If new entry was not sharing the data cluster, it * shouldn't be serious corruption. */ int err2 = fat_remove_entries(new_dir, &sinfo); if (corrupt) corrupt |= err2; sinfo.bh = NULL; } if (corrupt < 0) { fat_fs_error(new_dir->i_sb, "%s: Filesystem corrupted (i_pos %lld)", __func__, sinfo.i_pos); } goto out; } static const struct inode_operations vfat_dir_inode_operations = { .create = vfat_create, .lookup = vfat_lookup, .unlink = vfat_unlink, .mkdir = vfat_mkdir, .rmdir = vfat_rmdir, .rename = vfat_rename, .setattr = fat_setattr, .getattr = fat_getattr, }; static void setup(struct super_block *sb) { MSDOS_SB(sb)->dir_ops = &vfat_dir_inode_operations; if (MSDOS_SB(sb)->options.name_check != 's') sb->s_d_op = &vfat_ci_dentry_ops; else sb->s_d_op = &vfat_dentry_ops; } static int vfat_fill_super(struct super_block *sb, void *data, int silent) { return fat_fill_super(sb, data, silent, 1, setup); } static struct dentry *vfat_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_bdev(fs_type, flags, dev_name, data, vfat_fill_super); } static struct file_system_type vfat_fs_type = { .owner = THIS_MODULE, .name = "vfat", .mount = vfat_mount, .kill_sb = kill_block_super, .fs_flags = FS_REQUIRES_DEV, }; static int __init init_vfat_fs(void) { return register_filesystem(&vfat_fs_type); } static void __exit exit_vfat_fs(void) { unregister_filesystem(&vfat_fs_type); } MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("VFAT filesystem support"); MODULE_AUTHOR("Gordon Chaffee"); module_init(init_vfat_fs) module_exit(exit_vfat_fs)
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5590_1
crossvul-cpp_data_good_1709_0
/* $Id: igd_desc_parse.c,v 1.17 2015/09/15 13:30:04 nanard Exp $ */ /* Project : miniupnp * http://miniupnp.free.fr/ * Author : Thomas Bernard * Copyright (c) 2005-2015 Thomas Bernard * This software is subject to the conditions detailed in the * LICENCE file provided in this distribution. */ #include "igd_desc_parse.h" #include <stdio.h> #include <string.h> /* Start element handler : * update nesting level counter and copy element name */ void IGDstartelt(void * d, const char * name, int l) { struct IGDdatas * datas = (struct IGDdatas *)d; if(l >= MINIUPNPC_URL_MAXSIZE) l = MINIUPNPC_URL_MAXSIZE-1; memcpy(datas->cureltname, name, l); datas->cureltname[l] = '\0'; datas->level++; if( (l==7) && !memcmp(name, "service", l) ) { datas->tmp.controlurl[0] = '\0'; datas->tmp.eventsuburl[0] = '\0'; datas->tmp.scpdurl[0] = '\0'; datas->tmp.servicetype[0] = '\0'; } } #define COMPARE(str, cstr) (0==memcmp(str, cstr, sizeof(cstr) - 1)) /* End element handler : * update nesting level counter and update parser state if * service element is parsed */ void IGDendelt(void * d, const char * name, int l) { struct IGDdatas * datas = (struct IGDdatas *)d; datas->level--; /*printf("endelt %2d %.*s\n", datas->level, l, name);*/ if( (l==7) && !memcmp(name, "service", l) ) { if(COMPARE(datas->tmp.servicetype, "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:")) { memcpy(&datas->CIF, &datas->tmp, sizeof(struct IGDdatas_service)); } else if(COMPARE(datas->tmp.servicetype, "urn:schemas-upnp-org:service:WANIPv6FirewallControl:")) { memcpy(&datas->IPv6FC, &datas->tmp, sizeof(struct IGDdatas_service)); } else if(COMPARE(datas->tmp.servicetype, "urn:schemas-upnp-org:service:WANIPConnection:") || COMPARE(datas->tmp.servicetype, "urn:schemas-upnp-org:service:WANPPPConnection:") ) { if(datas->first.servicetype[0] == '\0') { memcpy(&datas->first, &datas->tmp, sizeof(struct IGDdatas_service)); } else { memcpy(&datas->second, &datas->tmp, sizeof(struct IGDdatas_service)); } } } } /* Data handler : * copy data depending on the current element name and state */ void IGDdata(void * d, const char * data, int l) { struct IGDdatas * datas = (struct IGDdatas *)d; char * dstmember = 0; /*printf("%2d %s : %.*s\n", datas->level, datas->cureltname, l, data); */ if( !strcmp(datas->cureltname, "URLBase") ) dstmember = datas->urlbase; else if( !strcmp(datas->cureltname, "presentationURL") ) dstmember = datas->presentationurl; else if( !strcmp(datas->cureltname, "serviceType") ) dstmember = datas->tmp.servicetype; else if( !strcmp(datas->cureltname, "controlURL") ) dstmember = datas->tmp.controlurl; else if( !strcmp(datas->cureltname, "eventSubURL") ) dstmember = datas->tmp.eventsuburl; else if( !strcmp(datas->cureltname, "SCPDURL") ) dstmember = datas->tmp.scpdurl; /* else if( !strcmp(datas->cureltname, "deviceType") ) dstmember = datas->devicetype_tmp;*/ if(dstmember) { if(l>=MINIUPNPC_URL_MAXSIZE) l = MINIUPNPC_URL_MAXSIZE-1; memcpy(dstmember, data, l); dstmember[l] = '\0'; } } #ifdef DEBUG void printIGD(struct IGDdatas * d) { printf("urlbase = '%s'\n", d->urlbase); printf("WAN Device (Common interface config) :\n"); /*printf(" deviceType = '%s'\n", d->CIF.devicetype);*/ printf(" serviceType = '%s'\n", d->CIF.servicetype); printf(" controlURL = '%s'\n", d->CIF.controlurl); printf(" eventSubURL = '%s'\n", d->CIF.eventsuburl); printf(" SCPDURL = '%s'\n", d->CIF.scpdurl); printf("primary WAN Connection Device (IP or PPP Connection):\n"); /*printf(" deviceType = '%s'\n", d->first.devicetype);*/ printf(" servicetype = '%s'\n", d->first.servicetype); printf(" controlURL = '%s'\n", d->first.controlurl); printf(" eventSubURL = '%s'\n", d->first.eventsuburl); printf(" SCPDURL = '%s'\n", d->first.scpdurl); printf("secondary WAN Connection Device (IP or PPP Connection):\n"); /*printf(" deviceType = '%s'\n", d->second.devicetype);*/ printf(" servicetype = '%s'\n", d->second.servicetype); printf(" controlURL = '%s'\n", d->second.controlurl); printf(" eventSubURL = '%s'\n", d->second.eventsuburl); printf(" SCPDURL = '%s'\n", d->second.scpdurl); printf("WAN IPv6 Firewall Control :\n"); /*printf(" deviceType = '%s'\n", d->IPv6FC.devicetype);*/ printf(" servicetype = '%s'\n", d->IPv6FC.servicetype); printf(" controlURL = '%s'\n", d->IPv6FC.controlurl); printf(" eventSubURL = '%s'\n", d->IPv6FC.eventsuburl); printf(" SCPDURL = '%s'\n", d->IPv6FC.scpdurl); } #endif /* DEBUG */
./CrossVul/dataset_final_sorted/CWE-119/c/good_1709_0
crossvul-cpp_data_good_5733_3
/* * Copyright (c) 2011 Mark Himsley * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * video field order filter, heavily influenced by vf_pad.c */ #include "libavutil/opt.h" #include "libavutil/imgutils.h" #include "libavutil/internal.h" #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "avfilter.h" #include "formats.h" #include "internal.h" #include "video.h" typedef struct { const AVClass *class; int dst_tff; ///< output bff/tff int line_size[4]; ///< bytes of pixel data per line for each plane } FieldOrderContext; static int query_formats(AVFilterContext *ctx) { AVFilterFormats *formats; enum AVPixelFormat pix_fmt; int ret; /** accept any input pixel format that is not hardware accelerated, not * a bitstream format, and does not have vertically sub-sampled chroma */ if (ctx->inputs[0]) { formats = NULL; for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL || desc->flags & AV_PIX_FMT_FLAG_BITSTREAM) && desc->nb_components && !desc->log2_chroma_h && (ret = ff_add_format(&formats, pix_fmt)) < 0) { ff_formats_unref(&formats); return ret; } } ff_formats_ref(formats, &ctx->inputs[0]->out_formats); ff_formats_ref(formats, &ctx->outputs[0]->in_formats); } return 0; } static int config_input(AVFilterLink *inlink) { AVFilterContext *ctx = inlink->dst; FieldOrderContext *s = ctx->priv; int plane; /** full an array with the number of bytes that the video * data occupies per line for each plane of the input video */ for (plane = 0; plane < 4; plane++) { s->line_size[plane] = av_image_get_linesize(inlink->format, inlink->w, plane); } return 0; } static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h) { AVFilterContext *ctx = inlink->dst; AVFilterLink *outlink = ctx->outputs[0]; return ff_get_video_buffer(outlink, w, h); } static int filter_frame(AVFilterLink *inlink, AVFrame *frame) { AVFilterContext *ctx = inlink->dst; FieldOrderContext *s = ctx->priv; AVFilterLink *outlink = ctx->outputs[0]; int h, plane, line_step, line_size, line; uint8_t *data; if (!frame->interlaced_frame || frame->top_field_first == s->dst_tff) return ff_filter_frame(outlink, frame); av_dlog(ctx, "picture will move %s one line\n", s->dst_tff ? "up" : "down"); h = frame->height; for (plane = 0; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++) { line_step = frame->linesize[plane]; line_size = s->line_size[plane]; data = frame->data[plane]; if (s->dst_tff) { /** Move every line up one line, working from * the top to the bottom of the frame. * The original top line is lost. * The new last line is created as a copy of the * penultimate line from that field. */ for (line = 0; line < h; line++) { if (1 + line < frame->height) { memcpy(data, data + line_step, line_size); } else { memcpy(data, data - line_step - line_step, line_size); } data += line_step; } } else { /** Move every line down one line, working from * the bottom to the top of the frame. * The original bottom line is lost. * The new first line is created as a copy of the * second line from that field. */ data += (h - 1) * line_step; for (line = h - 1; line >= 0 ; line--) { if (line > 0) { memcpy(data, data - line_step, line_size); } else { memcpy(data, data + line_step + line_step, line_size); } data -= line_step; } } } frame->top_field_first = s->dst_tff; return ff_filter_frame(outlink, frame); } #define OFFSET(x) offsetof(FieldOrderContext, x) #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM static const AVOption fieldorder_options[] = { { "order", "output field order", OFFSET(dst_tff), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS, "order" }, { "bff", "bottom field first", 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, .flags=FLAGS, .unit = "order" }, { "tff", "top field first", 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, .flags=FLAGS, .unit = "order" }, { NULL }, }; AVFILTER_DEFINE_CLASS(fieldorder); static const AVFilterPad avfilter_vf_fieldorder_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .config_props = config_input, .get_video_buffer = get_video_buffer, .filter_frame = filter_frame, .needs_writable = 1, }, { NULL } }; static const AVFilterPad avfilter_vf_fieldorder_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, }, { NULL } }; AVFilter avfilter_vf_fieldorder = { .name = "fieldorder", .description = NULL_IF_CONFIG_SMALL("Set the field order."), .priv_size = sizeof(FieldOrderContext), .priv_class = &fieldorder_class, .query_formats = query_formats, .inputs = avfilter_vf_fieldorder_inputs, .outputs = avfilter_vf_fieldorder_outputs, };
./CrossVul/dataset_final_sorted/CWE-119/c/good_5733_3
crossvul-cpp_data_bad_3288_0
/* ** Copyright (C) 2010-2011 Erik de Castro Lopo <erikd@mega-nerd.com> ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as published by ** the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "sfconfig.h" #include <stdio.h> #include <fcntl.h> #include <string.h> #include <ctype.h> #include "sndfile.h" #include "sfendian.h" #include "common.h" int id3_skip (SF_PRIVATE * psf) { unsigned char buf [10] ; memset (buf, 0, sizeof (buf)) ; psf_binheader_readf (psf, "pb", 0, buf, 10) ; if (buf [0] == 'I' && buf [1] == 'D' && buf [2] == '3') { int offset = buf [6] & 0x7f ; offset = (offset << 7) | (buf [7] & 0x7f) ; offset = (offset << 7) | (buf [8] & 0x7f) ; offset = (offset << 7) | (buf [9] & 0x7f) ; psf_log_printf (psf, "ID3 length : %d\n--------------------\n", offset) ; /* Never want to jump backwards in a file. */ if (offset < 0) return 0 ; /* Calculate new file offset and position ourselves there. */ psf->fileoffset += offset + 10 ; psf_binheader_readf (psf, "p", psf->fileoffset) ; return 1 ; } ; return 0 ; } /* id3_skip */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3288_0
crossvul-cpp_data_good_3406_0
/* radare - LGPL - Copyright 2009-2017 - nibble, pancake */ #if 0 * Use RList * Support callback for null command (why?) * Show help of commands - long commands not yet tested at all - added interface to export command list into an autocompletable argc, argv for dietline * r_cmd must provide a nesting char table indexing for commands - this is already partially done - this is pretty similar to r_db - every module can register their own commands - commands can be listed like in a tree #endif #define INTERACTIVE_MAX_REP 1024 #include <r_core.h> #include <r_anal.h> #include <r_cons.h> #include <stdint.h> #include <sys/types.h> #include <ctype.h> #include <stdarg.h> #if __UNIX__ #include <sys/utsname.h> #endif static void cmd_debug_reg(RCore *core, const char *str); #include "cmd_quit.c" #include "cmd_hash.c" #include "cmd_debug.c" #include "cmd_log.c" #include "cmd_zign.c" #include "cmd_section.c" #include "cmd_flag.c" #include "cmd_project.c" #include "cmd_write.c" #include "cmd_cmp.c" #include "cmd_eval.c" #include "cmd_anal.c" #include "cmd_open.c" #include "cmd_meta.c" #include "cmd_type.c" #include "cmd_egg.c" #include "cmd_info.c" #include "cmd_macro.c" #include "cmd_magic.c" #include "cmd_mount.c" #include "cmd_seek.c" #include "cmd_print.c" #include "cmd_help.c" #include "cmd_search.c" static void recursive_help(RCore *core, const char *cmd) { char *nl, *line; if (strchr (cmd, '[')) { // eprintf ("Skip ((%s))\n", cmd); return; } char *msg = r_core_cmd_str (core, cmd); if (!msg) { return; } line = msg; r_cons_print (msg); (void) r_str_ansi_filter (msg, NULL, NULL, strlen (msg)); do { nl = strchr (line, '\n'); if (nl) { *nl = 0; } if (r_cons_is_breaked ()) { break; } char *help_token = strstr (line, "[?]"); if (help_token) { help_token[0] = '?'; help_token[1] = 0; const char *sp = strchr (line, ' '); if (sp) { recursive_help (core, sp + 1); } } line = nl + 1; } while (nl); free (msg); } static int r_core_cmd_nullcallback(void *data) { RCore *core = (RCore*) data; if (core->cons->breaked) { core->cons->breaked = false; return 0; } if (!core->cmdrepeat) { return 0; } r_core_cmd_repeat (core, true); return 1; } // TODO: move somewhere else R_API RAsmOp *r_core_disassemble (RCore *core, ut64 addr) { int delta; ut8 buf[128]; static RBuffer *b = NULL; // XXX: never freed and non-thread safe. move to RCore RAsmOp *op; if (!b) { b = r_buf_new (); if (!b || !r_core_read_at (core, addr, buf, sizeof (buf))) { return NULL; } b->base = addr; r_buf_set_bytes (b, buf, sizeof (buf)); } else { if ((addr < b->base) || addr > (b->base + b->length - 32)) { if (!r_core_read_at (core, addr, buf, sizeof (buf))) { return NULL; } b->base = addr; r_buf_set_bytes (b, buf, sizeof (buf)); } } delta = addr - b->base; op = R_NEW0 (RAsmOp); r_asm_set_pc (core->assembler, addr); if (r_asm_disassemble (core->assembler, op, b->buf + delta, b->length) < 1) { free (op); return NULL; } return op; } static int cmd_uname(void *data, const char *input) { const char* help_msg[] = { "Usage:", "u", "uname or undo write/seek", "u", "", "show system uname", "uw", "", "alias for wc (requires: e io.cache=true)", "us", "", "alias for s- (seek history)", NULL}; switch (input[0]) { case '?': r_core_cmd_help (data, help_msg); return 1; case 's': r_core_cmdf (data, "s-%s", input + 1); return 1; case 'w': r_core_cmdf (data, "wc%s", input + 1); return 1; } #if __UNIX__ struct utsname un; uname (&un); r_cons_printf ("%s %s %s %s\n", un.sysname, un.nodename, un.release, un.machine); #elif __WINDOWS__ r_cons_printf ("windows\n"); #else r_cons_printf ("unknown\n"); #endif return 0; } static int cmd_alias(void *data, const char *input) { int i; char *def, *q, *desc, *buf; RCore *core = (RCore *)data; if (*input == '?') { const char* help_msg[] = { "Usage:", "$alias[=cmd] [args...]", "Alias commands", "$", "", "list all defined aliases", "$*", "", "same as above, but using r2 commands", "$", "dis='af;pdf'", "create command - analyze to show function", "$", "test=#!pipe node /tmp/test.js", "create command - rlangpipe script", "$", "dis=", "undefine alias", "$", "dis", "execute the previously defined alias", "$", "dis?", "show commands aliased by 'analyze'", NULL}; r_core_cmd_help (core, help_msg); return 0; } i = strlen (input); buf = malloc (i + 2); if (!buf) { return 0; } *buf = '$'; // prefix aliases with a dash memcpy (buf + 1, input, i + 1); q = strchr (buf, ' '); def = strchr (buf, '='); desc = strchr (buf, '?'); /* create alias */ if ((def && q && (def < q)) || (def && !q)) { *def++ = 0; size_t len = strlen (def); /* Remove quotes */ if ((def[0] == '\'') && (def[len - 1] == '\'')) { def[len - 1] = 0x00; def++; } if (!q || (q && q>def)) { if (*def) r_cmd_alias_set (core->rcmd, buf, def, 0); else r_cmd_alias_del (core->rcmd, buf); } /* Show command for alias */ } else if (desc && !q) { char *v; *desc = 0; v = r_cmd_alias_get (core->rcmd, buf, 0); if (v) { r_cons_println (v); free (buf); return 1; } else { eprintf ("unknown key '%s'\n", buf); } /* Show aliases */ } else if (buf[1] == '*') { int i, count = 0; char **keys = r_cmd_alias_keys (core->rcmd, &count); for (i = 0; i < count; i++) { const char *v = r_cmd_alias_get (core->rcmd, keys[i], 0); r_cons_printf ("%s=%s\n", keys[i], v); } } else if (!buf[1]) { int i, count = 0; char **keys = r_cmd_alias_keys (core->rcmd, &count); for (i = 0; i < count; i++) { r_cons_println (keys[i]); } /* Execute alias */ } else { char *v; if (q) *q = 0; v = r_cmd_alias_get (core->rcmd, buf, 0); if (v) { if (q) { char *out, *args = q + 1; out = malloc (strlen (v) + strlen (args) + 2); if (out) { //XXX slow strcpy (out, v); strcat (out, " "); strcat (out, args); r_core_cmd0 (core, out); free (out); } else eprintf ("cannot malloc\n"); } else { r_core_cmd0 (core, v); } } else { eprintf ("unknown key '%s'\n", buf); } } free (buf); return 0; } static int getArg(char ch, int def) { switch (ch) { case '&': case '-': return ch; } return def; } static void aliascmd(RCore *core, const char *str) { switch (str[0]) { case '-': if (str[1]) { r_cmd_alias_del (core->rcmd, str + 2); } else { r_cmd_alias_del (core->rcmd, NULL); // r_cmd_alias_reset (core->rcmd); } break; case '?': eprintf ("Usage: =$[-][remotecmd] # remote command alias\n"); eprintf (" =$dr # makes 'dr' alias for =!dr\n"); eprintf (" =$-dr # unset 'dr' alias\n"); break; case 0: r_core_cmd0 (core, "$"); break; default: r_cmd_alias_set (core->rcmd, str, "", 1); break; } } static int cmd_rap(void *data, const char *input) { RCore *core = (RCore *)data; switch (*input) { case '$': aliascmd (core, input + 1); break; case '\0': r_core_rtr_list (core); break; case 'h': r_core_rtr_http (core, getArg (input[1], 'h'), input + 1); break; case 'H': while (input[1] == ' ') { input++; } r_core_rtr_http (core, getArg (input[1], 'H'), input + 1); break; case 'g': r_core_rtr_gdb (core, getArg (input[1], 'g'), input + 1); break; case '?': r_core_rtr_help (core); break; case '+': r_core_rtr_add (core, input + 1); break; case '-': r_core_rtr_remove (core, input + 1); break; case '=': r_core_rtr_session (core, input + 1); break; //case ':': r_core_rtr_cmds (core, input + 1); break; case '<': r_core_rtr_pushout (core, input + 1); break; case '!': if (input[1] == '=') { // swap core->cmdremote = core->cmdremote? 0: 1; core->cmdremote = input[2]? 1: 0; r_cons_println (r_str_bool (core->cmdremote)); } else { r_io_system (core->io, input + 1); } break; default: r_core_rtr_cmd (core, input); break; } return 0; } static int cmd_rap_run(void *data, const char *input) { RCore *core = (RCore *)data; return r_io_system (core->io, input); } static int cmd_yank(void *data, const char *input) { ut64 n; RCore *core = (RCore *)data; switch (input[0]) { case ' ': r_core_yank (core, core->offset, r_num_math (core->num, input + 1)); break; case 'l': core->num->value = core->yank_buf->length; break; case 'y': while (input[1] == ' ') { input++; } n = input[1]? r_num_math (core->num, input + 1): core->offset; r_core_yank_paste (core, n, 0); break; case 'x': r_core_yank_hexdump (core, r_num_math (core->num, input + 1)); break; case 'z': r_core_yank_string (core, core->offset, r_num_math (core->num, input + 1)); break; case 'w': switch (input[1]) { case ' ': r_core_yank_set (core, 0, (const ut8*)input + 2, strlen (input + 2)); break; case 'x': if (input[2] == ' ') { char *out = strdup (input + 3); int len = r_hex_str2bin (input + 3, (ut8*)out); if (len> 0) { r_core_yank_set (core, 0LL, (const ut8*)out, len); } else { eprintf ("Invalid length\n"); } free (out); } else { eprintf ("Usage: ywx [hexpairs]\n"); } // r_core_yank_write_hex (core, input + 2); break; } break; case 'p': r_core_yank_cat (core, r_num_math (core->num, input + 1)); break; case 's': r_core_yank_cat_string (core, r_num_math (core->num, input + 1)); break; case 't': // "wt" if (input[1] == 'f') { // "wtf" const char *file = r_str_chop_ro (input + 2); if (!r_file_dump (file, core->yank_buf->buf, core->yank_buf->length, false)) { eprintf ("Cannot dump to '%s'\n", file); } } else { r_core_yank_to (core, input + 1); } break; case 'f': switch (input[1]) { case ' ': // "wf" r_core_yank_file_ex (core, input + 1); break; case 'a': // "wfa" r_core_yank_file_all (core, input + 2); break; } break; case '\0': r_core_yank_dump (core, r_num_math (core->num, "")); break; default:{ const char* help_msg[] = { "Usage:", "y[ptxy] [len] [[@]addr]", " # See wd? for memcpy, same as 'yf'.", "y", "", "show yank buffer information (srcoff len bytes)", "y", " 16", "copy 16 bytes into clipboard", "y", " 16 0x200", "copy 16 bytes into clipboard from 0x200", "y", " 16 @ 0x200", "copy 16 bytes into clipboard from 0x200", "yz", "", "copy up to blocksize zero terminated string bytes into clipboard", "yz", " 16", "copy up to 16 zero terminated string bytes into clipboard", "yz", " @ 0x200", "copy up to blocksize zero terminated string bytes into clipboard from 0x200", "yz", " 16 @ 0x200", "copy up to 16 zero terminated string bytes into clipboard from 0x200", "yp", "", "print contents of clipboard", "yx", "", "print contents of clipboard in hexadecimal", "ys", "", "print contents of clipboard as string", "yt", " 64 0x200", "copy 64 bytes from current seek to 0x200", "ytf", " file", "dump the clipboard to given file", "yf", " 64 0x200", "file copy 64 bytes from 0x200 from file (opens w/ io), use -1 for all bytes", "yfa", " file copy", "copy all bytes from file (opens w/ io)", "yy", " 0x3344", "paste clipboard", NULL}; r_core_cmd_help (core, help_msg); } break; } return true; } R_API int r_core_run_script (RCore *core, const char *file) { int ret = false; RListIter *iter; RLangPlugin *p; char *name; r_list_foreach (core->scriptstack, iter, name) { if (!strcmp (file, name)) { eprintf ("WARNING: ignored nested source: %s\n", file); return false; } } r_list_push (core->scriptstack, strdup (file)); if (!strcmp (file, "-")) { char *out = r_core_editor (core, NULL, NULL); if (out) { ret = r_core_cmd_lines (core, out); free (out); } } else if (r_parse_is_c_file (file)) { char *out = r_parse_c_file (core->anal, file); if (out) { r_cons_strcat (out); sdb_query_lines (core->anal->sdb_types, out); free (out); } ret = out? true: false; } else { p = r_lang_get_by_extension (core->lang, file); if (p) { r_lang_use (core->lang, p->name); ret = r_lang_run_file (core->lang, file); } else { #if __WINDOWS__ #define cmdstr(x) r_str_newf (x" %s", file); #else #define cmdstr(x) r_str_newf (x" '%s'", file); #endif const char *p = r_str_lchr (file, '.'); if (p) { const char *ext = p + 1; /* TODO: handle this inside r_lang_pipe with new APIs */ if (!strcmp (ext, "js")) { char *cmd = cmdstr ("node"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "exe")) { #if __WINDOWS__ char *cmd = r_str_newf ("%s", file); #else char *cmd = cmdstr ("wine"); #endif r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "d")) { char *cmd = cmdstr ("dmd -run"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "lsp")) { char *cmd = cmdstr ("newlisp -n"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "go")) { char *cmd = cmdstr ("go run"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "es6")) { char *cmd = cmdstr ("babel-node"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "rb")) { char *cmd = cmdstr ("ruby %s"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "pl")) { char *cmd = cmdstr ("perl"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } else if (!strcmp (ext, "py")) { char *cmd = cmdstr ("python"); r_lang_use (core->lang, "pipe"); r_lang_run_file (core->lang, cmd); free (cmd); ret = 1; } } if (!ret) { ret = r_core_cmd_file (core, file); } } } free (r_list_pop (core->scriptstack)); return ret; } static int cmd_ls(void *data, const char *input) { if (*input) { char *res = r_syscmd_ls (input + 1); if (res) { r_cons_print (res); free (res); } } return 0; } static int cmd_stdin(void *data, const char *input) { RCore *core = (RCore *)data; if (input[0] == '?') { r_cons_printf ("Usage: '-' '.-' '. -' do the same\n"); return false; } return r_core_run_script (core, "-"); } static int cmd_interpret(void *data, const char *input) { char *str, *ptr, *eol, *rbuf, *filter, *inp; const char *host, *port, *cmd; RCore *core = (RCore *)data; switch (*input) { case '\0': r_core_cmd_repeat (core, 0); break; case ':': if ((ptr = strchr (input + 1, ' '))) { /* .:port cmd */ /* .:host:port cmd */ cmd = ptr + 1; *ptr = 0; eol = strchr (input + 1, ':'); if (eol) { *eol = 0; host = input + 1; port = eol + 1; } else { host = "localhost"; port = input + ((input[1] == ':')? 2: 1); } rbuf = r_core_rtr_cmds_query (core, host, port, cmd); if (rbuf) { r_cons_print (rbuf); free (rbuf); } } else { r_core_rtr_cmds (core, input + 1); } break; case '.': // same as \n r_core_cmd_repeat (core, 1); break; case '-': if (input[1] == '?') { r_cons_printf ("Usage: '-' '.-' '. -' do the same\n"); } else { r_core_run_script (core, "-"); } break; case ' ': if (!r_core_run_script (core, input + 1)) { eprintf ("Cannot find script '%s'\n", input + 1); core->num->value = 1; } else { core->num->value = 0; } break; case '!': /* from command */ r_core_cmd_command (core, input + 1); break; case '(': r_cmd_macro_call (&core->rcmd->macro, input + 1); break; case '?':{ const char* help_msg[] = { "Usage:", ".[r2cmd] | [file] | [!command] | [(macro)]", " # define macro or load r2, cparse or rlang file", ".", "", "repeat last command backward", ".", "r2cmd", "interpret the output of the command as r2 commands", "..", "", "repeat last command forward (same as \\n)", ".:", "8080", "listen for commands on given tcp port", ".", " foo.r2", "interpret r2 script", ".-", "", "open cfg.editor and interpret tmp file", ".!", "rabin -ri $FILE", "interpret output of command", ".", "(foo 1 2 3)", "run macro 'foo' with args 1, 2, 3", "./", " ELF", "interpret output of command /m ELF as r. commands", NULL}; r_core_cmd_help (core, help_msg); } break; default: if (*input >= 0 && *input <= 9) { eprintf ("|ERROR| No .[0..9] to avoid infinite loops\n"); break; } inp = strdup (input); filter = strchr (inp, '~'); if (filter) { *filter = 0; } ptr = str = r_core_cmd_str (core, inp); if (filter) { *filter = '~'; } r_cons_break_push (NULL, NULL); if (ptr) { for (;;) { if (r_cons_is_breaked ()) { break; } eol = strchr (ptr, '\n'); if (eol) *eol = '\0'; if (*ptr) { char *p = r_str_append (strdup (ptr), filter); r_core_cmd0 (core, p); free (p); } if (!eol) break; ptr = eol + 1; } } r_cons_break_pop (); free (str); free (inp); break; } return 0; } static int callback_foreach_kv (void *user, const char *k, const char *v) { r_cons_printf ("%s=%s\n", k, v); return 1; } static int cmd_kuery(void *data, const char *input) { char buf[1024], *out; RCore *core = (RCore*)data; const char *sp, *p = "[sdb]> "; const int buflen = sizeof (buf) - 1; Sdb *s = core->sdb; switch (input[0]) { case ' ': out = sdb_querys (s, NULL, 0, input + 1); if (out) { r_cons_println (out); } free (out); break; //case 's': r_pair_save (s, input + 3); break; //case 'l': r_pair_load (sdb, input + 3); break; case '\0': sdb_foreach (s, callback_foreach_kv, NULL); break; // TODO: add command to list all namespaces // sdb_ns_foreach ? case 's': if (core->http_up) { return false; } if (!r_config_get_i (core->config, "scr.interactive")) { return false; } if (input[1] == ' ') { char *n, *o, *p = strdup (input + 2); // TODO: slash split here? or inside sdb_ns ? for (n = o = p; n; o = n) { n = strchr (o, '/'); // SDB_NS_SEPARATOR NAMESPACE if (n) *n++ = 0; s = sdb_ns (s, o, 1); } free (p); } if (!s) s = core->sdb; for (;;) { r_line_set_prompt (p); if (r_cons_fgets (buf, buflen, 0, NULL) < 1) break; if (!*buf) break; out = sdb_querys (s, NULL, 0, buf); if (out) { r_cons_println (out); } } break; case 'o': if (r_sandbox_enable (0)) { eprintf ("This command is disabled in sandbox mode\n"); return 0; } if (input[1] == ' ') { char *fn = strdup (input + 2); if (!fn) { eprintf("Unable to allocate memory\n"); return 0; } char *ns = strchr (fn, ' '); if (ns) { Sdb *db; *ns++ = 0; if (r_file_exists (fn)) { db = sdb_ns_path (core->sdb, ns, 1); if (db) { Sdb *newdb = sdb_new (NULL, fn, 0); if (newdb) { sdb_drain (db, newdb); } else { eprintf ("Cannot open sdb '%s'\n", fn); } } else eprintf ("Cannot find sdb '%s'\n", ns); } else eprintf ("Cannot open file\n"); } else eprintf ("Missing sdb namespace\n"); free (fn); } else { eprintf ("Usage: ko [file] [namespace]\n"); } break; case 'd': if (r_sandbox_enable (0)) { eprintf ("This command is disabled in sandbox mode\n"); return 0; } if (input[1] == ' ') { char *fn = strdup (input + 2); char *ns = strchr (fn, ' '); if (ns) { *ns++ = 0; Sdb *db = sdb_ns_path (core->sdb, ns, 0); if (db) { sdb_file (db, fn); sdb_sync (db); } else eprintf ("Cannot find sdb '%s'\n", ns); } else eprintf ("Missing sdb namespace\n"); free (fn); } else { eprintf ("Usage: kd [file] [namespace]\n"); } break; case '?': { const char* help_msg[] = { "Usage:", "k[s] [key[=value]]", "Sdb Query", "k", " foo=bar", "set value", "k", " foo", "show value", "k", "", "list keys", "ko", " [file.sdb] [ns]", "open file into namespace", "kd", " [file.sdb] [ns]", "dump namespace to disk", "ks", " [ns]", "enter the sdb query shell", "k", " anal/meta/*", "ist kv from anal > meta namespaces", "k", " anal/**", "list namespaces under anal", "k", " anal/meta/meta.0x80404", "get value for meta.0x80404 key", //"kl", " ha.sdb", "load keyvalue from ha.sdb", //"ks", " ha.sdb", "save keyvalue to ha.sdb", NULL, }; r_core_cmd_help (core, help_msg); } break; } if (input[0] == '\0') { /* nothing more to do, the command has been parsed. */ return 0; } sp = strchr (input + 1, ' '); if (sp) { char *inp = strdup (input); inp [(size_t)(sp - input)] = 0; s = sdb_ns (core->sdb, inp + 1, 1); out = sdb_querys (s, NULL, 0, sp + 1); if (out) { r_cons_println (out); free (out); } free (inp); return 0; } return 0; } static int cmd_bsize(void *data, const char *input) { ut64 n; RFlagItem *flag; RCore *core = (RCore *)data; switch (input[0]) { case 'm': n = r_num_math (core->num, input + 1); if (n > 1) core->blocksize_max = n; else r_cons_printf ("0x%x\n", (ut32)core->blocksize_max); break; case '+': n = r_num_math (core->num, input + 1); r_core_block_size (core, core->blocksize + n); break; case '-': n = r_num_math (core->num, input + 1); r_core_block_size (core, core->blocksize - n); break; case 'f': if (input[1] == ' ') { flag = r_flag_get (core->flags, input + 2); if (flag) { r_core_block_size (core, flag->size); } else { eprintf ("bf: cannot find flag named '%s'\n", input + 2); } } else { eprintf ("Usage: bf [flagname]\n"); } break; case '\0': r_cons_printf ("0x%x\n", core->blocksize); break; case '?':{ const char* help_msg[] = { "Usage:", "b[f] [arg]\n", "Get/Set block size", "b", "", "display current block size", "b", " 33", "set block size to 33", "b", "+3", "increase blocksize by 3", "b", "-16", "decrease blocksize by 16", "b", " eip+4", "numeric argument can be an expression", "bf", " foo", "set block size to flag size", "bm", " 1M", "set max block size", NULL }; r_core_cmd_help (core, help_msg); } break; default: //input = r_str_clean(input); r_core_block_size (core, r_num_math (core->num, input)); break; } return 0; } static int cmd_resize(void *data, const char *input) { RCore *core = (RCore *)data; ut64 oldsize, newsize = 0; st64 delta = 0; int grow, ret; if (core->file && core->file->desc) oldsize = r_io_desc_size (core->io, core->file->desc); else oldsize = 0; switch (*input) { case '2': // TODO: use argv[0] instead of 'radare2' r_sys_cmdf ("radare%s", input); return true; case 'm': if (input[1] == ' ') r_file_rm (input + 2); else eprintf ("Usage: rm [file] # removes a file\n"); return true; case '\0': if (core->file && core->file->desc) { if (oldsize != -1) { r_cons_printf ("%"PFMT64d"\n", oldsize); } } return true; case '+': case '-': delta = (st64)r_num_math (core->num, input); newsize = oldsize + delta; break; case ' ': newsize = r_num_math (core->num, input + 1); if (newsize == 0) { if (input[1] == '0') eprintf ("Invalid size\n"); return false; } break; default: case '?':{ const char* help_msg[] = { "Usage:", "r[+-][ size]", "Resize file", "r", "", "display file size", "r", " size", "expand or truncate file to given size", "r-", "num", "remove num bytes, move following data down", "r+", "num", "insert num bytes, move following data up", "rm" ," [file]", "remove file", "r2" ," [file]", "launch r2", NULL}; r_core_cmd_help (core, help_msg); } return true; } grow = (newsize > oldsize); if (grow) { ret = r_io_resize (core->io, newsize); if (ret < 1) eprintf ("r_io_resize: cannot resize\n"); } if (delta && core->offset < newsize) r_io_shift (core->io, core->offset, grow?newsize:oldsize, delta); if (!grow) { ret = r_io_resize (core->io, newsize); if (ret < 1) eprintf ("r_io_resize: cannot resize\n"); } if (newsize < core->offset+core->blocksize || oldsize < core->offset + core->blocksize) { r_core_block_read (core); } return true; } static int cmd_visual(void *data, const char *input) { RCore *core = (RCore*) data; if (core->http_up) { return false; } if (!r_config_get_i (core->config, "scr.interactive")) { return false; } return r_core_visual ((RCore *)data, input); } static int task_finished(void *user, void *data) { eprintf ("TASK FINISHED\n"); return 0; } static int taskbgrun(RThread *th) { char *res; RCoreTask *task = th->user; RCore *core = task->core; close (2); // no stderr res = r_core_cmd_str (core, task->msg->text); task->msg->res = res; task->state = 'd'; eprintf ("Task %d finished\n", task->id); // TODO: run callback and pass result return 0; } static int cmd_thread(void *data, const char *input) { RCore *core = (RCore*) data; if (r_sandbox_enable (0)) { eprintf ("This command is disabled in sandbox mode\n"); return 0; } switch (input[0]) { case '\0': case 'j': r_core_task_list (core, *input); break; case '&': if (input[1] == '&') { // wait until ^C } else { int tid = r_num_math (core->num, input + 1); if (tid) { RCoreTask *task = r_core_task_get (core, tid); if (task) { r_core_task_join (core, task); } else eprintf ("Cannot find task\n"); } else { r_core_task_run (core, NULL); } } break; case '=': { int tid = r_num_math (core->num, input + 1); if (tid) { RCoreTask *task = r_core_task_get (core, tid); if (task) { r_cons_printf ("Task %d Status %c Command %s\n", task->id, task->state, task->msg->text); if (task->msg->res) r_cons_println (task->msg->res); } else eprintf ("Cannot find task\n"); } else { r_core_task_list (core, 1); }} break; case '+': r_core_task_add (core, r_core_task_new (core, input + 1, (RCoreTaskCallback)task_finished, core)); break; case '-': if (input[1] == '*') { r_core_task_del (core, -1); } else { r_core_task_del (core, r_num_math (core->num, input + 1)); } break; case '?': { helpCmdTasks (core); } break; case ' ': { int tid = r_num_math (core->num, input + 1); if (tid) { RCoreTask *task = r_core_task_get (core, tid); if (task) { r_core_task_join (core, task); } else { eprintf ("Cannot find task\n"); } } else { RCoreTask *task = r_core_task_add (core, r_core_task_new ( core, input + 1, (RCoreTaskCallback)task_finished, core)); RThread *th = r_th_new (taskbgrun, task, 0); task->msg->th = th; } //r_core_cmd0 (core, task->msg->text); //r_core_task_del (core, task->id); } break; default: eprintf ("&?\n"); break; } return 0; } static int cmd_pointer(void *data, const char *input) { RCore *core = (RCore*) data; int ret = true; char *str, *eq; while (*input == ' ') input++; if (!*input || *input == '?') { const char* help_msg[] = { "Usage:", "*<addr>[=[0x]value]", "Pointer read/write data/values", "*", "entry0=cc", "write trap in entrypoint", "*", "entry0+10=0x804800", "write value in delta address", "*", "entry0", "read byte at given address", "TODO: last command should honor asm.bits", "", "", NULL}; r_core_cmd_help (core, help_msg); return ret; } str = strdup (input); eq = strchr (str, '='); if (eq) { *eq++ = 0; if (!strncmp (eq, "0x", 2)) { ret = r_core_cmdf (core, "wv %s@%s", eq, str); } else { ret = r_core_cmdf (core, "wx %s@%s", eq, str); } } else { ret = r_core_cmdf (core, "?v [%s]", input); } free (str); return ret; } static int cmd_env(void *data, const char *input) { RCore *core = (RCore*)data; int ret = true; switch (*input) { case '?': { const char* help_msg[] = { "Usage:", "%[name[=value]]", "Set each NAME to VALUE in the environment", "%", "", "list all environment variables", "%", "SHELL", "prints SHELL value", "%", "TMPDIR=/tmp", "sets TMPDIR value to \"/tmp\"", NULL}; r_core_cmd_help (core, help_msg); } break; default: ret = r_core_cmdf (core, "env %s", input); } return ret; } static int cmd_system(void *data, const char *input) { RCore *core = (RCore*)data; ut64 n; int ret = 0; switch (*input) { case '=': if (input[1] == '?') { r_cons_printf ("Usage: !=[!] - enable/disable remote commands\n"); } else { if (!r_sandbox_enable (0)) { core->cmdremote = input[1]? 1: 0; r_cons_println (r_str_bool (core->cmdremote)); } } break; case '!': if (r_sandbox_enable (0)) { eprintf ("This command is disabled in sandbox mode\n"); return 0; } if (input[1]) { int olen; char *out = NULL; char *cmd = r_core_sysenv_begin (core, input); if (cmd) { ret = r_sys_cmd_str_full (cmd + 1, NULL, &out, &olen, NULL); r_core_sysenv_end (core, input); r_cons_memcat (out, olen); free (out); free (cmd); } //else eprintf ("Error setting up system environment\n"); } else { eprintf ("History saved to "R2_HOMEDIR"/history\n"); r_line_hist_save (R2_HOMEDIR"/history"); } break; case '\0': r_line_hist_list (); break; case '?': r_core_sysenv_help (core); break; default: n = atoi (input); if (*input == '0' || n > 0) { const char *cmd = r_line_hist_get (n); if (cmd) r_core_cmd0 (core, cmd); //else eprintf ("Error setting up system environment\n"); } else { char *cmd = r_core_sysenv_begin (core, input); if (cmd) { ret = r_sys_cmd (cmd); r_core_sysenv_end (core, input); free (cmd); } else eprintf ("Error setting up system environment\n"); } break; } return ret; } R_API int r_core_cmd_pipe(RCore *core, char *radare_cmd, char *shell_cmd) { #if __UNIX__ || __CYGWIN__ int stdout_fd, fds[2]; int child; #endif int si, olen, ret = -1, pipecolor = -1; char *str, *out = NULL; if (r_sandbox_enable (0)) { eprintf ("Pipes are not allowed in sandbox mode\n"); return -1; } si = r_config_get_i (core->config, "scr.interactive"); r_config_set_i (core->config, "scr.interactive", 0); if (!r_config_get_i (core->config, "scr.pipecolor")) { pipecolor = r_config_get_i (core->config, "scr.color"); r_config_set_i (core->config, "scr.color", 0); } if (*shell_cmd=='!') { r_cons_grep_parsecmd (shell_cmd, "\""); olen = 0; out = NULL; // TODO: implement foo str = r_core_cmd_str (core, radare_cmd); r_sys_cmd_str_full (shell_cmd + 1, str, &out, &olen, NULL); free (str); r_cons_memcat (out, olen); free (out); ret = 0; } #if __UNIX__ || __CYGWIN__ radare_cmd = (char*)r_str_trim_head (radare_cmd); shell_cmd = (char*)r_str_trim_head (shell_cmd); signal (SIGPIPE, SIG_IGN); stdout_fd = dup (1); if (stdout_fd != -1) { pipe (fds); child = r_sys_fork (); if (child == -1) { eprintf ("Cannot fork\n"); close (stdout_fd); } else if (child) { dup2 (fds[1], 1); close (fds[1]); close (fds[0]); r_core_cmd (core, radare_cmd, 0); r_cons_flush (); close (1); wait (&ret); dup2 (stdout_fd, 1); close (stdout_fd); } else { close (fds[1]); dup2 (fds[0], 0); //dup2 (1, 2); // stderr goes to stdout r_sandbox_system (shell_cmd, 0); close (stdout_fd); } } #else #ifdef _MSC_VER #pragma message ("r_core_cmd_pipe UNIMPLEMENTED FOR THIS PLATFORM") #else #warning r_core_cmd_pipe UNIMPLEMENTED FOR THIS PLATFORM #endif eprintf ("r_core_cmd_pipe: unimplemented for this platform\n"); #endif if (pipecolor != -1) r_config_set_i (core->config, "scr.color", pipecolor); r_config_set_i (core->config, "scr.interactive", si); return ret; } static char *parse_tmp_evals(RCore *core, const char *str) { char *res = NULL; RStrBuf *buf; char *s = strdup (str); buf = r_strbuf_new (""); int i, argc = r_str_split (s, ','); for (i = 0; i < argc; i++) { char *eq, *kv = (char *)r_str_word_get0 (s, i); if (!kv) { break; } eq = strchr (kv, '='); if (eq) { *eq = 0; const char *ov = r_config_get (core->config, kv); r_strbuf_appendf (buf, "e %s=%s;", kv, ov); r_config_set (core->config, kv, eq + 1); *eq = '='; } else { eprintf ("Missing '=' in e: expression (%s)\n", kv); } } res = r_strbuf_drain (buf); free (s); return res; } static int r_core_cmd_subst_i(RCore *core, char *cmd, char* colon); static int r_core_cmd_subst(RCore *core, char *cmd) { int ret = 0, rep = atoi (cmd), orep; char *cmt, *colon = NULL, *icmd = strdup (cmd); const char *cmdrep = NULL; cmd = r_str_trim_head_tail (icmd); // lines starting with # are ignored (never reach cmd_hash()), except #! and #? if (!icmd || (cmd[0] == '#' && cmd[1] != '!' && cmd[1] != '?')) { goto beach; } cmt = *icmd ? strchr (icmd + 1, '#'): NULL; if (cmt && (cmt[1] == ' ' || cmt[1] == '\t')) { *cmt = 0; } if (*cmd != '"') { if (!strchr (cmd, '\'')) { // allow | awk '{foo;bar}' // ignore ; if there's a single quote if ((colon = strchr (cmd, ';'))) { *colon = 0; } } } else { colon = NULL; } if (rep > 0) { while (IS_DIGIT(*cmd)) { cmd++; } // do not repeat null cmd if (!*cmd) { goto beach; } } if (rep < 1) { rep = 1; } // XXX if output is a pipe then we dont want to be interactive if (rep > 1 && r_sandbox_enable (0)) { eprintf ("Command repeat sugar disabled in sandbox mode (%s)\n", cmd); goto beach; } else { if (rep > INTERACTIVE_MAX_REP) { if (r_config_get_i (core->config, "scr.interactive")) { if (!r_cons_yesno ('n', "Are you sure to repeat this %d times? (y/N)", rep)) { goto beach; } } } } // TODO: store in core->cmdtimes to speedup ? cmdrep = r_config_get (core->config, "cmd.times"); if (!cmdrep) { cmdrep = ""; } orep = rep; int ocur_enabled = core->print->cur_enabled; while (rep-- && *cmd) { core->print->cur_enabled = false; if (ocur_enabled && core->seltab >= 0) { if (core->seltab == core->curtab) { core->print->cur_enabled = true; } } char *cr = strdup (cmdrep); core->break_loop = false; ret = r_core_cmd_subst_i (core, cmd, colon); if (ret && *cmd == 'q') { free (cr); goto beach; } if (core->break_loop) { break; } if (cr && *cr) { if (orep > 1) { // XXX: do not flush here, we need r_cons_push () and r_cons_pop() r_cons_flush (); // XXX: we must import register flags in C (void)r_core_cmd0 (core, ".dr*"); (void)r_core_cmd0 (core, cr); } } free (cr); } core->print->cur_enabled = ocur_enabled; if (colon && colon[1]) { for (++colon; *colon == ';'; colon++); r_core_cmd_subst (core, colon); } else { if (!*icmd) { r_core_cmd_nullcallback (core); } } beach: free (icmd); return ret; } static char *find_eoq(char *p) { for (; *p; p++) { if (*p == '"') { break; } if (*p == '\\' && p[1] == '"') { p++; } } return p; } static char* findSeparator(char *p) { char *q = strchr (p, '+'); if (q) { return q; } return strchr (p, '-'); } static int r_core_cmd_subst_i(RCore *core, char *cmd, char *colon) { const char *quotestr = "`"; const char *tick = NULL; char *ptr, *ptr2, *str; char *arroba = NULL; int i, ret = 0, pipefd; bool usemyblock = false; int scr_html = -1; int scr_color = -1; bool eos = false; bool haveQuote = false; if (!cmd) { return 0; } cmd = r_str_trim_head_tail (cmd); /* quoted / raw command */ switch (*cmd) { case '.': if (cmd[1] == '"') { /* interpret */ return r_cmd_call (core->rcmd, cmd); } break; case '"': for (; *cmd; ) { int pipefd = -1; ut64 oseek = UT64_MAX; char *line, *p; haveQuote = *cmd == '"'; if (haveQuote) { // *cmd = 0; cmd++; p = cmd[0] ? find_eoq (cmd + 1) : NULL; if (!p || !*p) { eprintf ("Missing \" in (%s).", cmd); return false; } *p++ = 0; if (!*p) { eos = true; } } else { char *sc = strchr (cmd, ';'); if (sc) { *sc = 0; } r_core_cmd0 (core, cmd); if (!sc) { break; } cmd = sc + 1; continue; } if (p[0]) { // workaround :D if (p[0] == '@') { p--; } while (p[1] == ';' || IS_WHITESPACE (p[1])) { p++; } if (p[1] == '@' || (p[1] && p[2] == '@')) { char *q = strchr (p + 1, '"'); if (q) { *q = 0; } haveQuote = q != NULL; oseek = core->offset; r_core_seek (core, r_num_math (core->num, p + 2), 1); if (q) { *p = '"'; p = q; } else { p = strchr (p + 1, ';'); } } if (p && *p && p[1] == '>') { str = p + 2; while (*str == '>') { str++; } while (IS_WHITESPACE (*str)) { str++; } r_cons_flush (); pipefd = r_cons_pipe_open (str, 1, p[2] == '>'); } } line = strdup (cmd); line = r_str_replace (line, "\\\"", "\"", true); if (p && *p && p[1] == '|') { str = p + 2; while (IS_WHITESPACE (*str)) { str++; } r_core_cmd_pipe (core, cmd, str); } else { r_cmd_call (core->rcmd, line); } free (line); if (oseek != UT64_MAX) { r_core_seek (core, oseek, 1); oseek = UT64_MAX; } if (pipefd != -1) { r_cons_flush (); r_cons_pipe_close (pipefd); } if (!p) { break; } if (eos) { break; } if (haveQuote) { if (*p == ';') { cmd = p + 1; } else { if (*p == '"') { cmd = p + 1; } else { *p = '"'; cmd = p; } } } else { cmd = p + 1; } } return true; case '(': if (cmd[1] != '*') { return r_cmd_call (core->rcmd, cmd); } } // TODO must honor " and ` /* comments */ if (*cmd != '#') { ptr = (char *)r_str_lastbut (cmd, '#', quotestr); if (ptr && (ptr[1] == ' ' || ptr[1] == '\t')) { *ptr = '\0'; } } /* multiple commands */ // TODO: must honor " and ` boundaries //ptr = strrchr (cmd, ';'); if (*cmd != '#') { ptr = (char *)r_str_lastbut (cmd, ';', quotestr); if (colon && ptr) { int ret ; *ptr = '\0'; if (r_core_cmd_subst (core, cmd) == -1) { return -1; } cmd = ptr + 1; ret = r_core_cmd_subst (core, cmd); *ptr = ';'; return ret; //r_cons_flush (); } } // TODO must honor " and ` /* pipe console to shell process */ //ptr = strchr (cmd, '|'); ptr = (char *)r_str_lastbut (cmd, '|', quotestr); if (ptr) { char *ptr2 = strchr (cmd, '`'); if (!ptr2 || (ptr2 && ptr2 > ptr)) { if (!tick || (tick && tick > ptr)) { *ptr = '\0'; cmd = r_str_clean (cmd); if (!strcmp (ptr + 1, "?")) { // "|?" // TODO: should be disable scr.color in pd| ? eprintf ("Usage: <r2command> | <program|H|>\n"); eprintf (" pd|? - show this help\n"); eprintf (" pd| - disable scr.html and scr.color\n"); eprintf (" pd|H - enable scr.html, respect scr.color\n"); return ret; } else if (!strcmp (ptr + 1, "H")) { // "|H" scr_html = r_config_get_i (core->config, "scr.html"); r_config_set_i (core->config, "scr.html", true); } else if (ptr[1]) { // "| grep .." int value = core->num->value; if (*cmd) { r_core_cmd_pipe (core, cmd, ptr + 1); } else { r_io_system (core->io, ptr + 1); } core->num->value = value; return 0; } else { // "|" scr_html = r_config_get_i (core->config, "scr.html"); r_config_set_i (core->config, "scr.html", 0); scr_color = r_config_get_i (core->config, "scr.color"); r_config_set_i (core->config, "scr.color", false); } } } } // TODO must honor " and ` /* bool conditions */ ptr = (char *)r_str_lastbut (cmd, '&', quotestr); //ptr = strchr (cmd, '&'); while (ptr && ptr[1] == '&') { *ptr = '\0'; ret = r_cmd_call (core->rcmd, cmd); if (ret == -1) { eprintf ("command error(%s)\n", cmd); if (scr_html != -1) { r_config_set_i (core->config, "scr.html", scr_html); } if (scr_color != -1) { r_config_set_i (core->config, "scr.color", scr_color); } return ret; } for (cmd = ptr + 2; cmd && *cmd == ' '; cmd++); ptr = strchr (cmd, '&'); } /* Out Of Band Input */ free (core->oobi); core->oobi = NULL; ptr = strstr (cmd, "?*"); if (ptr) { char *prech = ptr - 1; if (*prech != '~') { ptr[1] = 0; if (*cmd != '#' && strlen (cmd) < 5) { r_cons_break_push (NULL, NULL); recursive_help (core, cmd); r_cons_break_pop (); r_cons_grep_parsecmd (ptr + 2, "`"); if (scr_html != -1) { r_config_set_i (core->config, "scr.html", scr_html); } if (scr_color != -1) { r_config_set_i (core->config, "scr.color", scr_color); } return 0; } } } #if 0 ptr = strchr (cmd, '<'); if (ptr) { ptr[0] = '\0'; if (r_cons_singleton()->is_interactive) { if (ptr[1] == '<') { /* this is a bit mess */ //const char *oprompt = strdup (r_line_singleton ()->prompt); //oprompt = ">"; for (str = ptr + 2; str[0] == ' '; str++) { //nothing to see here } eprintf ("==> Reading from stdin until '%s'\n", str); free (core->oobi); core->oobi = malloc (1); if (core->oobi) { core->oobi[0] = '\0'; } core->oobi_len = 0; for (;;) { char buf[1024]; int ret; write (1, "> ", 2); fgets (buf, sizeof (buf) - 1, stdin); // XXX use r_line ?? if (feof (stdin)) { break; } if (*buf) buf[strlen (buf) - 1]='\0'; ret = strlen (buf); core->oobi_len += ret; core->oobi = realloc (core->oobi, core->oobi_len + 1); if (core->oobi) { if (!strcmp (buf, str)) { break; } strcat ((char *)core->oobi, buf); } } //r_line_set_prompt (oprompt); } else { for (str = ptr + 1; *str == ' '; str++) { //nothing to see here } if (!*str) { goto next; } eprintf ("Slurping file '%s'\n", str); free (core->oobi); core->oobi = (ut8*)r_file_slurp (str, &core->oobi_len); if (!core->oobi) { eprintf ("cannot open file\n"); } else if (ptr == cmd) { return r_core_cmd_buffer (core, (const char *)core->oobi); } } } else { eprintf ("Cannot slurp with << in non-interactive mode\n"); return 0; } } next: #endif // TODO must honor " and ` /* pipe console to file */ ptr = strchr (cmd, '>'); if (ptr) { int fdn = 1; int pipecolor = r_config_get_i (core->config, "scr.pipecolor"); int use_editor = false; int ocolor = r_config_get_i (core->config, "scr.color"); *ptr = '\0'; str = r_str_trim_head_tail (ptr + 1 + (ptr[1] == '>')); if (!*str) { eprintf ("No output?\n"); goto next2; } /* r_cons_flush() handles interactive output (to the terminal) * differently (e.g. asking about too long output). This conflicts * with piping to a file. Disable it while piping. */ if (ptr > (cmd + 1) && ISWHITECHAR (ptr[-2])) { char *fdnum = ptr - 1; if (*fdnum == 'H') { // "H>" scr_html = r_config_get_i (core->config, "scr.html"); r_config_set_i (core->config, "scr.html", true); pipecolor = true; *fdnum = 0; } else { if (IS_DIGIT(*fdnum)) { fdn = *fdnum - '0'; } *fdnum = 0; } } r_cons_set_interactive (false); if (!strcmp (str, "-")) { use_editor = true; str = r_file_temp ("dumpedit"); r_config_set (core->config, "scr.color", "false"); } if (fdn > 0) { pipefd = r_cons_pipe_open (str, fdn, ptr[1] == '>'); if (pipefd != -1) { if (!pipecolor) { r_config_set_i (core->config, "scr.color", 0); } ret = r_core_cmd_subst (core, cmd); r_cons_flush (); r_cons_pipe_close (pipefd); } } r_cons_set_last_interactive (); if (!pipecolor) { r_config_set_i (core->config, "scr.color", ocolor); } if (use_editor) { const char *editor = r_config_get (core->config, "cfg.editor"); if (editor && *editor) { r_sys_cmdf ("%s '%s'", editor, str); r_file_rm (str); } else { eprintf ("No cfg.editor configured\n"); } r_config_set_i (core->config, "scr.color", ocolor); free (str); } if (scr_html != -1) { r_config_set_i (core->config, "scr.html", scr_html); } if (scr_color != -1) { r_config_set_i (core->config, "scr.color", scr_color); } return ret; } next2: /* sub commands */ ptr = strchr (cmd, '`'); if (ptr) { int empty = 0; int oneline = 1; if (ptr[1] == '`') { memmove (ptr, ptr + 1, strlen (ptr)); oneline = 0; empty = 1; } ptr2 = strchr (ptr + 1, '`'); if (empty) { /* do nothing */ } else if (!ptr2) { eprintf ("parse: Missing backtick in expression.\n"); goto fail; } else { int value = core->num->value; *ptr = '\0'; *ptr2 = '\0'; if (ptr[1] == '!') { str = r_core_cmd_str_pipe (core, ptr + 1); } else { str = r_core_cmd_str (core, ptr + 1); } if (!str) { goto fail; } // ignore contents if first char is pipe or comment if (*str == '|' || *str == '*') { eprintf ("r_core_cmd_subst_i: invalid backticked command\n"); free (str); goto fail; } if (oneline && str) { for (i = 0; str[i]; i++) { if (str[i] == '\n') { str[i] = ' '; } } } str = r_str_append (str, ptr2 + 1); cmd = r_str_append (strdup (cmd), str); core->num->value = value; ret = r_core_cmd_subst (core, cmd); free (cmd); if (scr_html != -1) { r_config_set_i (core->config, "scr.html", scr_html); } free (str); return ret; } } // TODO must honor " and ` core->fixedblock = false; if (r_str_endswith (cmd, "~?") && cmd[2] == '\0') { r_cons_grep_help (); return true; } if (*cmd != '.') { r_cons_grep_parsecmd (cmd, quotestr); } /* temporary seek commands */ if (*cmd!= '(' && *cmd != '"') { ptr = strchr (cmd, '@'); if (ptr == cmd + 1 && *cmd == '?') { ptr = NULL; } } else { ptr = NULL; } core->tmpseek = ptr? true: false; int rc = 0; if (ptr) { char *f, *ptr2 = strchr (ptr + 1, '!'); ut64 addr = UT64_MAX; const char *tmpbits = NULL; const char *offstr = NULL; ut64 tmpbsz = core->blocksize; char *tmpeval = NULL; ut64 tmpoff = core->offset; char *tmpasm = NULL; int tmpfd = -1; int sz, len; ut8 *buf; *ptr = '\0'; for (ptr++; *ptr == ' '; ptr++) { //nothing to see here } if (*ptr && ptr[1] == ':') { /* do nothing here */ } else { ptr--; } arroba = (ptr[0] && ptr[1] && ptr[2])? strchr (ptr + 2, '@'): NULL; repeat_arroba: if (arroba) { *arroba = 0; } if (ptr[1] == '?') { helpCmdAt (core); } else if (ptr[0] && ptr[1] == ':' && ptr[2]) { usemyblock = true; switch (ptr[0]) { case 'f': // "@f:" // slurp file in block f = r_file_slurp (ptr + 2, &sz); if (f) { buf = malloc (sz); if (buf) { free (core->block); core->block = buf; core->blocksize = sz; memcpy (core->block, f, sz); } else { eprintf ("cannot alloc %d", sz); } free (f); } else { eprintf ("cannot open '%s'\n", ptr + 3); } break; case 'r': // "@r:" // regname if (ptr[1] == ':') { ut64 regval; char *mander = strdup (ptr + 2); char *sep = findSeparator (mander); if (sep) { char ch = *sep; *sep = 0; regval = r_debug_reg_get (core->dbg, mander); *sep = ch; char *numexpr = r_str_newf ("0x%"PFMT64x"%s", regval, sep); regval = r_num_math (core->num, numexpr); free (numexpr); } else { regval = r_debug_reg_get (core->dbg, ptr + 2); } r_core_seek (core, regval, 1); free (mander); } break; case 'b': // "@b:" // bits tmpbits = strdup (r_config_get (core->config, "asm.bits")); r_config_set_i (core->config, "asm.bits", r_num_math (core->num, ptr + 2)); break; case 'i': // "@i:" { ut64 addr = r_num_math (core->num, ptr + 2); if (addr) { r_core_cmdf (core, "so %s", ptr + 2); } } break; case 'e': // "@e:" tmpeval = parse_tmp_evals (core, ptr + 2); break; case 'x': // "@x:" // hexpairs if (ptr[1] == ':') { buf = malloc (strlen (ptr + 2) + 1); if (buf) { len = r_hex_str2bin (ptr + 2, buf); r_core_block_size (core, R_ABS(len)); memcpy (core->block, buf, core->blocksize); core->fixedblock = true; free (buf); } else { eprintf ("cannot allocate\n"); } } else { eprintf ("Invalid @x: syntax\n"); } break; case 'k': // "@k" { char *out = sdb_querys (core->sdb, NULL, 0, ptr + ((ptr[1])? 2: 1)); if (out) { r_core_seek (core, r_num_math (core->num, out), 1); free (out); } } break; case 'o': // "@o:3" if (ptr[1] == ':') { tmpfd = core->io->raised; r_io_raise (core->io, atoi (ptr + 2)); } break; case 'a': // "@a:" if (ptr[1] == ':') { char *q = strchr (ptr + 2, ':'); tmpasm = strdup (r_config_get (core->config, "asm.arch")); if (q) { *q++ = 0; tmpbits = r_config_get (core->config, "asm.bits"); r_config_set (core->config, "asm.bits", q); } r_config_set (core->config, "asm.arch", ptr + 2); // TODO: handle asm.bits } else { eprintf ("Usage: pd 10 @a:arm:32\n"); } break; case 's': // "@s:" len = strlen (ptr + 2); r_core_block_size (core, len); memcpy (core->block, ptr + 2, len); break; default: goto ignore; } *ptr = '@'; goto next_arroba; //ignore; //return ret; } ignore: ptr = r_str_trim_head (ptr + 1); ptr--; cmd = r_str_clean (cmd); if (ptr2) { if (strlen (ptr + 1) == 13 && strlen (ptr2 + 1) == 6 && !memcmp (ptr + 1, "0x", 2) && !memcmp (ptr2 + 1, "0x", 2)) { /* 0xXXXX:0xYYYY */ } else if (strlen (ptr + 1) == 9 && strlen (ptr2 + 1) == 4) { /* XXXX:YYYY */ } else { *ptr2 = '\0'; if (!ptr2[1]) { goto fail; } r_core_block_size ( core, r_num_math (core->num, ptr2 + 1)); } } offstr = r_str_trim_head (ptr + 1); addr = r_num_math (core->num, offstr); if (isalpha ((unsigned char)ptr[1]) && !addr) { if (!r_flag_get (core->flags, ptr + 1)) { eprintf ("Invalid address (%s)\n", ptr + 1); goto fail; } } else { char ch = *offstr; if (ch == '-' || ch == '+') { addr = core->offset + addr; } } next_arroba: if (arroba) { ptr = arroba; arroba = NULL; goto repeat_arroba; } if (ptr[1] == '@') { // TODO: remove temporally seek (should be done by cmd_foreach) if (ptr[2] == '@') { char *rule = ptr + 3; while (*rule && *rule == ' ') rule++; ret = r_core_cmd_foreach3 (core, cmd, rule); } else { ret = r_core_cmd_foreach (core, cmd, ptr + 2); } //ret = -1; /* do not run out-of-foreach cmd */ } else { bool tmpseek = false; const char *fromvars[] = { "anal.from", "diff.from", "graph.from", "io.buffer.from", "lines.from", "search.from", "zoom.from", NULL }; const char *tovars[] = { "anal.to", "diff.to", "graph.to", "io.buffer.to", "lines.to", "search.to", "zoom.to", NULL }; ut64 curfrom[R_ARRAY_SIZE (fromvars) - 1], curto[R_ARRAY_SIZE (tovars) - 1]; // @.. if (ptr[1] == '.' && ptr[2] == '.') { char *range = ptr + 3; char *p = strchr (range, ' '); if (!p) { eprintf ("Usage: / ABCD @..0x1000 0x3000\n"); free (tmpeval); free (tmpasm); goto fail; } *p = '\x00'; ut64 from = r_num_math (core->num, range); ut64 to = r_num_math (core->num, p + 1); // save current ranges for (i = 0; fromvars[i]; i++) { curfrom[i] = r_config_get_i (core->config, fromvars[i]); } for (i = 0; tovars[i]; i++) { curto[i] = r_config_get_i (core->config, tovars[i]); } // set new ranges for (i = 0; fromvars[i]; i++) { r_config_set_i (core->config, fromvars[i], from); } for (i = 0; tovars[i]; i++) { r_config_set_i (core->config, tovars[i], to); } tmpseek = true; } if (usemyblock) { if (addr != UT64_MAX) { core->offset = addr; } ret = r_cmd_call (core->rcmd, r_str_trim_head (cmd)); } else { if (addr != UT64_MAX) { if (!ptr[1] || r_core_seek (core, addr, 1)) { r_core_block_read (core); ret = r_cmd_call (core->rcmd, r_str_trim_head (cmd)); } else { ret = 0; } } } if (tmpseek) { // restore ranges for (i = 0; fromvars[i]; i++) { r_config_set_i (core->config, fromvars[i], curfrom[i]); } for (i = 0; tovars[i]; i++) { r_config_set_i (core->config, tovars[i], curto[i]); } } } if (ptr2) { *ptr2 = '!'; r_core_block_size (core, tmpbsz); } if (tmpasm) { r_config_set (core->config, "asm.arch", tmpasm); tmpasm = NULL; } if (tmpfd != -1) { r_io_raise (core->io, tmpfd); } if (tmpbits) { r_config_set (core->config, "asm.bits", tmpbits); tmpbits = NULL; } if (tmpeval) { r_core_cmd0 (core, tmpeval); R_FREE (tmpeval); } r_core_seek (core, tmpoff, 1); *ptr = '@'; rc = ret; goto beach; } rc = cmd? r_cmd_call (core->rcmd, r_str_trim_head (cmd)): false; beach: if (scr_html != -1) { r_cons_flush (); r_config_set_i (core->config, "scr.html", scr_html); } if (scr_color != -1) { r_config_set_i (core->config, "scr.color", scr_color); } core->fixedblock = false; return rc; fail: rc = -1; goto beach; } static int foreach_comment(void *user, const char *k, const char *v) { RAnalMetaUserItem *ui = user; RCore *core = ui->anal->user; const char *cmd = ui->user; if (!strncmp (k, "meta.C.", 7)) { char *cmt = (char *)sdb_decode (v, 0); if (!cmt) cmt = strdup (""); //eprintf ("--> %s = %s\n", k + 7, cmt); r_core_cmdf (core, "s %s", k + 7); r_core_cmd0 (core, cmd); free (cmt); } return 1; } R_API int r_core_cmd_foreach3(RCore *core, const char *cmd, char *each) { RDebug *dbg = core->dbg; RList *list, *head; RListIter *iter; RFlagItem *flg; int i; switch (each[0]) { case '=': { char *arg; for (arg = each + 1; ; ) { char *next = strchr (arg, ' '); if (next) { *next = 0; } if (arg && *arg) { r_core_cmdf (core, "%s %s", cmd, arg); } if (!next) { break; } arg = next + 1; } } break; case '?': r_cons_printf ("Usage: @@@ [type] # types:\n" " symbols\n" " imports\n" " regs\n" " threads\n" " comments\n" " functions\n" " flags\n"); break; case 'c': switch (each[1]) { case 'a': // call break; default: r_meta_list_cb (core->anal, R_META_TYPE_COMMENT, 0, foreach_comment, (void*)cmd, UT64_MAX); break; } break; case 't': // iterate over all threads if (dbg && dbg->h && dbg->h->threads) { int origpid = dbg->pid; RDebugPid *p; list = dbg->h->threads (dbg, dbg->pid); if (!list) return false; r_list_foreach (list, iter, p) { r_core_cmdf (core, "dp %d", p->pid); r_cons_printf ("PID %d\n", p->pid); r_core_cmd0 (core, cmd); } r_core_cmdf (core, "dp %d", origpid); r_list_free (list); } break; case 'r': // registers { ut64 offorig = core->offset; for (i = 0; i < 128; i++) { RRegItem *item; ut64 value; head = r_reg_get_list (dbg->reg, i); if (!head) { continue; } r_list_foreach (head, iter, item) { if (item->size != core->anal->bits) { continue; } value = r_reg_get_value (dbg->reg, item); r_core_seek (core, value, 1); r_cons_printf ("%s: ", item->name); r_core_cmd0 (core, cmd); } } r_core_seek (core, offorig, 1); } break; case 'i': // imports { RBinImport *imp; ut64 offorig = core->offset; list = r_bin_get_imports (core->bin); r_list_foreach (list, iter, imp) { char *impflag = r_str_newf ("sym.imp.%s", imp->name); ut64 addr = r_num_math (core->num, impflag); if (addr && addr != UT64_MAX) { r_core_seek (core, addr, 1); r_core_cmd0 (core, cmd); } } r_core_seek (core, offorig, 1); } break; case 's': // symbols { RBinSymbol *sym; ut64 offorig = core->offset; list = r_bin_get_symbols (core->bin); r_list_foreach (list, iter, sym) { r_core_seek (core, sym->vaddr, 1); r_core_cmd0 (core, cmd); } r_core_seek (core, offorig, 1); } break; case 'f': switch (each[1]) { case 'l': // flags r_list_foreach (core->flags->flags, iter, flg) { r_core_seek (core, flg->offset, 1); r_core_cmd0 (core, cmd); } break; case 'u': // functions { ut64 offorig = core->offset; RAnalFunction *fcn; list = core->anal->fcns; r_list_foreach (list, iter, fcn) { r_cons_printf ("[0x%08"PFMT64x" %s\n", fcn->addr, fcn->name); r_core_seek (core, fcn->addr, 1); r_core_cmd0 (core, cmd); } r_core_seek (core, offorig, 1); } break; } break; } return 0; } static void foreachOffset (RCore *core, const char *_cmd, const char *each) { char *cmd = strdup (_cmd); char *str = cmd; char *nextLine = NULL; ut64 addr; /* foreach list of items */ while (each) { // skip spaces while (*each == ' ') { each++; } // stahp if empty string if (!*each) { break; } // find newline char *nl = strchr (each, '\n'); if (nl) { *nl = 0; nextLine = nl + 1; } else { nextLine = NULL; } // chop comment in line nl = strchr (each, '#'); if (nl) { *nl = 0; } // space separated numbers while (each && *each) { // find spaces while (*each== ' ') each++; str = strchr (each, ' '); if (str) { *str = '\0'; addr = r_num_math (core->num, each); *str = ' '; each = str + 1; } else { if (!*each) { break; } addr = r_num_math (core->num, each); each = NULL; } r_core_seek (core, addr, 1); r_core_cmd (core, cmd, 0); r_cons_flush (); } each = nextLine; } free (cmd); } R_API int r_core_cmd_foreach(RCore *core, const char *cmd, char *each) { int i, j; char ch; char *word = NULL; char *str, *ostr; RListIter *iter; RFlagItem *flag; ut64 oseek, addr; // for (; *each == ' '; each++); for (; *cmd == ' '; cmd++); oseek = core->offset; ostr = str = strdup (each); r_cons_break_push (NULL, NULL); //pop on return switch (each[0]) { case '/': // "@@/" { char *cmdhit = strdup (r_config_get (core->config, "cmd.hit")); r_config_set (core->config, "cmd.hit", cmd); r_core_cmd0 (core, each); r_config_set (core->config, "cmd.hit", cmdhit); free (cmdhit); } return 0; case '?': helpCmdForeach (core); break; case 'b': // "@@b" - function basic blocks { RListIter *iter; RAnalBlock *bb; RAnalFunction *fcn = r_anal_get_fcn_at (core->anal, core->offset, 0); int bs = core->blocksize; if (fcn) { r_list_sort (fcn->bbs, bb_cmp); r_list_foreach (fcn->bbs, iter, bb) { r_core_block_size (core, bb->size); r_core_seek (core, bb->addr, 1); r_core_cmd (core, cmd, 0); if (r_cons_is_breaked ()) { break; } } } free (ostr); r_core_block_size (core, bs); goto out_finish; } break; case 'i': // "@@i" - function instructions { RListIter *iter; RAnalBlock *bb; int i; RAnalFunction *fcn = r_anal_get_fcn_at (core->anal, core->offset, 0); if (fcn) { r_list_sort (fcn->bbs, bb_cmp); r_list_foreach (fcn->bbs, iter, bb) { for (i = 0; i < bb->op_pos_size; i++) { ut64 addr = bb->addr + bb->op_pos[i]; r_core_seek (core, addr, 1); r_core_cmd (core, cmd, 0); if (r_cons_is_breaked ()) { break; } } } } free (ostr); goto out_finish; } break; case 'f': // "@@f" if (each[1] == ':') { RAnalFunction *fcn; RListIter *iter; if (core->anal) { r_list_foreach (core->anal->fcns, iter, fcn) { if (each[2] && strstr (fcn->name, each + 2)) { r_core_seek (core, fcn->addr, 1); r_core_cmd (core, cmd, 0); if (r_cons_is_breaked ()) { break; } } } } free (ostr); goto out_finish; } else { RAnalFunction *fcn; RListIter *iter; if (core->anal) { RConsGrep grep = core->cons->grep; r_list_foreach (core->anal->fcns, iter, fcn) { char *buf; r_core_seek (core, fcn->addr, 1); r_cons_push (); r_core_cmd (core, cmd, 0); buf = (char *)r_cons_get_buffer (); if (buf) { buf = strdup (buf); } r_cons_pop (); r_cons_strcat (buf); free (buf); if (r_cons_is_breaked ()) { break; } } core->cons->grep = grep; } free (ostr); goto out_finish; } break; case 't': { RDebugPid *p; int pid = core->dbg->pid; if (core->dbg->h && core->dbg->h->pids) { RList *list = core->dbg->h->pids (core->dbg, R_MAX (0, pid)); r_list_foreach (list, iter, p) { r_cons_printf ("# PID %d\n", p->pid); r_debug_select (core->dbg, p->pid, p->pid); r_core_cmd (core, cmd, 0); r_cons_newline (); } r_list_free (list); } r_debug_select (core->dbg, pid, pid); free (ostr); goto out_finish; } break; case 'c': // "@@c:" if (each[1] == ':') { char *arg = r_core_cmd_str (core, each + 2); if (arg) { foreachOffset (core, cmd, arg); } } break; case '=': foreachOffset (core, cmd, str + 1); break; case 'd': if (each[1] == 'b' && each[2] == 't') { ut64 oseek = core->offset; RDebugFrame *frame; RListIter *iter; RList *list; list = r_debug_frames (core->dbg, UT64_MAX); i = 0; r_list_foreach (list, iter, frame) { switch (each[3]) { case 'b': r_core_seek (core, frame->bp, 1); break; case 's': r_core_seek (core, frame->sp, 1); break; default: case 'a': r_core_seek (core, frame->addr, 1); break; } r_core_cmd (core, cmd, 0); r_cons_newline (); i++; } r_core_seek (core, oseek, 0); r_list_free (list); } else { eprintf("Invalid for-each statement. Use @@=dbt[abs]\n"); } break; case 'k': /* foreach list of items */ { char *out = sdb_querys (core->sdb, NULL, 0, str + ((str[1])? 2: 1)); if (out) { each = out; do { while (*each == ' ') each++; if (!*each) { break; } str = strchr (each, ' '); if (str) { *str = '\0'; addr = r_num_math (core->num, each); *str = ' '; } else { addr = r_num_math (core->num, each); } //eprintf ("; 0x%08"PFMT64x":\n", addr); each = str + 1; r_core_seek (core, addr, 1); r_core_cmd (core, cmd, 0); r_cons_flush (); } while (str != NULL); free (out); } } break; case '.': if (each[1] == '(') { char cmd2[1024]; // XXX whats this 999 ? i = 0; for (core->rcmd->macro.counter = 0; i < 999; core->rcmd->macro.counter++) { if (r_cons_is_breaked ()) { break; } r_cmd_macro_call (&core->rcmd->macro, each + 2); if (!core->rcmd->macro.brk_value) { break; } addr = core->rcmd->macro._brk_value; sprintf (cmd2, "%s @ 0x%08"PFMT64x"", cmd, addr); eprintf ("0x%08"PFMT64x" (%s)\n", addr, cmd2); r_core_seek (core, addr, 1); r_core_cmd (core, cmd2, 0); i++; } } else { char buf[1024]; char cmd2[1024]; FILE *fd = r_sandbox_fopen (each + 1, "r"); if (fd) { core->rcmd->macro.counter=0; while (!feof (fd)) { buf[0] = '\0'; if (!fgets (buf, sizeof (buf), fd)) { break; } addr = r_num_math (core->num, buf); eprintf ("0x%08"PFMT64x": %s\n", addr, cmd); sprintf (cmd2, "%s @ 0x%08"PFMT64x"", cmd, addr); r_core_seek (core, addr, 1); // XXX r_core_cmd (core, cmd2, 0); core->rcmd->macro.counter++; } fclose (fd); } else { eprintf ("cannot open file '%s' to read offsets\n", each + 1); } } break; default: core->rcmd->macro.counter = 0; for (; *each == ' '; each++); i = 0; while (str[i]) { j = i; for (; str[j] && str[j] == ' '; j++); // skip spaces for (i = j; str[i] && str[i] != ' '; i++); // find EOS ch = str[i]; str[i] = '\0'; word = strdup (str + j); if (!word) { break; } str[i] = ch; { int flagspace = core->flags->space_idx; /* for all flags in current flagspace */ // XXX: dont ask why, but this only works with _prev.. r_list_foreach (core->flags->flags, iter, flag) { if (r_cons_is_breaked ()) { break; } /* filter per flag spaces */ if ((flagspace != -1) && (flag->space != flagspace)) { continue; } if (r_str_glob (flag->name, word)) { char *buf = NULL; const char *tmp = NULL; r_core_seek (core, flag->offset, 1); r_cons_push (); r_core_cmd (core, cmd, 0); tmp = r_cons_get_buffer (); buf = tmp? strdup (tmp): NULL; r_cons_pop (); r_cons_strcat (buf); free (buf); } } core->flags->space_idx = flagspace; core->rcmd->macro.counter++ ; free (word); word = NULL; } } } r_cons_break_pop (); // XXX: use r_core_seek here core->offset = oseek; free (word); free (ostr); return true; out_finish: r_cons_break_pop (); return false; } R_API int r_core_cmd(RCore *core, const char *cstr, int log) { char *cmd, *ocmd, *ptr, *rcmd; int ret = false, i; r_th_lock_enter (core->lock); if (core->cmdfilter) { const char *invalid_chars = ";|>`@"; for (i = 0; invalid_chars[i]; i++) { if (strchr (cstr, invalid_chars[i])) { ret = true; goto beach; } } if (strncmp (cstr, core->cmdfilter, strlen (core->cmdfilter))) { ret = true; goto beach; } } if (core->cmdremote) { if (*cstr != '=' && *cstr != 'q' && strncmp (cstr, "!=", 2)) { r_io_system (core->io, cstr); goto beach; // false } } if (!cstr || *cstr == '|') { // raw comment syntax goto beach; // false; } if (!strncmp (cstr, "/*", 2)) { if (r_sandbox_enable (0)) { eprintf ("This command is disabled in sandbox mode\n"); goto beach; // false } core->incomment = true; } else if (!strncmp (cstr, "*/", 2)) { core->incomment = false; goto beach; // false } if (core->incomment) { goto beach; // false } if (log && (*cstr && (*cstr != '.' || !strncmp (cstr, ".(", 2)))) { free (core->lastcmd); core->lastcmd = strdup (cstr); } ocmd = cmd = malloc (strlen (cstr) + 4096); if (!ocmd) { goto beach; } r_str_cpy (cmd, cstr); if (log) { r_line_hist_add (cstr); } if (core->cmd_depth < 1) { eprintf ("r_core_cmd: That was too deep (%s)...\n", cmd); free (ocmd); free (core->oobi); core->oobi = NULL; core->oobi_len = 0; goto beach; } core->cmd_depth--; for (rcmd = cmd;;) { ptr = strchr (rcmd, '\n'); if (ptr) { *ptr = '\0'; } ret = r_core_cmd_subst (core, rcmd); if (ret == -1) { eprintf ("|ERROR| Invalid command '%s' (0x%02x)\n", rcmd, *rcmd); break; } if (!ptr) { break; } rcmd = ptr + 1; } r_th_lock_leave (core->lock); /* run pending analysis commands */ if (core->anal->cmdtail) { char *res = core->anal->cmdtail; core->anal->cmdtail = NULL; r_core_cmd_lines (core, res); free (res); } core->cmd_depth++; free (ocmd); free (core->oobi); core->oobi = NULL; core->oobi_len = 0; return ret; beach: r_th_lock_leave (core->lock); /* run pending analysis commands */ if (core->anal->cmdtail) { char *res = core->anal->cmdtail; core->anal->cmdtail = NULL; r_core_cmd0 (core, res); free (res); } return ret; } R_API int r_core_cmd_lines(RCore *core, const char *lines) { int r, ret = true; char *nl, *data, *odata; if (!lines || !*lines) { return true; } data = odata = strdup (lines); if (!odata) { return false; } nl = strchr (odata, '\n'); if (nl) { r_cons_break_push (NULL, NULL); do { if (r_cons_is_breaked ()) { free (odata); r_cons_break_pop (); return ret; } *nl = '\0'; r = r_core_cmd (core, data, 0); if (r < 0) { //== -1) { data = nl + 1; ret = -1; //r; //false; break; } r_cons_flush (); if (data[0] == 'q') { if (data[1] == '!') { ret = -1; } else { eprintf ("'q': quit ignored. Use 'q!'\n"); } data = nl + 1; break; } data = nl + 1; } while ((nl = strchr (data, '\n'))); r_cons_break_pop (); } if (ret >= 0 && data && *data) { r_core_cmd (core, data, 0); } free (odata); return ret; } R_API int r_core_cmd_file(RCore *core, const char *file) { char *data, *odata; data = r_file_abspath (file); if (!data) return false; odata = r_file_slurp (data, NULL); free (data); if (!odata) return false; if (!r_core_cmd_lines (core, odata)) { eprintf ("Failed to run script '%s'\n", file); free (odata); return false; } free (odata); return true; } R_API int r_core_cmd_command(RCore *core, const char *command) { int ret, len; char *buf, *rcmd, *ptr; char *cmd = r_core_sysenv_begin (core, command); rcmd = ptr = buf = r_sys_cmd_str (cmd, 0, &len); if (!buf) { free (cmd); return -1; } ret = r_core_cmd (core, rcmd, 0); r_core_sysenv_end (core, command); free (buf); return ret; } //TODO: Fix disasm loop is mandatory R_API char *r_core_disassemble_instr(RCore *core, ut64 addr, int l) { char *cmd, *ret = NULL; cmd = r_str_newf ("pd %i @ 0x%08"PFMT64x, l, addr); if (cmd) { ret = r_core_cmd_str (core, cmd); free (cmd); } return ret; } R_API char *r_core_disassemble_bytes(RCore *core, ut64 addr, int b) { char *cmd, *ret = NULL; cmd = r_str_newf ("pD %i @ 0x%08"PFMT64x, b, addr); if (cmd) { ret = r_core_cmd_str (core, cmd); free (cmd); } return ret; } R_API int r_core_cmd_buffer(void *user, const char *buf) { char *ptr, *optr, *str = strdup (buf); if (!str) return false; optr = str; ptr = strchr (str, '\n'); while (ptr) { *ptr = '\0'; r_core_cmd (user, optr, 0); optr = ptr + 1; ptr = strchr (str, '\n'); } r_core_cmd (user, optr, 0); free (str); return true; } R_API int r_core_cmdf(void *user, const char *fmt, ...) { char string[4096]; int ret; va_list ap; va_start (ap, fmt); vsnprintf (string, sizeof (string), fmt, ap); ret = r_core_cmd ((RCore *)user, string, 0); va_end (ap); return ret; } R_API int r_core_cmd0(void *user, const char *cmd) { return r_core_cmd ((RCore *)user, cmd, 0); } R_API int r_core_flush(void *user, const char *cmd) { int ret = r_core_cmd ((RCore *)user, cmd, 0); r_cons_flush (); return ret; } R_API char *r_core_cmd_str_pipe(RCore *core, const char *cmd) { char *s, *tmp = NULL; if (r_sandbox_enable (0)) { return r_core_cmd_str (core, cmd); } r_cons_reset (); r_sandbox_disable (1); if (r_file_mkstemp ("cmd", &tmp) != -1) { int pipefd = r_cons_pipe_open (tmp, 1, 0); if (pipefd == -1) { r_sandbox_disable (0); return r_core_cmd_str (core, cmd); } char *_cmd = strdup (cmd); r_core_cmd_subst (core, _cmd); r_cons_flush (); r_cons_pipe_close (pipefd); s = r_file_slurp (tmp, NULL); if (s) { r_file_rm (tmp); r_sandbox_disable (0); free (tmp); free (_cmd); return s; } eprintf ("slurp %s fails\n", tmp); r_file_rm (tmp); free (tmp); free (_cmd); r_sandbox_disable (0); return r_core_cmd_str (core, cmd); } r_sandbox_disable (0); return NULL; } R_API char *r_core_cmd_strf(RCore *core, const char *fmt, ...) { char string[4096]; char *ret; va_list ap; va_start (ap, fmt); vsnprintf (string, sizeof (string), fmt, ap); ret = r_core_cmd_str (core, string); va_end (ap); return ret; } /* return: pointer to a buffer with the output of the command */ R_API char *r_core_cmd_str(RCore *core, const char *cmd) { const char *static_str; char *retstr = NULL; r_cons_push (); if (r_core_cmd (core, cmd, 0) == -1) { //eprintf ("Invalid command: %s\n", cmd); return NULL; } r_cons_filter (); static_str = r_cons_get_buffer (); retstr = strdup (static_str? static_str: ""); r_cons_pop (); return retstr; } R_API void r_core_cmd_repeat(RCore *core, int next) { // Fix for backtickbug px`~` if (core->cmd_depth + 1 < R_CORE_CMD_DEPTH) return; if (core->lastcmd) switch (*core->lastcmd) { case '.': if (core->lastcmd[1] == '(') // macro call r_core_cmd0 (core, core->lastcmd); break; case 'd': // debug r_core_cmd0 (core, core->lastcmd); switch (core->lastcmd[1]) { case 's': case 'c': r_core_cmd0 (core, "sr PC;pd 1"); } break; case 'p': // print case 'x': case '$': if (next) { r_core_seek (core, core->offset + core->blocksize, 1); } else { if (core->blocksize > core->offset) { r_core_seek (core, 0, 1); } else { r_core_seek (core, core->offset - core->blocksize, 1); } } r_core_cmd0 (core, core->lastcmd); break; } } static int cmd_ox(void *data, const char *input) { return r_core_cmdf ((RCore*)data, "s 0%s", input); } R_API void r_core_cmd_init(RCore *core) { core->rcmd = r_cmd_new (); core->rcmd->macro.user = core; core->rcmd->macro.num = core->num; core->rcmd->macro.cmd = r_core_cmd0; core->rcmd->nullcallback = r_core_cmd_nullcallback; core->rcmd->macro.cb_printf = (PrintfCallback)r_cons_printf; r_cmd_set_data (core->rcmd, core); r_cmd_add (core->rcmd, "0x", "alias for px", &cmd_ox); r_cmd_add (core->rcmd, "x", "alias for px", &cmd_hexdump); r_cmd_add (core->rcmd, "mount", "mount filesystem", &cmd_mount); r_cmd_add (core->rcmd, "analysis", "analysis", &cmd_anal); r_cmd_add (core->rcmd, "flag", "get/set flags", &cmd_flag); r_cmd_add (core->rcmd, "g", "egg manipulation", &cmd_egg); r_cmd_add (core->rcmd, "debug", "debugger operations", &cmd_debug); r_cmd_add (core->rcmd, "ls", "list files and directories", &cmd_ls); r_cmd_add (core->rcmd, "info", "get file info", &cmd_info); r_cmd_add (core->rcmd, "cmp", "compare memory", &cmd_cmp); r_cmd_add (core->rcmd, "seek", "seek to an offset", &cmd_seek); r_cmd_add (core->rcmd, "Text", "Text log utility", &cmd_log); r_cmd_add (core->rcmd, "t", "type information (cparse)", &cmd_type); r_cmd_add (core->rcmd, "zign", "zignatures", &cmd_zign); r_cmd_add (core->rcmd, "Section", "setup section io information", &cmd_section); r_cmd_add (core->rcmd, "bsize", "change block size", &cmd_bsize); r_cmd_add (core->rcmd, "kuery", "perform sdb query", &cmd_kuery); r_cmd_add (core->rcmd, "eval", "evaluate configuration variable", &cmd_eval); r_cmd_add (core->rcmd, "print", "print current block", &cmd_print); r_cmd_add (core->rcmd, "write", "write bytes", &cmd_write); r_cmd_add (core->rcmd, "Code", "code metadata", &cmd_meta); r_cmd_add (core->rcmd, "Project", "project", &cmd_project); r_cmd_add (core->rcmd, "open", "open or map file", &cmd_open); r_cmd_add (core->rcmd, "yank", "yank bytes", &cmd_yank); r_cmd_add (core->rcmd, "resize", "change file size", &cmd_resize); r_cmd_add (core->rcmd, "Visual", "enter visual mode", &cmd_visual); r_cmd_add (core->rcmd, "visual", "enter visual mode", &cmd_visual); r_cmd_add (core->rcmd, "*", "pointer read/write", &cmd_pointer); r_cmd_add (core->rcmd, "&", "threading capabilities", &cmd_thread); r_cmd_add (core->rcmd, "%", "short version of 'env' command", &cmd_env); r_cmd_add (core->rcmd, "!", "run system command", &cmd_system); r_cmd_add (core->rcmd, "=", "io pipe", &cmd_rap); r_cmd_add (core->rcmd, "\\", "alias for =!", &cmd_rap_run); r_cmd_add (core->rcmd, "#", "calculate hash", &cmd_hash); r_cmd_add (core->rcmd, "?", "help message", &cmd_help); r_cmd_add (core->rcmd, "$", "alias", &cmd_alias); r_cmd_add (core->rcmd, ".", "interpret", &cmd_interpret); r_cmd_add (core->rcmd, "/", "search kw, pattern aes", &cmd_search); r_cmd_add (core->rcmd, "-", "open cfg.editor and run script", &cmd_stdin); r_cmd_add (core->rcmd, "(", "macro", &cmd_macro); r_cmd_add (core->rcmd, "u", "uname/undo", &cmd_uname); r_cmd_add (core->rcmd, "quit", "exit program session", &cmd_quit); r_cmd_add (core->rcmd, "Q", "alias for q!", &cmd_Quit); r_cmd_add (core->rcmd, "L", "manage dynamically loaded plugins", &cmd_plugins); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_3406_0
crossvul-cpp_data_good_2988_0
/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com * Copyright (c) 2016 Facebook * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * 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. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/bpf.h> #include <linux/bpf_verifier.h> #include <linux/filter.h> #include <net/netlink.h> #include <linux/file.h> #include <linux/vmalloc.h> #include <linux/stringify.h> #include "disasm.h" static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { #define BPF_PROG_TYPE(_id, _name) \ [_id] = & _name ## _verifier_ops, #define BPF_MAP_TYPE(_id, _ops) #include <linux/bpf_types.h> #undef BPF_PROG_TYPE #undef BPF_MAP_TYPE }; /* bpf_check() is a static code analyzer that walks eBPF program * instruction by instruction and updates register/stack state. * All paths of conditional branches are analyzed until 'bpf_exit' insn. * * The first pass is depth-first-search to check that the program is a DAG. * It rejects the following programs: * - larger than BPF_MAXINSNS insns * - if loop is present (detected via back-edge) * - unreachable insns exist (shouldn't be a forest. program = one function) * - out of bounds or malformed jumps * The second pass is all possible path descent from the 1st insn. * Since it's analyzing all pathes through the program, the length of the * analysis is limited to 64k insn, which may be hit even if total number of * insn is less then 4K, but there are too many branches that change stack/regs. * Number of 'branches to be analyzed' is limited to 1k * * On entry to each instruction, each register has a type, and the instruction * changes the types of the registers depending on instruction semantics. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is * copied to R1. * * All registers are 64-bit. * R0 - return register * R1-R5 argument passing registers * R6-R9 callee saved registers * R10 - frame pointer read-only * * At the start of BPF program the register R1 contains a pointer to bpf_context * and has type PTR_TO_CTX. * * Verifier tracks arithmetic operations on pointers in case: * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), * 1st insn copies R10 (which has FRAME_PTR) type into R1 * and 2nd arithmetic instruction is pattern matched to recognize * that it wants to construct a pointer to some element within stack. * So after 2nd insn, the register R1 has type PTR_TO_STACK * (and -20 constant is saved for further stack bounds checking). * Meaning that this reg is a pointer to stack plus known immediate constant. * * Most of the time the registers have SCALAR_VALUE type, which * means the register has some value, but it's not a valid pointer. * (like pointer plus pointer becomes SCALAR_VALUE type) * * When verifier sees load or store instructions the type of base register * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer * types recognized by check_mem_access() function. * * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' * and the range of [ptr, ptr + map's value_size) is accessible. * * registers used to pass values to function calls are checked against * function argument constraints. * * ARG_PTR_TO_MAP_KEY is one of such argument constraints. * It means that the register type passed to this function must be * PTR_TO_STACK and it will be used inside the function as * 'pointer to map element key' * * For example the argument constraints for bpf_map_lookup_elem(): * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, * .arg1_type = ARG_CONST_MAP_PTR, * .arg2_type = ARG_PTR_TO_MAP_KEY, * * ret_type says that this function returns 'pointer to map elem value or null' * function expects 1st argument to be a const pointer to 'struct bpf_map' and * 2nd argument should be a pointer to stack, which will be used inside * the helper function as a pointer to map element key. * * On the kernel side the helper function looks like: * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) * { * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; * void *key = (void *) (unsigned long) r2; * void *value; * * here kernel can access 'key' and 'map' pointers safely, knowing that * [key, key + map->key_size) bytes are valid and were initialized on * the stack of eBPF program. * } * * Corresponding eBPF program may look like: * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), * here verifier looks at prototype of map_lookup_elem() and sees: * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, * Now verifier knows that this map has key of R1->map_ptr->key_size bytes * * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, * Now verifier checks that [R2, R2 + map's key_size) are within stack limits * and were initialized prior to this call. * If it's ok, then verifier allows this BPF_CALL insn and looks at * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function * returns ether pointer to map value or NULL. * * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' * insn, the register holding that pointer in the true branch changes state to * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false * branch. See check_cond_jmp_op(). * * After the call R0 is set to return type of the function and registers R1-R5 * are set to NOT_INIT to indicate that they are no longer readable. */ /* verifier_state + insn_idx are pushed to stack when branch is encountered */ struct bpf_verifier_stack_elem { /* verifer state is 'st' * before processing instruction 'insn_idx' * and after processing instruction 'prev_insn_idx' */ struct bpf_verifier_state st; int insn_idx; int prev_insn_idx; struct bpf_verifier_stack_elem *next; }; #define BPF_COMPLEXITY_LIMIT_INSNS 131072 #define BPF_COMPLEXITY_LIMIT_STACK 1024 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA) struct bpf_call_arg_meta { struct bpf_map *map_ptr; bool raw_mode; bool pkt_access; int regno; int access_size; }; static DEFINE_MUTEX(bpf_verifier_lock); /* log_level controls verbosity level of eBPF verifier. * verbose() is used to dump the verification trace to the log, so the user * can figure out what's wrong with the program */ static __printf(2, 3) void verbose(struct bpf_verifier_env *env, const char *fmt, ...) { struct bpf_verifer_log *log = &env->log; unsigned int n; va_list args; if (!log->level || !log->ubuf || bpf_verifier_log_full(log)) return; va_start(args, fmt); n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); va_end(args); WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, "verifier log line truncated - local buffer too short\n"); n = min(log->len_total - log->len_used - 1, n); log->kbuf[n] = '\0'; if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) log->len_used += n; else log->ubuf = NULL; } static bool type_is_pkt_pointer(enum bpf_reg_type type) { return type == PTR_TO_PACKET || type == PTR_TO_PACKET_META; } /* string representation of 'enum bpf_reg_type' */ static const char * const reg_type_str[] = { [NOT_INIT] = "?", [SCALAR_VALUE] = "inv", [PTR_TO_CTX] = "ctx", [CONST_PTR_TO_MAP] = "map_ptr", [PTR_TO_MAP_VALUE] = "map_value", [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null", [PTR_TO_STACK] = "fp", [PTR_TO_PACKET] = "pkt", [PTR_TO_PACKET_META] = "pkt_meta", [PTR_TO_PACKET_END] = "pkt_end", }; static void print_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *state) { struct bpf_reg_state *reg; enum bpf_reg_type t; int i; for (i = 0; i < MAX_BPF_REG; i++) { reg = &state->regs[i]; t = reg->type; if (t == NOT_INIT) continue; verbose(env, " R%d=%s", i, reg_type_str[t]); if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && tnum_is_const(reg->var_off)) { /* reg->off should be 0 for SCALAR_VALUE */ verbose(env, "%lld", reg->var_off.value + reg->off); } else { verbose(env, "(id=%d", reg->id); if (t != SCALAR_VALUE) verbose(env, ",off=%d", reg->off); if (type_is_pkt_pointer(t)) verbose(env, ",r=%d", reg->range); else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE || t == PTR_TO_MAP_VALUE_OR_NULL) verbose(env, ",ks=%d,vs=%d", reg->map_ptr->key_size, reg->map_ptr->value_size); if (tnum_is_const(reg->var_off)) { /* Typically an immediate SCALAR_VALUE, but * could be a pointer whose offset is too big * for reg->off */ verbose(env, ",imm=%llx", reg->var_off.value); } else { if (reg->smin_value != reg->umin_value && reg->smin_value != S64_MIN) verbose(env, ",smin_value=%lld", (long long)reg->smin_value); if (reg->smax_value != reg->umax_value && reg->smax_value != S64_MAX) verbose(env, ",smax_value=%lld", (long long)reg->smax_value); if (reg->umin_value != 0) verbose(env, ",umin_value=%llu", (unsigned long long)reg->umin_value); if (reg->umax_value != U64_MAX) verbose(env, ",umax_value=%llu", (unsigned long long)reg->umax_value); if (!tnum_is_unknown(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, ",var_off=%s", tn_buf); } } verbose(env, ")"); } } for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] == STACK_SPILL) verbose(env, " fp%d=%s", -MAX_BPF_STACK + i * BPF_REG_SIZE, reg_type_str[state->stack[i].spilled_ptr.type]); } verbose(env, "\n"); } static int copy_stack_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) { if (!src->stack) return 0; if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) { /* internal bug, make state invalid to reject the program */ memset(dst, 0, sizeof(*dst)); return -EFAULT; } memcpy(dst->stack, src->stack, sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE)); return 0; } /* do_check() starts with zero-sized stack in struct bpf_verifier_state to * make it consume minimal amount of memory. check_stack_write() access from * the program calls into realloc_verifier_state() to grow the stack size. * Note there is a non-zero 'parent' pointer inside bpf_verifier_state * which this function copies over. It points to previous bpf_verifier_state * which is never reallocated */ static int realloc_verifier_state(struct bpf_verifier_state *state, int size, bool copy_old) { u32 old_size = state->allocated_stack; struct bpf_stack_state *new_stack; int slot = size / BPF_REG_SIZE; if (size <= old_size || !size) { if (copy_old) return 0; state->allocated_stack = slot * BPF_REG_SIZE; if (!size && old_size) { kfree(state->stack); state->stack = NULL; } return 0; } new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state), GFP_KERNEL); if (!new_stack) return -ENOMEM; if (copy_old) { if (state->stack) memcpy(new_stack, state->stack, sizeof(*new_stack) * (old_size / BPF_REG_SIZE)); memset(new_stack + old_size / BPF_REG_SIZE, 0, sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE); } state->allocated_stack = slot * BPF_REG_SIZE; kfree(state->stack); state->stack = new_stack; return 0; } static void free_verifier_state(struct bpf_verifier_state *state, bool free_self) { kfree(state->stack); if (free_self) kfree(state); } /* copy verifier state from src to dst growing dst stack space * when necessary to accommodate larger src stack */ static int copy_verifier_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) { int err; err = realloc_verifier_state(dst, src->allocated_stack, false); if (err) return err; memcpy(dst, src, offsetof(struct bpf_verifier_state, allocated_stack)); return copy_stack_state(dst, src); } static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, int *insn_idx) { struct bpf_verifier_state *cur = env->cur_state; struct bpf_verifier_stack_elem *elem, *head = env->head; int err; if (env->head == NULL) return -ENOENT; if (cur) { err = copy_verifier_state(cur, &head->st); if (err) return err; } if (insn_idx) *insn_idx = head->insn_idx; if (prev_insn_idx) *prev_insn_idx = head->prev_insn_idx; elem = head->next; free_verifier_state(&head->st, false); kfree(head); env->head = elem; env->stack_size--; return 0; } static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { struct bpf_verifier_state *cur = env->cur_state; struct bpf_verifier_stack_elem *elem; int err; elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); if (!elem) goto err; elem->insn_idx = insn_idx; elem->prev_insn_idx = prev_insn_idx; elem->next = env->head; env->head = elem; env->stack_size++; err = copy_verifier_state(&elem->st, cur); if (err) goto err; if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) { verbose(env, "BPF program is too complex\n"); goto err; } return &elem->st; err: /* pop all elements and return */ while (!pop_stack(env, NULL, NULL)); return NULL; } #define CALLER_SAVED_REGS 6 static const int caller_saved[CALLER_SAVED_REGS] = { BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 }; static void __mark_reg_not_init(struct bpf_reg_state *reg); /* Mark the unknown part of a register (variable offset or scalar value) as * known to have the value @imm. */ static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) { reg->id = 0; reg->var_off = tnum_const(imm); reg->smin_value = (s64)imm; reg->smax_value = (s64)imm; reg->umin_value = imm; reg->umax_value = imm; } /* Mark the 'variable offset' part of a register as zero. This should be * used only on registers holding a pointer type. */ static void __mark_reg_known_zero(struct bpf_reg_state *reg) { __mark_reg_known(reg, 0); } static void mark_reg_known_zero(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_known_zero(regs + regno); } static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) { return type_is_pkt_pointer(reg->type); } static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) { return reg_is_pkt_pointer(reg) || reg->type == PTR_TO_PACKET_END; } /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, enum bpf_reg_type which) { /* The register can already have a range from prior markings. * This is fine as long as it hasn't been advanced from its * origin. */ return reg->type == which && reg->id == 0 && reg->off == 0 && tnum_equals_const(reg->var_off, 0); } /* Attempts to improve min/max values based on var_off information */ static void __update_reg_bounds(struct bpf_reg_state *reg) { /* min signed is max(sign bit) | min(other bits) */ reg->smin_value = max_t(s64, reg->smin_value, reg->var_off.value | (reg->var_off.mask & S64_MIN)); /* max signed is min(sign bit) | max(other bits) */ reg->smax_value = min_t(s64, reg->smax_value, reg->var_off.value | (reg->var_off.mask & S64_MAX)); reg->umin_value = max(reg->umin_value, reg->var_off.value); reg->umax_value = min(reg->umax_value, reg->var_off.value | reg->var_off.mask); } /* Uses signed min/max values to inform unsigned, and vice-versa */ static void __reg_deduce_bounds(struct bpf_reg_state *reg) { /* Learn sign from signed bounds. * If we cannot cross the sign boundary, then signed and unsigned bounds * are the same, so combine. This works even in the negative case, e.g. * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. */ if (reg->smin_value >= 0 || reg->smax_value < 0) { reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); return; } /* Learn sign from unsigned bounds. Signed bounds cross the sign * boundary, so we must be careful. */ if ((s64)reg->umax_value >= 0) { /* Positive. We can't learn anything from the smin, but smax * is positive, hence safe. */ reg->smin_value = reg->umin_value; reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); } else if ((s64)reg->umin_value < 0) { /* Negative. We can't learn anything from the smax, but smin * is negative, hence safe. */ reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); reg->smax_value = reg->umax_value; } } /* Attempts to improve var_off based on unsigned min/max information */ static void __reg_bound_offset(struct bpf_reg_state *reg) { reg->var_off = tnum_intersect(reg->var_off, tnum_range(reg->umin_value, reg->umax_value)); } /* Reset the min/max bounds of a register */ static void __mark_reg_unbounded(struct bpf_reg_state *reg) { reg->smin_value = S64_MIN; reg->smax_value = S64_MAX; reg->umin_value = 0; reg->umax_value = U64_MAX; } /* Mark a register as having a completely unknown (scalar) value. */ static void __mark_reg_unknown(struct bpf_reg_state *reg) { reg->type = SCALAR_VALUE; reg->id = 0; reg->off = 0; reg->var_off = tnum_unknown; __mark_reg_unbounded(reg); } static void mark_reg_unknown(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_unknown(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_unknown(regs + regno); } static void __mark_reg_not_init(struct bpf_reg_state *reg) { __mark_reg_unknown(reg); reg->type = NOT_INIT; } static void mark_reg_not_init(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_not_init(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_not_init(regs + regno); } static void init_reg_state(struct bpf_verifier_env *env, struct bpf_reg_state *regs) { int i; for (i = 0; i < MAX_BPF_REG; i++) { mark_reg_not_init(env, regs, i); regs[i].live = REG_LIVE_NONE; } /* frame pointer */ regs[BPF_REG_FP].type = PTR_TO_STACK; mark_reg_known_zero(env, regs, BPF_REG_FP); /* 1st arg to a function */ regs[BPF_REG_1].type = PTR_TO_CTX; mark_reg_known_zero(env, regs, BPF_REG_1); } enum reg_arg_type { SRC_OP, /* register is used as source operand */ DST_OP, /* register is used as destination operand */ DST_OP_NO_MARK /* same as above, check only, don't mark */ }; static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno) { struct bpf_verifier_state *parent = state->parent; if (regno == BPF_REG_FP) /* We don't need to worry about FP liveness because it's read-only */ return; while (parent) { /* if read wasn't screened by an earlier write ... */ if (state->regs[regno].live & REG_LIVE_WRITTEN) break; /* ... then we depend on parent's value */ parent->regs[regno].live |= REG_LIVE_READ; state = parent; parent = state->parent; } } static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, enum reg_arg_type t) { struct bpf_reg_state *regs = env->cur_state->regs; if (regno >= MAX_BPF_REG) { verbose(env, "R%d is invalid\n", regno); return -EINVAL; } if (t == SRC_OP) { /* check whether register used as source operand can be read */ if (regs[regno].type == NOT_INIT) { verbose(env, "R%d !read_ok\n", regno); return -EACCES; } mark_reg_read(env->cur_state, regno); } else { /* check whether register used as dest operand can be written to */ if (regno == BPF_REG_FP) { verbose(env, "frame pointer is read only\n"); return -EACCES; } regs[regno].live |= REG_LIVE_WRITTEN; if (t == DST_OP) mark_reg_unknown(env, regs, regno); } return 0; } static bool is_spillable_regtype(enum bpf_reg_type type) { switch (type) { case PTR_TO_MAP_VALUE: case PTR_TO_MAP_VALUE_OR_NULL: case PTR_TO_STACK: case PTR_TO_CTX: case PTR_TO_PACKET: case PTR_TO_PACKET_META: case PTR_TO_PACKET_END: case CONST_PTR_TO_MAP: return true; default: return false; } } /* check_stack_read/write functions track spill/fill of registers, * stack boundary and alignment are checked in check_mem_access() */ static int check_stack_write(struct bpf_verifier_env *env, struct bpf_verifier_state *state, int off, int size, int value_regno) { int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; err = realloc_verifier_state(state, round_up(slot + 1, BPF_REG_SIZE), true); if (err) return err; /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, * so it's aligned access and [off, off + size) are within stack limits */ if (!env->allow_ptr_leaks && state->stack[spi].slot_type[0] == STACK_SPILL && size != BPF_REG_SIZE) { verbose(env, "attempt to corrupt spilled pointer on stack\n"); return -EACCES; } if (value_regno >= 0 && is_spillable_regtype(state->regs[value_regno].type)) { /* register containing pointer is being spilled into stack */ if (size != BPF_REG_SIZE) { verbose(env, "invalid size of register spill\n"); return -EACCES; } /* save register state */ state->stack[spi].spilled_ptr = state->regs[value_regno]; state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; for (i = 0; i < BPF_REG_SIZE; i++) state->stack[spi].slot_type[i] = STACK_SPILL; } else { /* regular write of data into stack */ state->stack[spi].spilled_ptr = (struct bpf_reg_state) {}; for (i = 0; i < size; i++) state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = STACK_MISC; } return 0; } static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot) { struct bpf_verifier_state *parent = state->parent; while (parent) { /* if read wasn't screened by an earlier write ... */ if (state->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN) break; /* ... then we depend on parent's value */ parent->stack[slot].spilled_ptr.live |= REG_LIVE_READ; state = parent; parent = state->parent; } } static int check_stack_read(struct bpf_verifier_env *env, struct bpf_verifier_state *state, int off, int size, int value_regno) { int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; u8 *stype; if (state->allocated_stack <= slot) { verbose(env, "invalid read from stack off %d+0 size %d\n", off, size); return -EACCES; } stype = state->stack[spi].slot_type; if (stype[0] == STACK_SPILL) { if (size != BPF_REG_SIZE) { verbose(env, "invalid size of register spill\n"); return -EACCES; } for (i = 1; i < BPF_REG_SIZE; i++) { if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) { verbose(env, "corrupted spill memory\n"); return -EACCES; } } if (value_regno >= 0) { /* restore register state from stack */ state->regs[value_regno] = state->stack[spi].spilled_ptr; mark_stack_slot_read(state, spi); } return 0; } else { for (i = 0; i < size; i++) { if (stype[(slot - i) % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid read from stack off %d+%d size %d\n", off, i, size); return -EACCES; } } if (value_regno >= 0) /* have read misc data from the stack */ mark_reg_unknown(env, state->regs, value_regno); return 0; } } /* check read/write into map element returned by bpf_map_lookup_elem() */ static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_map *map = regs[regno].map_ptr; if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || off + size > map->value_size) { verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", map->value_size, off, size); return -EACCES; } return 0; } /* check read/write into a map element with possible variable offset */ static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *reg = &state->regs[regno]; int err; /* We may have adjusted the register to this map value, so we * need to try adding each of min_value and max_value to off * to make sure our theoretical access will be safe. */ if (env->log.level) print_verifier_state(env, state); /* The minimum value is only important with signed * comparisons where we can't assume the floor of a * value is 0. If we are using signed variables for our * index'es we need to make sure that whatever we use * will have a set floor within our range. */ if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", regno); return -EACCES; } err = __check_map_access(env, regno, reg->smin_value + off, size, zero_size_allowed); if (err) { verbose(env, "R%d min value is outside of the array range\n", regno); return err; } /* If we haven't set a max value then we need to bail since we can't be * sure we won't do bad things. * If reg->umax_value + off could overflow, treat that as unbounded too. */ if (reg->umax_value >= BPF_MAX_VAR_OFF) { verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n", regno); return -EACCES; } err = __check_map_access(env, regno, reg->umax_value + off, size, zero_size_allowed); if (err) verbose(env, "R%d max value is outside of the array range\n", regno); return err; } #define MAX_PACKET_OFF 0xffff static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, const struct bpf_call_arg_meta *meta, enum bpf_access_type t) { switch (env->prog->type) { case BPF_PROG_TYPE_LWT_IN: case BPF_PROG_TYPE_LWT_OUT: /* dst_input() and dst_output() can't write for now */ if (t == BPF_WRITE) return false; /* fallthrough */ case BPF_PROG_TYPE_SCHED_CLS: case BPF_PROG_TYPE_SCHED_ACT: case BPF_PROG_TYPE_XDP: case BPF_PROG_TYPE_LWT_XMIT: case BPF_PROG_TYPE_SK_SKB: if (meta) return meta->pkt_access; env->seen_direct_write = true; return true; default: return false; } } static int __check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = &regs[regno]; if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || (u64)off + size > reg->range) { verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", off, size, regno, reg->id, reg->off, reg->range); return -EACCES; } return 0; } static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = &regs[regno]; int err; /* We may have added a variable offset to the packet pointer; but any * reg->range we have comes after that. We are only checking the fixed * offset. */ /* We don't allow negative numbers, because we aren't tracking enough * detail to prove they're safe. */ if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", regno); return -EACCES; } err = __check_packet_access(env, regno, off, size, zero_size_allowed); if (err) { verbose(env, "R%d offset is outside of the packet\n", regno); return err; } return err; } /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, enum bpf_access_type t, enum bpf_reg_type *reg_type) { struct bpf_insn_access_aux info = { .reg_type = *reg_type, }; if (env->ops->is_valid_access && env->ops->is_valid_access(off, size, t, &info)) { /* A non zero info.ctx_field_size indicates that this field is a * candidate for later verifier transformation to load the whole * field and then apply a mask when accessed with a narrower * access than actual ctx access size. A zero info.ctx_field_size * will only allow for whole field access and rejects any other * type of narrower access. */ *reg_type = info.reg_type; env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; /* remember the offset of last byte accessed in ctx */ if (env->prog->aux->max_ctx_offset < off + size) env->prog->aux->max_ctx_offset = off + size; return 0; } verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); return -EACCES; } static bool __is_pointer_value(bool allow_ptr_leaks, const struct bpf_reg_state *reg) { if (allow_ptr_leaks) return false; return reg->type != SCALAR_VALUE; } static bool is_pointer_value(struct bpf_verifier_env *env, int regno) { return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno); } static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size, bool strict) { struct tnum reg_off; int ip_align; /* Byte size accesses are always allowed. */ if (!strict || size == 1) return 0; /* For platforms that do not have a Kconfig enabling * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of * NET_IP_ALIGN is universally set to '2'. And on platforms * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get * to this code only in strict mode where we want to emulate * the NET_IP_ALIGN==2 checking. Therefore use an * unconditional IP align value of '2'. */ ip_align = 2; reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); if (!tnum_is_aligned(reg_off, size)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "misaligned packet access off %d+%s+%d+%d size %d\n", ip_align, tn_buf, reg->off, off, size); return -EACCES; } return 0; } static int check_generic_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, const char *pointer_desc, int off, int size, bool strict) { struct tnum reg_off; /* Byte size accesses are always allowed. */ if (!strict || size == 1) return 0; reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); if (!tnum_is_aligned(reg_off, size)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", pointer_desc, tn_buf, reg->off, off, size); return -EACCES; } return 0; } static int check_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size) { bool strict = env->strict_alignment; const char *pointer_desc = ""; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: /* Special case, because of NET_IP_ALIGN. Given metadata sits * right in front, treat it the very same way. */ return check_pkt_ptr_alignment(env, reg, off, size, strict); case PTR_TO_MAP_VALUE: pointer_desc = "value "; break; case PTR_TO_CTX: pointer_desc = "context "; break; case PTR_TO_STACK: pointer_desc = "stack "; break; default: break; } return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, strict); } /* truncate register to smaller size (in bytes) * must be called with size < BPF_REG_SIZE */ static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) { u64 mask; /* clear high bits in bit representation */ reg->var_off = tnum_cast(reg->var_off, size); /* fix arithmetic bounds */ mask = ((u64)1 << (size * 8)) - 1; if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { reg->umin_value &= mask; reg->umax_value &= mask; } else { reg->umin_value = 0; reg->umax_value = mask; } reg->smin_value = reg->umin_value; reg->smax_value = reg->umax_value; } /* check whether memory at (regno + off) is accessible for t = (read | write) * if t==write, value_regno is a register which value is stored into memory * if t==read, value_regno is a register which will receive the value from memory * if t==write && value_regno==-1, some unknown value is stored into memory * if t==read && value_regno==-1, don't care what we read from memory */ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off, int bpf_size, enum bpf_access_type t, int value_regno) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = regs + regno; int size, err = 0; size = bpf_size_to_bytes(bpf_size); if (size < 0) return size; /* alignment checks will add in reg->off themselves */ err = check_ptr_alignment(env, reg, off, size); if (err) return err; /* for access checks, reg->off is just part of off */ off += reg->off; if (reg->type == PTR_TO_MAP_VALUE) { if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into map\n", value_regno); return -EACCES; } err = check_map_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else if (reg->type == PTR_TO_CTX) { enum bpf_reg_type reg_type = SCALAR_VALUE; if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into ctx\n", value_regno); return -EACCES; } /* ctx accesses must be at a fixed offset, so that we can * determine what type of data were returned. */ if (reg->off) { verbose(env, "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n", regno, reg->off, off - reg->off); return -EACCES; } if (!tnum_is_const(reg->var_off) || reg->var_off.value) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable ctx access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } err = check_ctx_access(env, insn_idx, off, size, t, &reg_type); if (!err && t == BPF_READ && value_regno >= 0) { /* ctx access returns either a scalar, or a * PTR_TO_PACKET[_META,_END]. In the latter * case, we know the offset is zero. */ if (reg_type == SCALAR_VALUE) mark_reg_unknown(env, regs, value_regno); else mark_reg_known_zero(env, regs, value_regno); regs[value_regno].id = 0; regs[value_regno].off = 0; regs[value_regno].range = 0; regs[value_regno].type = reg_type; } } else if (reg->type == PTR_TO_STACK) { /* stack accesses must be at a fixed offset, so that we can * determine what type of data were returned. * See check_stack_read(). */ if (!tnum_is_const(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable stack access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } off += reg->var_off.value; if (off >= 0 || off < -MAX_BPF_STACK) { verbose(env, "invalid stack off=%d size=%d\n", off, size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (t == BPF_WRITE) err = check_stack_write(env, state, off, size, value_regno); else err = check_stack_read(env, state, off, size, value_regno); } else if (reg_is_pkt_pointer(reg)) { if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { verbose(env, "cannot write into packet\n"); return -EACCES; } if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into packet\n", value_regno); return -EACCES; } err = check_packet_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else { verbose(env, "R%d invalid mem access '%s'\n", regno, reg_type_str[reg->type]); return -EACCES; } if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && regs[value_regno].type == SCALAR_VALUE) { /* b/h/w load zero-extends, mark upper bits as known 0 */ coerce_reg_to_size(&regs[value_regno], size); } return err; } static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) { int err; if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) || insn->imm != 0) { verbose(env, "BPF_XADD uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d leaks addr into mem\n", insn->src_reg); return -EACCES; } /* check whether atomic_add can read the memory */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, -1); if (err) return err; /* check whether atomic_add can write into the same memory */ return check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); } /* Does this register contain a constant zero? */ static bool register_is_null(struct bpf_reg_state reg) { return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0); } /* when register 'regno' is passed into function that will read 'access_size' * bytes from that pointer, make sure that it's within stack boundary * and all elements of stack are initialized. * Unlike most pointer bounds-checking functions, this one doesn't take an * 'off' argument, so it has to add in reg->off itself. */ static int check_stack_boundary(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs; int off, i, slot, spi; if (regs[regno].type != PTR_TO_STACK) { /* Allow zero-byte read from NULL, regardless of pointer type */ if (zero_size_allowed && access_size == 0 && register_is_null(regs[regno])) return 0; verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[regs[regno].type], reg_type_str[PTR_TO_STACK]); return -EACCES; } /* Only allow fixed-offset stack reads */ if (!tnum_is_const(regs[regno].var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off); verbose(env, "invalid variable stack read R%d var_off=%s\n", regno, tn_buf); return -EACCES; } off = regs[regno].off + regs[regno].var_off.value; if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || access_size < 0 || (access_size == 0 && !zero_size_allowed)) { verbose(env, "invalid stack type R%d off=%d access_size=%d\n", regno, off, access_size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (meta && meta->raw_mode) { meta->access_size = access_size; meta->regno = regno; return 0; } for (i = 0; i < access_size; i++) { slot = -(off + i) - 1; spi = slot / BPF_REG_SIZE; if (state->allocated_stack <= slot || state->stack[spi].slot_type[slot % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid indirect read from stack off %d+%d size %d\n", off, i, access_size); return -EACCES; } } return 0; } static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno]; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: return check_packet_access(env, regno, reg->off, access_size, zero_size_allowed); case PTR_TO_MAP_VALUE: return check_map_access(env, regno, reg->off, access_size, zero_size_allowed); default: /* scalar_value|ptr_to_stack or invalid ptr */ return check_stack_boundary(env, regno, access_size, zero_size_allowed, meta); } } static int check_func_arg(struct bpf_verifier_env *env, u32 regno, enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta) { struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno]; enum bpf_reg_type expected_type, type = reg->type; int err = 0; if (arg_type == ARG_DONTCARE) return 0; err = check_reg_arg(env, regno, SRC_OP); if (err) return err; if (arg_type == ARG_ANYTHING) { if (is_pointer_value(env, regno)) { verbose(env, "R%d leaks addr into helper function\n", regno); return -EACCES; } return 0; } if (type_is_pkt_pointer(type) && !may_access_direct_pkt_data(env, meta, BPF_READ)) { verbose(env, "helper access to the packet is not allowed\n"); return -EACCES; } if (arg_type == ARG_PTR_TO_MAP_KEY || arg_type == ARG_PTR_TO_MAP_VALUE) { expected_type = PTR_TO_STACK; if (!type_is_pkt_pointer(type) && type != expected_type) goto err_type; } else if (arg_type == ARG_CONST_SIZE || arg_type == ARG_CONST_SIZE_OR_ZERO) { expected_type = SCALAR_VALUE; if (type != expected_type) goto err_type; } else if (arg_type == ARG_CONST_MAP_PTR) { expected_type = CONST_PTR_TO_MAP; if (type != expected_type) goto err_type; } else if (arg_type == ARG_PTR_TO_CTX) { expected_type = PTR_TO_CTX; if (type != expected_type) goto err_type; } else if (arg_type == ARG_PTR_TO_MEM || arg_type == ARG_PTR_TO_MEM_OR_NULL || arg_type == ARG_PTR_TO_UNINIT_MEM) { expected_type = PTR_TO_STACK; /* One exception here. In case function allows for NULL to be * passed in as argument, it's a SCALAR_VALUE type. Final test * happens during stack boundary checking. */ if (register_is_null(*reg) && arg_type == ARG_PTR_TO_MEM_OR_NULL) /* final test in check_stack_boundary() */; else if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE && type != expected_type) goto err_type; meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM; } else { verbose(env, "unsupported arg_type %d\n", arg_type); return -EFAULT; } if (arg_type == ARG_CONST_MAP_PTR) { /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ meta->map_ptr = reg->map_ptr; } else if (arg_type == ARG_PTR_TO_MAP_KEY) { /* bpf_map_xxx(..., map_ptr, ..., key) call: * check that [key, key + map->key_size) are within * stack limits and initialized */ if (!meta->map_ptr) { /* in function declaration map_ptr must come before * map_key, so that it's verified and known before * we have to check map_key here. Otherwise it means * that kernel subsystem misconfigured verifier */ verbose(env, "invalid map_ptr to access map->key\n"); return -EACCES; } if (type_is_pkt_pointer(type)) err = check_packet_access(env, regno, reg->off, meta->map_ptr->key_size, false); else err = check_stack_boundary(env, regno, meta->map_ptr->key_size, false, NULL); } else if (arg_type == ARG_PTR_TO_MAP_VALUE) { /* bpf_map_xxx(..., map_ptr, ..., value) call: * check [value, value + map->value_size) validity */ if (!meta->map_ptr) { /* kernel subsystem misconfigured verifier */ verbose(env, "invalid map_ptr to access map->value\n"); return -EACCES; } if (type_is_pkt_pointer(type)) err = check_packet_access(env, regno, reg->off, meta->map_ptr->value_size, false); else err = check_stack_boundary(env, regno, meta->map_ptr->value_size, false, NULL); } else if (arg_type == ARG_CONST_SIZE || arg_type == ARG_CONST_SIZE_OR_ZERO) { bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); /* bpf_xxx(..., buf, len) call will access 'len' bytes * from stack pointer 'buf'. Check it * note: regno == len, regno - 1 == buf */ if (regno == 0) { /* kernel subsystem misconfigured verifier */ verbose(env, "ARG_CONST_SIZE cannot be first argument\n"); return -EACCES; } /* The register is SCALAR_VALUE; the access check * happens using its boundaries. */ if (!tnum_is_const(reg->var_off)) /* For unprivileged variable accesses, disable raw * mode so that the program is required to * initialize all the memory that the helper could * just partially fill up. */ meta = NULL; if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", regno); return -EACCES; } if (reg->umin_value == 0) { err = check_helper_mem_access(env, regno - 1, 0, zero_size_allowed, meta); if (err) return err; } if (reg->umax_value >= BPF_MAX_VAR_SIZ) { verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", regno); return -EACCES; } err = check_helper_mem_access(env, regno - 1, reg->umax_value, zero_size_allowed, meta); } return err; err_type: verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[type], reg_type_str[expected_type]); return -EACCES; } static int check_map_func_compatibility(struct bpf_verifier_env *env, struct bpf_map *map, int func_id) { if (!map) return 0; /* We need a two way check, first is from map perspective ... */ switch (map->map_type) { case BPF_MAP_TYPE_PROG_ARRAY: if (func_id != BPF_FUNC_tail_call) goto error; break; case BPF_MAP_TYPE_PERF_EVENT_ARRAY: if (func_id != BPF_FUNC_perf_event_read && func_id != BPF_FUNC_perf_event_output && func_id != BPF_FUNC_perf_event_read_value) goto error; break; case BPF_MAP_TYPE_STACK_TRACE: if (func_id != BPF_FUNC_get_stackid) goto error; break; case BPF_MAP_TYPE_CGROUP_ARRAY: if (func_id != BPF_FUNC_skb_under_cgroup && func_id != BPF_FUNC_current_task_under_cgroup) goto error; break; /* devmap returns a pointer to a live net_device ifindex that we cannot * allow to be modified from bpf side. So do not allow lookup elements * for now. */ case BPF_MAP_TYPE_DEVMAP: if (func_id != BPF_FUNC_redirect_map) goto error; break; /* Restrict bpf side of cpumap, open when use-cases appear */ case BPF_MAP_TYPE_CPUMAP: if (func_id != BPF_FUNC_redirect_map) goto error; break; case BPF_MAP_TYPE_ARRAY_OF_MAPS: case BPF_MAP_TYPE_HASH_OF_MAPS: if (func_id != BPF_FUNC_map_lookup_elem) goto error; break; case BPF_MAP_TYPE_SOCKMAP: if (func_id != BPF_FUNC_sk_redirect_map && func_id != BPF_FUNC_sock_map_update && func_id != BPF_FUNC_map_delete_elem) goto error; break; default: break; } /* ... and second from the function itself. */ switch (func_id) { case BPF_FUNC_tail_call: if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) goto error; break; case BPF_FUNC_perf_event_read: case BPF_FUNC_perf_event_output: case BPF_FUNC_perf_event_read_value: if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) goto error; break; case BPF_FUNC_get_stackid: if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) goto error; break; case BPF_FUNC_current_task_under_cgroup: case BPF_FUNC_skb_under_cgroup: if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) goto error; break; case BPF_FUNC_redirect_map: if (map->map_type != BPF_MAP_TYPE_DEVMAP && map->map_type != BPF_MAP_TYPE_CPUMAP) goto error; break; case BPF_FUNC_sk_redirect_map: if (map->map_type != BPF_MAP_TYPE_SOCKMAP) goto error; break; case BPF_FUNC_sock_map_update: if (map->map_type != BPF_MAP_TYPE_SOCKMAP) goto error; break; default: break; } return 0; error: verbose(env, "cannot pass map_type %d into func %s#%d\n", map->map_type, func_id_name(func_id), func_id); return -EINVAL; } static int check_raw_mode(const struct bpf_func_proto *fn) { int count = 0; if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) count++; return count > 1 ? -EINVAL : 0; } /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] * are now invalid, so turn them into unknown SCALAR_VALUE. */ static void clear_all_pkt_pointers(struct bpf_verifier_env *env) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs, *reg; int i; for (i = 0; i < MAX_BPF_REG; i++) if (reg_is_pkt_pointer_any(&regs[i])) mark_reg_unknown(env, regs, i); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; reg = &state->stack[i].spilled_ptr; if (reg_is_pkt_pointer_any(reg)) __mark_reg_unknown(reg); } } static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx) { const struct bpf_func_proto *fn = NULL; struct bpf_reg_state *regs; struct bpf_call_arg_meta meta; bool changes_data; int i, err; /* find function prototype */ if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } if (env->ops->get_func_proto) fn = env->ops->get_func_proto(func_id); if (!fn) { verbose(env, "unknown func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } /* eBPF programs must be GPL compatible to use GPL-ed functions */ if (!env->prog->gpl_compatible && fn->gpl_only) { verbose(env, "cannot call GPL only function from proprietary program\n"); return -EINVAL; } /* With LD_ABS/IND some JITs save/restore skb from r1. */ changes_data = bpf_helper_changes_pkt_data(fn->func); if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", func_id_name(func_id), func_id); return -EINVAL; } memset(&meta, 0, sizeof(meta)); meta.pkt_access = fn->pkt_access; /* We only support one arg being in raw mode at the moment, which * is sufficient for the helper functions we have right now. */ err = check_raw_mode(fn); if (err) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(func_id), func_id); return err; } /* check args */ err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta); if (err) return err; /* Mark slots with STACK_MISC in case of raw mode, stack offset * is inferred from register state. */ for (i = 0; i < meta.access_size; i++) { err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1); if (err) return err; } regs = cur_regs(env); /* reset caller saved regs */ for (i = 0; i < CALLER_SAVED_REGS; i++) { mark_reg_not_init(env, regs, caller_saved[i]); check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); } /* update return register (already marked as written above) */ if (fn->ret_type == RET_INTEGER) { /* sets type to SCALAR_VALUE */ mark_reg_unknown(env, regs, BPF_REG_0); } else if (fn->ret_type == RET_VOID) { regs[BPF_REG_0].type = NOT_INIT; } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) { struct bpf_insn_aux_data *insn_aux; regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; /* There is no offset yet applied, variable or fixed */ mark_reg_known_zero(env, regs, BPF_REG_0); regs[BPF_REG_0].off = 0; /* remember map_ptr, so that check_map_access() * can check 'value_size' boundary of memory access * to map element returned from bpf_map_lookup_elem() */ if (meta.map_ptr == NULL) { verbose(env, "kernel subsystem misconfigured verifier\n"); return -EINVAL; } regs[BPF_REG_0].map_ptr = meta.map_ptr; regs[BPF_REG_0].id = ++env->id_gen; insn_aux = &env->insn_aux_data[insn_idx]; if (!insn_aux->map_ptr) insn_aux->map_ptr = meta.map_ptr; else if (insn_aux->map_ptr != meta.map_ptr) insn_aux->map_ptr = BPF_MAP_PTR_POISON; } else { verbose(env, "unknown return type %d of func %s#%d\n", fn->ret_type, func_id_name(func_id), func_id); return -EINVAL; } err = check_map_func_compatibility(env, meta.map_ptr, func_id); if (err) return err; if (changes_data) clear_all_pkt_pointers(env); return 0; } static bool signed_add_overflows(s64 a, s64 b) { /* Do the add in u64, where overflow is well-defined */ s64 res = (s64)((u64)a + (u64)b); if (b < 0) return res > a; return res < a; } static bool signed_sub_overflows(s64 a, s64 b) { /* Do the sub in u64, where overflow is well-defined */ s64 res = (s64)((u64)a - (u64)b); if (b < 0) return res < a; return res > a; } /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. * Caller should also handle BPF_MOV case separately. * If we return -EACCES, caller may want to try again treating pointer as a * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. */ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg) { struct bpf_reg_state *regs = cur_regs(env), *dst_reg; bool known = tnum_is_const(off_reg->var_off); s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; u8 opcode = BPF_OP(insn->code); u32 dst = insn->dst_reg; dst_reg = &regs[dst]; if (WARN_ON_ONCE(known && (smin_val != smax_val))) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: known but bad sbounds\n"); return -EINVAL; } if (WARN_ON_ONCE(known && (umin_val != umax_val))) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: known but bad ubounds\n"); return -EINVAL; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops on pointers produce (meaningless) scalars */ if (!env->allow_ptr_leaks) verbose(env, "R%d 32-bit pointer arithmetic prohibited\n", dst); return -EACCES; } if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n", dst); return -EACCES; } if (ptr_reg->type == CONST_PTR_TO_MAP) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n", dst); return -EACCES; } if (ptr_reg->type == PTR_TO_PACKET_END) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n", dst); return -EACCES; } /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. * The id may be overwritten later if we create a new variable offset. */ dst_reg->type = ptr_reg->type; dst_reg->id = ptr_reg->id; switch (opcode) { case BPF_ADD: /* We can take a fixed offset as long as it doesn't overflow * the s32 'off' field */ if (known && (ptr_reg->off + smin_val == (s64)(s32)(ptr_reg->off + smin_val))) { /* pointer += K. Accumulate it into fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->off = ptr_reg->off + smin_val; dst_reg->range = ptr_reg->range; break; } /* A new variable offset is created. Note that off_reg->off * == 0, since it's a scalar. * dst_reg gets the pointer type and since some positive * integer value was added to the pointer, give it a new 'id' * if it's a PTR_TO_PACKET. * this creates a new 'base' pointer, off_reg (variable) gets * added into the variable offset, and we copy the fixed offset * from ptr_reg. */ if (signed_add_overflows(smin_ptr, smin_val) || signed_add_overflows(smax_ptr, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr + smin_val; dst_reg->smax_value = smax_ptr + smax_val; } if (umin_ptr + umin_val < umin_ptr || umax_ptr + umax_val < umax_ptr) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value = umin_ptr + umin_val; dst_reg->umax_value = umax_ptr + umax_val; } dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ dst_reg->range = 0; } break; case BPF_SUB: if (dst_reg == off_reg) { /* scalar -= pointer. Creates an unknown scalar */ if (!env->allow_ptr_leaks) verbose(env, "R%d tried to subtract pointer from scalar\n", dst); return -EACCES; } /* We don't allow subtraction from FP, because (according to * test_verifier.c test "invalid fp arithmetic", JITs might not * be able to deal with it. */ if (ptr_reg->type == PTR_TO_STACK) { if (!env->allow_ptr_leaks) verbose(env, "R%d subtraction from stack pointer prohibited\n", dst); return -EACCES; } if (known && (ptr_reg->off - smin_val == (s64)(s32)(ptr_reg->off - smin_val))) { /* pointer -= K. Subtract it from fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->id = ptr_reg->id; dst_reg->off = ptr_reg->off - smin_val; dst_reg->range = ptr_reg->range; break; } /* A new variable offset is created. If the subtrahend is known * nonnegative, then any reg->range we had before is still good. */ if (signed_sub_overflows(smin_ptr, smax_val) || signed_sub_overflows(smax_ptr, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr - smax_val; dst_reg->smax_value = smax_ptr - smin_val; } if (umin_ptr < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value = umin_ptr - umax_val; dst_reg->umax_value = umax_ptr - umin_val; } dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ if (smin_val < 0) dst_reg->range = 0; } break; case BPF_AND: case BPF_OR: case BPF_XOR: /* bitwise ops on pointers are troublesome, prohibit for now. * (However, in principle we could allow some cases, e.g. * ptr &= ~3 which would reduce min_value by 3.) */ if (!env->allow_ptr_leaks) verbose(env, "R%d bitwise operator %s on pointer prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; default: /* other operators (e.g. MUL,LSH) produce non-pointer results */ if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; } __update_reg_bounds(dst_reg); __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } /* WARNING: This function does calculations on 64-bit values, but the actual * execution may occur on 32-bit values. Therefore, things like bitshifts * need extra checks in the 32-bit case. */ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } if (src_known) dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; if (src_known) dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->32 */ coerce_reg_to_size(dst_reg, 4); coerce_reg_to_size(&src_reg, 4); } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max * and var_off. */ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg; struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; u8 opcode = BPF_OP(insn->code); int rc; dst_reg = &regs[insn->dst_reg]; src_reg = NULL; if (dst_reg->type != SCALAR_VALUE) ptr_reg = dst_reg; if (BPF_SRC(insn->code) == BPF_X) { src_reg = &regs[insn->src_reg]; if (src_reg->type != SCALAR_VALUE) { if (dst_reg->type != SCALAR_VALUE) { /* Combining two pointers by any ALU op yields * an arbitrary scalar. */ if (!env->allow_ptr_leaks) { verbose(env, "R%d pointer %s pointer prohibited\n", insn->dst_reg, bpf_alu_string[opcode >> 4]); return -EACCES; } mark_reg_unknown(env, regs, insn->dst_reg); return 0; } else { /* scalar += pointer * This is legal, but we have to reverse our * src/dest handling in computing the range */ rc = adjust_ptr_min_max_vals(env, insn, src_reg, dst_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* scalar += unknown scalar */ __mark_reg_unknown(&off_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, off_reg); } return rc; } } else if (ptr_reg) { /* pointer += scalar */ rc = adjust_ptr_min_max_vals(env, insn, dst_reg, src_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* unknown scalar += scalar */ __mark_reg_unknown(dst_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, *src_reg); } return rc; } } else { /* Pretend the src is a reg with a known value, since we only * need to be able to read from this state. */ off_reg.type = SCALAR_VALUE; __mark_reg_known(&off_reg, insn->imm); src_reg = &off_reg; if (ptr_reg) { /* pointer += K */ rc = adjust_ptr_min_max_vals(env, insn, ptr_reg, src_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* unknown scalar += K */ __mark_reg_unknown(dst_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, off_reg); } return rc; } } /* Got here implies adding two SCALAR_VALUEs */ if (WARN_ON_ONCE(ptr_reg)) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: unexpected ptr_reg\n"); return -EINVAL; } if (WARN_ON(!src_reg)) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: no src_reg\n"); return -EINVAL; } return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); } /* check validity of 32-bit and 64-bit arithmetic operations */ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); int err; if (opcode == BPF_END || opcode == BPF_NEG) { if (opcode == BPF_NEG) { if (BPF_SRC(insn->code) != 0 || insn->src_reg != BPF_REG_0 || insn->off != 0 || insn->imm != 0) { verbose(env, "BPF_NEG uses reserved fields\n"); return -EINVAL; } } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0 || (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || BPF_CLASS(insn->code) == BPF_ALU64) { verbose(env, "BPF_END uses reserved fields\n"); return -EINVAL; } } /* check src operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer arithmetic prohibited\n", insn->dst_reg); return -EACCES; } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; } else if (opcode == BPF_MOV) { if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose(env, "BPF_MOV uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose(env, "BPF_MOV uses reserved fields\n"); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; if (BPF_SRC(insn->code) == BPF_X) { if (BPF_CLASS(insn->code) == BPF_ALU64) { /* case: R1 = R2 * copy register state to dest reg */ regs[insn->dst_reg] = regs[insn->src_reg]; regs[insn->dst_reg].live |= REG_LIVE_WRITTEN; } else { /* R1 = (u32) R2 */ if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d partial copy of pointer\n", insn->src_reg); return -EACCES; } mark_reg_unknown(env, regs, insn->dst_reg); coerce_reg_to_size(&regs[insn->dst_reg], 4); } } else { /* case: R = imm * remember the value we stored into this reg */ regs[insn->dst_reg].type = SCALAR_VALUE; if (BPF_CLASS(insn->code) == BPF_ALU64) { __mark_reg_known(regs + insn->dst_reg, insn->imm); } else { __mark_reg_known(regs + insn->dst_reg, (u32)insn->imm); } } } else if (opcode > BPF_END) { verbose(env, "invalid BPF_ALU opcode %x\n", opcode); return -EINVAL; } else { /* all other ALU ops: and, sub, xor, add, ... */ if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose(env, "BPF_ALU uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose(env, "BPF_ALU uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if ((opcode == BPF_MOD || opcode == BPF_DIV) && BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { verbose(env, "div by zero\n"); return -EINVAL; } if ((opcode == BPF_LSH || opcode == BPF_RSH || opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; if (insn->imm < 0 || insn->imm >= size) { verbose(env, "invalid shift %d\n", insn->imm); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; return adjust_reg_min_max_vals(env, insn); } return 0; } static void find_good_pkt_pointers(struct bpf_verifier_state *state, struct bpf_reg_state *dst_reg, enum bpf_reg_type type, bool range_right_open) { struct bpf_reg_state *regs = state->regs, *reg; u16 new_range; int i; if (dst_reg->off < 0 || (dst_reg->off == 0 && range_right_open)) /* This doesn't give us any range */ return; if (dst_reg->umax_value > MAX_PACKET_OFF || dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) /* Risk of overflow. For instance, ptr + (1<<63) may be less * than pkt_end, but that's because it's also less than pkt. */ return; new_range = dst_reg->off; if (range_right_open) new_range--; /* Examples for register markings: * * pkt_data in dst register: * * r2 = r3; * r2 += 8; * if (r2 > pkt_end) goto <handle exception> * <access okay> * * r2 = r3; * r2 += 8; * if (r2 < pkt_end) goto <access okay> * <handle exception> * * Where: * r2 == dst_reg, pkt_end == src_reg * r2=pkt(id=n,off=8,r=0) * r3=pkt(id=n,off=0,r=0) * * pkt_data in src register: * * r2 = r3; * r2 += 8; * if (pkt_end >= r2) goto <access okay> * <handle exception> * * r2 = r3; * r2 += 8; * if (pkt_end <= r2) goto <handle exception> * <access okay> * * Where: * pkt_end == dst_reg, r2 == src_reg * r2=pkt(id=n,off=8,r=0) * r3=pkt(id=n,off=0,r=0) * * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) * and [r3, r3 + 8-1) respectively is safe to access depending on * the check. */ /* If our ids match, then we must have the same max_value. And we * don't care about the other reg's fixed offset, since if it's too big * the range won't allow anything. * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. */ for (i = 0; i < MAX_BPF_REG; i++) if (regs[i].type == type && regs[i].id == dst_reg->id) /* keep the maximum range already checked */ regs[i].range = max(regs[i].range, new_range); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; reg = &state->stack[i].spilled_ptr; if (reg->type == type && reg->id == dst_reg->id) reg->range = max(reg->range, new_range); } } /* Adjusts the register min/max values in the case that the dst_reg is the * variable register that we are working on, and src_reg is a constant or we're * simply doing a BPF_K check. * In JEQ/JNE cases we also adjust the var_off values. */ static void reg_set_min_max(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { /* If the dst_reg is a pointer, we can't learn anything about its * variable offset from the compare (unless src_reg were a pointer into * the same object, but we don't bother with that. * Since false_reg and true_reg have the same type by construction, we * only need to check one of them for pointerness. */ if (__is_pointer_value(false, false_reg)) return; switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ __mark_reg_known(true_reg, val); break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ __mark_reg_known(false_reg, val); break; case BPF_JGT: false_reg->umax_value = min(false_reg->umax_value, val); true_reg->umin_value = max(true_reg->umin_value, val + 1); break; case BPF_JSGT: false_reg->smax_value = min_t(s64, false_reg->smax_value, val); true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); break; case BPF_JLT: false_reg->umin_value = max(false_reg->umin_value, val); true_reg->umax_value = min(true_reg->umax_value, val - 1); break; case BPF_JSLT: false_reg->smin_value = max_t(s64, false_reg->smin_value, val); true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); break; case BPF_JGE: false_reg->umax_value = min(false_reg->umax_value, val - 1); true_reg->umin_value = max(true_reg->umin_value, val); break; case BPF_JSGE: false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); true_reg->smin_value = max_t(s64, true_reg->smin_value, val); break; case BPF_JLE: false_reg->umin_value = max(false_reg->umin_value, val + 1); true_reg->umax_value = min(true_reg->umax_value, val); break; case BPF_JSLE: false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); true_reg->smax_value = min_t(s64, true_reg->smax_value, val); break; default: break; } __reg_deduce_bounds(false_reg); __reg_deduce_bounds(true_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(false_reg); __reg_bound_offset(true_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(false_reg); __update_reg_bounds(true_reg); } /* Same as above, but for the case that dst_reg holds a constant and src_reg is * the variable reg. */ static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { if (__is_pointer_value(false, false_reg)) return; switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ __mark_reg_known(true_reg, val); break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ __mark_reg_known(false_reg, val); break; case BPF_JGT: true_reg->umax_value = min(true_reg->umax_value, val - 1); false_reg->umin_value = max(false_reg->umin_value, val); break; case BPF_JSGT: true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); false_reg->smin_value = max_t(s64, false_reg->smin_value, val); break; case BPF_JLT: true_reg->umin_value = max(true_reg->umin_value, val + 1); false_reg->umax_value = min(false_reg->umax_value, val); break; case BPF_JSLT: true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); false_reg->smax_value = min_t(s64, false_reg->smax_value, val); break; case BPF_JGE: true_reg->umax_value = min(true_reg->umax_value, val); false_reg->umin_value = max(false_reg->umin_value, val + 1); break; case BPF_JSGE: true_reg->smax_value = min_t(s64, true_reg->smax_value, val); false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); break; case BPF_JLE: true_reg->umin_value = max(true_reg->umin_value, val); false_reg->umax_value = min(false_reg->umax_value, val - 1); break; case BPF_JSLE: true_reg->smin_value = max_t(s64, true_reg->smin_value, val); false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); break; default: break; } __reg_deduce_bounds(false_reg); __reg_deduce_bounds(true_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(false_reg); __reg_bound_offset(true_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(false_reg); __update_reg_bounds(true_reg); } /* Regs are known to be equal, so intersect their min/max/var_off */ static void __reg_combine_min_max(struct bpf_reg_state *src_reg, struct bpf_reg_state *dst_reg) { src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, dst_reg->umin_value); src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, dst_reg->umax_value); src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, dst_reg->smin_value); src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, dst_reg->smax_value); src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, dst_reg->var_off); /* We might have learned new bounds from the var_off. */ __update_reg_bounds(src_reg); __update_reg_bounds(dst_reg); /* We might have learned something about the sign bit. */ __reg_deduce_bounds(src_reg); __reg_deduce_bounds(dst_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(src_reg); __reg_bound_offset(dst_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(src_reg); __update_reg_bounds(dst_reg); } static void reg_combine_min_max(struct bpf_reg_state *true_src, struct bpf_reg_state *true_dst, struct bpf_reg_state *false_src, struct bpf_reg_state *false_dst, u8 opcode) { switch (opcode) { case BPF_JEQ: __reg_combine_min_max(true_src, true_dst); break; case BPF_JNE: __reg_combine_min_max(false_src, false_dst); break; } } static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id, bool is_null) { struct bpf_reg_state *reg = &regs[regno]; if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) { /* Old offset (both fixed and variable parts) should * have been known-zero, because we don't allow pointer * arithmetic on pointers that might be NULL. */ if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0) || reg->off)) { __mark_reg_known_zero(reg); reg->off = 0; } if (is_null) { reg->type = SCALAR_VALUE; } else if (reg->map_ptr->inner_map_meta) { reg->type = CONST_PTR_TO_MAP; reg->map_ptr = reg->map_ptr->inner_map_meta; } else { reg->type = PTR_TO_MAP_VALUE; } /* We don't need id from this point onwards anymore, thus we * should better reset it, so that state pruning has chances * to take effect. */ reg->id = 0; } } /* The logic is similar to find_good_pkt_pointers(), both could eventually * be folded together at some point. */ static void mark_map_regs(struct bpf_verifier_state *state, u32 regno, bool is_null) { struct bpf_reg_state *regs = state->regs; u32 id = regs[regno].id; int i; for (i = 0; i < MAX_BPF_REG; i++) mark_map_reg(regs, i, id, is_null); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null); } } static bool try_match_pkt_pointers(const struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg, struct bpf_verifier_state *this_branch, struct bpf_verifier_state *other_branch) { if (BPF_SRC(insn->code) != BPF_X) return false; switch (BPF_OP(insn->code)) { case BPF_JGT: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ find_good_pkt_pointers(this_branch, dst_reg, dst_reg->type, false); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end > pkt_data', pkt_data > pkt_meta' */ find_good_pkt_pointers(other_branch, src_reg, src_reg->type, true); } else { return false; } break; case BPF_JLT: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ find_good_pkt_pointers(other_branch, dst_reg, dst_reg->type, true); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end < pkt_data', pkt_data > pkt_meta' */ find_good_pkt_pointers(this_branch, src_reg, src_reg->type, false); } else { return false; } break; case BPF_JGE: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ find_good_pkt_pointers(this_branch, dst_reg, dst_reg->type, true); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ find_good_pkt_pointers(other_branch, src_reg, src_reg->type, false); } else { return false; } break; case BPF_JLE: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ find_good_pkt_pointers(other_branch, dst_reg, dst_reg->type, false); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ find_good_pkt_pointers(this_branch, src_reg, src_reg->type, true); } else { return false; } break; default: return false; } return true; } static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct bpf_verifier_state *other_branch, *this_branch = env->cur_state; struct bpf_reg_state *regs = this_branch->regs, *dst_reg; u8 opcode = BPF_OP(insn->code); int err; if (opcode > BPF_JSLE) { verbose(env, "invalid BPF_JMP opcode %x\n", opcode); return -EINVAL; } if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->src_reg); return -EACCES; } } else { if (insn->src_reg != BPF_REG_0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg = &regs[insn->dst_reg]; /* detect if R == 0 where R was initialized to zero earlier */ if (BPF_SRC(insn->code) == BPF_K && (opcode == BPF_JEQ || opcode == BPF_JNE) && dst_reg->type == SCALAR_VALUE && tnum_equals_const(dst_reg->var_off, insn->imm)) { if (opcode == BPF_JEQ) { /* if (imm == imm) goto pc+off; * only follow the goto, ignore fall-through */ *insn_idx += insn->off; return 0; } else { /* if (imm != imm) goto pc+off; * only follow fall-through branch, since * that's where the program will go */ return 0; } } other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx); if (!other_branch) return -EFAULT; /* detect if we are comparing against a constant value so we can adjust * our min/max values for our dst register. * this is only legit if both are scalars (or pointers to the same * object, I suppose, but we don't support that right now), because * otherwise the different base pointers mean the offsets aren't * comparable. */ if (BPF_SRC(insn->code) == BPF_X) { if (dst_reg->type == SCALAR_VALUE && regs[insn->src_reg].type == SCALAR_VALUE) { if (tnum_is_const(regs[insn->src_reg].var_off)) reg_set_min_max(&other_branch->regs[insn->dst_reg], dst_reg, regs[insn->src_reg].var_off.value, opcode); else if (tnum_is_const(dst_reg->var_off)) reg_set_min_max_inv(&other_branch->regs[insn->src_reg], &regs[insn->src_reg], dst_reg->var_off.value, opcode); else if (opcode == BPF_JEQ || opcode == BPF_JNE) /* Comparing for equality, we can combine knowledge */ reg_combine_min_max(&other_branch->regs[insn->src_reg], &other_branch->regs[insn->dst_reg], &regs[insn->src_reg], &regs[insn->dst_reg], opcode); } } else if (dst_reg->type == SCALAR_VALUE) { reg_set_min_max(&other_branch->regs[insn->dst_reg], dst_reg, insn->imm, opcode); } /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ if (BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { /* Mark all identical map registers in each branch as either * safe or unknown depending R == 0 or R != 0 conditional. */ mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg], this_branch, other_branch) && is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->dst_reg); return -EACCES; } if (env->log.level) print_verifier_state(env, this_branch); return 0; } /* return the map pointer stored inside BPF_LD_IMM64 instruction */ static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn) { u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32; return (struct bpf_map *) (unsigned long) imm64; } /* verify BPF_LD_IMM64 instruction */ static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); int err; if (BPF_SIZE(insn->code) != BPF_DW) { verbose(env, "invalid BPF_LD_IMM insn\n"); return -EINVAL; } if (insn->off != 0) { verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); return -EINVAL; } err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; if (insn->src_reg == 0) { u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; regs[insn->dst_reg].type = SCALAR_VALUE; __mark_reg_known(&regs[insn->dst_reg], imm); return 0; } /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */ BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD); regs[insn->dst_reg].type = CONST_PTR_TO_MAP; regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn); return 0; } static bool may_access_skb(enum bpf_prog_type type) { switch (type) { case BPF_PROG_TYPE_SOCKET_FILTER: case BPF_PROG_TYPE_SCHED_CLS: case BPF_PROG_TYPE_SCHED_ACT: return true; default: return false; } } /* verify safety of LD_ABS|LD_IND instructions: * - they can only appear in the programs where ctx == skb * - since they are wrappers of function calls, they scratch R1-R5 registers, * preserve R6-R9, and store return value into R0 * * Implicit input: * ctx == skb == R6 == CTX * * Explicit input: * SRC == any register * IMM == 32-bit immediate * * Output: * R0 - 8/16/32-bit skb data converted to cpu endianness */ static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); u8 mode = BPF_MODE(insn->code); int i, err; if (!may_access_skb(env->prog->type)) { verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); return -EINVAL; } if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || BPF_SIZE(insn->code) == BPF_DW || (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); return -EINVAL; } /* check whether implicit source operand (register R6) is readable */ err = check_reg_arg(env, BPF_REG_6, SRC_OP); if (err) return err; if (regs[BPF_REG_6].type != PTR_TO_CTX) { verbose(env, "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); return -EINVAL; } if (mode == BPF_IND) { /* check explicit source operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } /* reset caller saved regs to unreadable */ for (i = 0; i < CALLER_SAVED_REGS; i++) { mark_reg_not_init(env, regs, caller_saved[i]); check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); } /* mark destination R0 register as readable, since it contains * the value fetched from the packet. * Already marked as written above. */ mark_reg_unknown(env, regs, BPF_REG_0); return 0; } static int check_return_code(struct bpf_verifier_env *env) { struct bpf_reg_state *reg; struct tnum range = tnum_range(0, 1); switch (env->prog->type) { case BPF_PROG_TYPE_CGROUP_SKB: case BPF_PROG_TYPE_CGROUP_SOCK: case BPF_PROG_TYPE_SOCK_OPS: case BPF_PROG_TYPE_CGROUP_DEVICE: break; default: return 0; } reg = cur_regs(env) + BPF_REG_0; if (reg->type != SCALAR_VALUE) { verbose(env, "At program exit the register R0 is not a known value (%s)\n", reg_type_str[reg->type]); return -EINVAL; } if (!tnum_in(range, reg->var_off)) { verbose(env, "At program exit the register R0 "); if (!tnum_is_unknown(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "has value %s", tn_buf); } else { verbose(env, "has unknown scalar value"); } verbose(env, " should have been 0 or 1\n"); return -EINVAL; } return 0; } /* non-recursive DFS pseudo code * 1 procedure DFS-iterative(G,v): * 2 label v as discovered * 3 let S be a stack * 4 S.push(v) * 5 while S is not empty * 6 t <- S.pop() * 7 if t is what we're looking for: * 8 return t * 9 for all edges e in G.adjacentEdges(t) do * 10 if edge e is already labelled * 11 continue with the next edge * 12 w <- G.adjacentVertex(t,e) * 13 if vertex w is not discovered and not explored * 14 label e as tree-edge * 15 label w as discovered * 16 S.push(w) * 17 continue at 5 * 18 else if vertex w is discovered * 19 label e as back-edge * 20 else * 21 // vertex w is explored * 22 label e as forward- or cross-edge * 23 label t as explored * 24 S.pop() * * convention: * 0x10 - discovered * 0x11 - discovered and fall-through edge labelled * 0x12 - discovered and fall-through and branch edges labelled * 0x20 - explored */ enum { DISCOVERED = 0x10, EXPLORED = 0x20, FALLTHROUGH = 1, BRANCH = 2, }; #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L) static int *insn_stack; /* stack of insns to process */ static int cur_stack; /* current stack index */ static int *insn_state; /* t, w, e - match pseudo-code above: * t - index of current instruction * w - next instruction * e - edge */ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) { if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) return 0; if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) return 0; if (w < 0 || w >= env->prog->len) { verbose(env, "jump out of range from insn %d to %d\n", t, w); return -EINVAL; } if (e == BRANCH) /* mark branch target for state pruning */ env->explored_states[w] = STATE_LIST_MARK; if (insn_state[w] == 0) { /* tree-edge */ insn_state[t] = DISCOVERED | e; insn_state[w] = DISCOVERED; if (cur_stack >= env->prog->len) return -E2BIG; insn_stack[cur_stack++] = w; return 1; } else if ((insn_state[w] & 0xF0) == DISCOVERED) { verbose(env, "back-edge from insn %d to %d\n", t, w); return -EINVAL; } else if (insn_state[w] == EXPLORED) { /* forward- or cross-edge */ insn_state[t] = DISCOVERED | e; } else { verbose(env, "insn state internal bug\n"); return -EFAULT; } return 0; } /* non-recursive depth-first-search to detect loops in BPF program * loop == back-edge in directed graph */ static int check_cfg(struct bpf_verifier_env *env) { struct bpf_insn *insns = env->prog->insnsi; int insn_cnt = env->prog->len; int ret = 0; int i, t; insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); if (!insn_state) return -ENOMEM; insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); if (!insn_stack) { kfree(insn_state); return -ENOMEM; } insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ insn_stack[0] = 0; /* 0 is the first instruction */ cur_stack = 1; peek_stack: if (cur_stack == 0) goto check_state; t = insn_stack[cur_stack - 1]; if (BPF_CLASS(insns[t].code) == BPF_JMP) { u8 opcode = BPF_OP(insns[t].code); if (opcode == BPF_EXIT) { goto mark_explored; } else if (opcode == BPF_CALL) { ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; if (t + 1 < insn_cnt) env->explored_states[t + 1] = STATE_LIST_MARK; } else if (opcode == BPF_JA) { if (BPF_SRC(insns[t].code) != BPF_K) { ret = -EINVAL; goto err_free; } /* unconditional jump with single edge */ ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; /* tell verifier to check for equivalent states * after every call and jump */ if (t + 1 < insn_cnt) env->explored_states[t + 1] = STATE_LIST_MARK; } else { /* conditional jump with two edges */ env->explored_states[t] = STATE_LIST_MARK; ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; ret = push_insn(t, t + insns[t].off + 1, BRANCH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; } } else { /* all other non-branch instructions with single * fall-through edge */ ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; } mark_explored: insn_state[t] = EXPLORED; if (cur_stack-- <= 0) { verbose(env, "pop stack internal bug\n"); ret = -EFAULT; goto err_free; } goto peek_stack; check_state: for (i = 0; i < insn_cnt; i++) { if (insn_state[i] != EXPLORED) { verbose(env, "unreachable insn %d\n", i); ret = -EINVAL; goto err_free; } } ret = 0; /* cfg looks good */ err_free: kfree(insn_state); kfree(insn_stack); return ret; } /* check %cur's range satisfies %old's */ static bool range_within(struct bpf_reg_state *old, struct bpf_reg_state *cur) { return old->umin_value <= cur->umin_value && old->umax_value >= cur->umax_value && old->smin_value <= cur->smin_value && old->smax_value >= cur->smax_value; } /* Maximum number of register states that can exist at once */ #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) struct idpair { u32 old; u32 cur; }; /* If in the old state two registers had the same id, then they need to have * the same id in the new state as well. But that id could be different from * the old state, so we need to track the mapping from old to new ids. * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent * regs with old id 5 must also have new id 9 for the new state to be safe. But * regs with a different old id could still have new id 9, we don't care about * that. * So we look through our idmap to see if this old id has been seen before. If * so, we require the new id to match; otherwise, we add the id pair to the map. */ static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap) { unsigned int i; for (i = 0; i < ID_MAP_SIZE; i++) { if (!idmap[i].old) { /* Reached an empty slot; haven't seen this id before */ idmap[i].old = old_id; idmap[i].cur = cur_id; return true; } if (idmap[i].old == old_id) return idmap[i].cur == cur_id; } /* We ran out of idmap slots, which should be impossible */ WARN_ON_ONCE(1); return false; } /* Returns true if (rold safe implies rcur safe) */ static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, struct idpair *idmap) { if (!(rold->live & REG_LIVE_READ)) /* explored state didn't use this */ return true; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0) return true; if (rold->type == NOT_INIT) /* explored state can't have used this */ return true; if (rcur->type == NOT_INIT) return false; switch (rold->type) { case SCALAR_VALUE: if (rcur->type == SCALAR_VALUE) { /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); } else { /* if we knew anything about the old value, we're not * equal, because we can't know anything about the * scalar value of the pointer in the new value. */ return rold->umin_value == 0 && rold->umax_value == U64_MAX && rold->smin_value == S64_MIN && rold->smax_value == S64_MAX && tnum_is_unknown(rold->var_off); } case PTR_TO_MAP_VALUE: /* If the new min/max/var_off satisfy the old ones and * everything else matches, we are OK. * We don't care about the 'id' value, because nothing * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) */ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_MAP_VALUE_OR_NULL: /* a PTR_TO_MAP_VALUE could be safe to use as a * PTR_TO_MAP_VALUE_OR_NULL into the same map. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- * checked, doing so could have affected others with the same * id, and we can't check for that because we lost the id when * we converted to a PTR_TO_MAP_VALUE. */ if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) return false; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) return false; /* Check our ids match any regs they're supposed to */ return check_ids(rold->id, rcur->id, idmap); case PTR_TO_PACKET_META: case PTR_TO_PACKET: if (rcur->type != rold->type) return false; /* We must have at least as much range as the old ptr * did, so that any accesses which were safe before are * still safe. This is true even if old range < old off, * since someone could have accessed through (ptr - k), or * even done ptr -= k in a register, to get a safe access. */ if (rold->range > rcur->range) return false; /* If the offsets don't match, we can't trust our alignment; * nor can we be sure that we won't fall out of range. */ if (rold->off != rcur->off) return false; /* id relations must be preserved */ if (rold->id && !check_ids(rold->id, rcur->id, idmap)) return false; /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_CTX: case CONST_PTR_TO_MAP: case PTR_TO_STACK: case PTR_TO_PACKET_END: /* Only valid matches are exact, which memcmp() above * would have accepted */ default: /* Don't know what's going on, just say it's not safe */ return false; } /* Shouldn't get here; if we do, say it's not safe */ WARN_ON_ONCE(1); return false; } static bool stacksafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur, struct idpair *idmap) { int i, spi; /* if explored stack has more populated slots than current stack * such stacks are not equivalent */ if (old->allocated_stack > cur->allocated_stack) return false; /* walk slots of the explored stack and ignore any additional * slots in the current stack, since explored(safe) state * didn't use them */ for (i = 0; i < old->allocated_stack; i++) { spi = i / BPF_REG_SIZE; if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) continue; if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != cur->stack[spi].slot_type[i % BPF_REG_SIZE]) /* Ex: old explored (safe) state has STACK_SPILL in * this stack slot, but current has has STACK_MISC -> * this verifier states are not equivalent, * return false to continue verification of this path */ return false; if (i % BPF_REG_SIZE) continue; if (old->stack[spi].slot_type[0] != STACK_SPILL) continue; if (!regsafe(&old->stack[spi].spilled_ptr, &cur->stack[spi].spilled_ptr, idmap)) /* when explored and current stack slot are both storing * spilled registers, check that stored pointers types * are the same as well. * Ex: explored safe path could have stored * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} * but current path has stored: * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} * such verifier states are not equivalent. * return false to continue verification of this path */ return false; } return true; } /* compare two verifier states * * all states stored in state_list are known to be valid, since * verifier reached 'bpf_exit' instruction through them * * this function is called when verifier exploring different branches of * execution popped from the state stack. If it sees an old state that has * more strict register state and more strict stack state then this execution * branch doesn't need to be explored further, since verifier already * concluded that more strict state leads to valid finish. * * Therefore two states are equivalent if register state is more conservative * and explored stack state is more conservative than the current one. * Example: * explored current * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) * * In other words if current stack state (one being explored) has more * valid slots than old one that already passed validation, it means * the verifier can stop exploring and conclude that current state is valid too * * Similarly with registers. If explored state has register type as invalid * whereas register type in current state is meaningful, it means that * the current state will reach 'bpf_exit' instruction safely */ static bool states_equal(struct bpf_verifier_env *env, struct bpf_verifier_state *old, struct bpf_verifier_state *cur) { struct idpair *idmap; bool ret = false; int i; idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL); /* If we failed to allocate the idmap, just say it's not safe */ if (!idmap) return false; for (i = 0; i < MAX_BPF_REG; i++) { if (!regsafe(&old->regs[i], &cur->regs[i], idmap)) goto out_free; } if (!stacksafe(old, cur, idmap)) goto out_free; ret = true; out_free: kfree(idmap); return ret; } /* A write screens off any subsequent reads; but write marks come from the * straight-line code between a state and its parent. When we arrive at a * jump target (in the first iteration of the propagate_liveness() loop), * we didn't arrive by the straight-line code, so read marks in state must * propagate to parent regardless of state's write marks. */ static bool do_propagate_liveness(const struct bpf_verifier_state *state, struct bpf_verifier_state *parent) { bool writes = parent == state->parent; /* Observe write marks */ bool touched = false; /* any changes made? */ int i; if (!parent) return touched; /* Propagate read liveness of registers... */ BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); /* We don't need to worry about FP liveness because it's read-only */ for (i = 0; i < BPF_REG_FP; i++) { if (parent->regs[i].live & REG_LIVE_READ) continue; if (writes && (state->regs[i].live & REG_LIVE_WRITTEN)) continue; if (state->regs[i].live & REG_LIVE_READ) { parent->regs[i].live |= REG_LIVE_READ; touched = true; } } /* ... and stack slots */ for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && i < parent->allocated_stack / BPF_REG_SIZE; i++) { if (parent->stack[i].slot_type[0] != STACK_SPILL) continue; if (state->stack[i].slot_type[0] != STACK_SPILL) continue; if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ) continue; if (writes && (state->stack[i].spilled_ptr.live & REG_LIVE_WRITTEN)) continue; if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) { parent->stack[i].spilled_ptr.live |= REG_LIVE_READ; touched = true; } } return touched; } /* "parent" is "a state from which we reach the current state", but initially * it is not the state->parent (i.e. "the state whose straight-line code leads * to the current state"), instead it is the state that happened to arrive at * a (prunable) equivalent of the current state. See comment above * do_propagate_liveness() for consequences of this. * This function is just a more efficient way of calling mark_reg_read() or * mark_stack_slot_read() on each reg in "parent" that is read in "state", * though it requires that parent != state->parent in the call arguments. */ static void propagate_liveness(const struct bpf_verifier_state *state, struct bpf_verifier_state *parent) { while (do_propagate_liveness(state, parent)) { /* Something changed, so we need to feed those changes onward */ state = parent; parent = state->parent; } } static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) { struct bpf_verifier_state_list *new_sl; struct bpf_verifier_state_list *sl; struct bpf_verifier_state *cur = env->cur_state; int i, err; sl = env->explored_states[insn_idx]; if (!sl) /* this 'insn_idx' instruction wasn't marked, so we will not * be doing state search here */ return 0; while (sl != STATE_LIST_MARK) { if (states_equal(env, &sl->state, cur)) { /* reached equivalent register/stack state, * prune the search. * Registers read by the continuation are read by us. * If we have any write marks in env->cur_state, they * will prevent corresponding reads in the continuation * from reaching our parent (an explored_state). Our * own state will get the read marks recorded, but * they'll be immediately forgotten as we're pruning * this state and will pop a new one. */ propagate_liveness(&sl->state, cur); return 1; } sl = sl->next; } /* there were no equivalent states, remember current one. * technically the current state is not proven to be safe yet, * but it will either reach bpf_exit (which means it's safe) or * it will be rejected. Since there are no loops, we won't be * seeing this 'insn_idx' instruction again on the way to bpf_exit */ new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); if (!new_sl) return -ENOMEM; /* add new state to the head of linked list */ err = copy_verifier_state(&new_sl->state, cur); if (err) { free_verifier_state(&new_sl->state, false); kfree(new_sl); return err; } new_sl->next = env->explored_states[insn_idx]; env->explored_states[insn_idx] = new_sl; /* connect new state to parentage chain */ cur->parent = &new_sl->state; /* clear write marks in current state: the writes we did are not writes * our child did, so they don't screen off its reads from us. * (There are no read marks in current state, because reads always mark * their parent and current state never has children yet. Only * explored_states can get read marks.) */ for (i = 0; i < BPF_REG_FP; i++) cur->regs[i].live = REG_LIVE_NONE; for (i = 0; i < cur->allocated_stack / BPF_REG_SIZE; i++) if (cur->stack[i].slot_type[0] == STACK_SPILL) cur->stack[i].spilled_ptr.live = REG_LIVE_NONE; return 0; } static int ext_analyzer_insn_hook(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { if (env->dev_ops && env->dev_ops->insn_hook) return env->dev_ops->insn_hook(env, insn_idx, prev_insn_idx); return 0; } static int do_check(struct bpf_verifier_env *env) { struct bpf_verifier_state *state; struct bpf_insn *insns = env->prog->insnsi; struct bpf_reg_state *regs; int insn_cnt = env->prog->len; int insn_idx, prev_insn_idx = 0; int insn_processed = 0; bool do_print_state = false; state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); if (!state) return -ENOMEM; env->cur_state = state; init_reg_state(env, state->regs); state->parent = NULL; insn_idx = 0; for (;;) { struct bpf_insn *insn; u8 class; int err; if (insn_idx >= insn_cnt) { verbose(env, "invalid insn idx %d insn_cnt %d\n", insn_idx, insn_cnt); return -EFAULT; } insn = &insns[insn_idx]; class = BPF_CLASS(insn->code); if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { verbose(env, "BPF program is too large. Processed %d insn\n", insn_processed); return -E2BIG; } err = is_state_visited(env, insn_idx); if (err < 0) return err; if (err == 1) { /* found equivalent state, can prune the search */ if (env->log.level) { if (do_print_state) verbose(env, "\nfrom %d to %d: safe\n", prev_insn_idx, insn_idx); else verbose(env, "%d: safe\n", insn_idx); } goto process_bpf_exit; } if (need_resched()) cond_resched(); if (env->log.level > 1 || (env->log.level && do_print_state)) { if (env->log.level > 1) verbose(env, "%d:", insn_idx); else verbose(env, "\nfrom %d to %d:", prev_insn_idx, insn_idx); print_verifier_state(env, state); do_print_state = false; } if (env->log.level) { verbose(env, "%d: ", insn_idx); print_bpf_insn(verbose, env, insn, env->allow_ptr_leaks); } err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx); if (err) return err; regs = cur_regs(env); env->insn_aux_data[insn_idx].seen = true; if (class == BPF_ALU || class == BPF_ALU64) { err = check_alu_op(env, insn); if (err) return err; } else if (class == BPF_LDX) { enum bpf_reg_type *prev_src_type, src_reg_type; /* check for reserved fields is already done */ /* check src operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; src_reg_type = regs[insn->src_reg].type; /* check that memory (src_reg + off) is readable, * the state of dst_reg will be updated by this func */ err = check_mem_access(env, insn_idx, insn->src_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, insn->dst_reg); if (err) return err; prev_src_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_src_type == NOT_INIT) { /* saw a valid insn * dst_reg = *(u32 *)(src_reg + off) * save type to validate intersecting paths */ *prev_src_type = src_reg_type; } else if (src_reg_type != *prev_src_type && (src_reg_type == PTR_TO_CTX || *prev_src_type == PTR_TO_CTX)) { /* ABuser program is trying to use the same insn * dst_reg = *(u32*) (src_reg + off) * with different pointer types: * src_reg == ctx in one branch and * src_reg == stack|map in some other branch. * Reject it. */ verbose(env, "same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_STX) { enum bpf_reg_type *prev_dst_type, dst_reg_type; if (BPF_MODE(insn->code) == BPF_XADD) { err = check_xadd(env, insn_idx, insn); if (err) return err; insn_idx++; continue; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg_type = regs[insn->dst_reg].type; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg); if (err) return err; prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_dst_type == NOT_INIT) { *prev_dst_type = dst_reg_type; } else if (dst_reg_type != *prev_dst_type && (dst_reg_type == PTR_TO_CTX || *prev_dst_type == PTR_TO_CTX)) { verbose(env, "same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_ST) { if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { verbose(env, "BPF_ST uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); if (err) return err; } else if (class == BPF_JMP) { u8 opcode = BPF_OP(insn->code); if (opcode == BPF_CALL) { if (BPF_SRC(insn->code) != BPF_K || insn->off != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_CALL uses reserved fields\n"); return -EINVAL; } err = check_call(env, insn->imm, insn_idx); if (err) return err; } else if (opcode == BPF_JA) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_JA uses reserved fields\n"); return -EINVAL; } insn_idx += insn->off + 1; continue; } else if (opcode == BPF_EXIT) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_EXIT uses reserved fields\n"); return -EINVAL; } /* eBPF calling convetion is such that R0 is used * to return the value from eBPF program. * Make sure that it's readable at this time * of bpf_exit, which means that program wrote * something into it earlier */ err = check_reg_arg(env, BPF_REG_0, SRC_OP); if (err) return err; if (is_pointer_value(env, BPF_REG_0)) { verbose(env, "R0 leaks addr as return value\n"); return -EACCES; } err = check_return_code(env); if (err) return err; process_bpf_exit: err = pop_stack(env, &prev_insn_idx, &insn_idx); if (err < 0) { if (err != -ENOENT) return err; break; } else { do_print_state = true; continue; } } else { err = check_cond_jmp_op(env, insn, &insn_idx); if (err) return err; } } else if (class == BPF_LD) { u8 mode = BPF_MODE(insn->code); if (mode == BPF_ABS || mode == BPF_IND) { err = check_ld_abs(env, insn); if (err) return err; } else if (mode == BPF_IMM) { err = check_ld_imm(env, insn); if (err) return err; insn_idx++; env->insn_aux_data[insn_idx].seen = true; } else { verbose(env, "invalid BPF_LD mode\n"); return -EINVAL; } } else { verbose(env, "unknown insn class %d\n", class); return -EINVAL; } insn_idx++; } verbose(env, "processed %d insns, stack depth %d\n", insn_processed, env->prog->aux->stack_depth); return 0; } static int check_map_prealloc(struct bpf_map *map) { return (map->map_type != BPF_MAP_TYPE_HASH && map->map_type != BPF_MAP_TYPE_PERCPU_HASH && map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || !(map->map_flags & BPF_F_NO_PREALLOC); } static int check_map_prog_compatibility(struct bpf_verifier_env *env, struct bpf_map *map, struct bpf_prog *prog) { /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use * preallocated hash maps, since doing memory allocation * in overflow_handler can crash depending on where nmi got * triggered. */ if (prog->type == BPF_PROG_TYPE_PERF_EVENT) { if (!check_map_prealloc(map)) { verbose(env, "perf_event programs can only use preallocated hash map\n"); return -EINVAL; } if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta)) { verbose(env, "perf_event programs can only use preallocated inner hash map\n"); return -EINVAL; } } return 0; } /* look for pseudo eBPF instructions that access map FDs and * replace them with actual map pointers */ static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i, j, err; err = bpf_prog_calc_tag(env->prog); if (err) return err; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) == BPF_LDX && (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { verbose(env, "BPF_LDX uses reserved fields\n"); return -EINVAL; } if (BPF_CLASS(insn->code) == BPF_STX && ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { verbose(env, "BPF_STX uses reserved fields\n"); return -EINVAL; } if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { struct bpf_map *map; struct fd f; if (i == insn_cnt - 1 || insn[1].code != 0 || insn[1].dst_reg != 0 || insn[1].src_reg != 0 || insn[1].off != 0) { verbose(env, "invalid bpf_ld_imm64 insn\n"); return -EINVAL; } if (insn->src_reg == 0) /* valid generic load 64-bit imm */ goto next_insn; if (insn->src_reg != BPF_PSEUDO_MAP_FD) { verbose(env, "unrecognized bpf_ld_imm64 insn\n"); return -EINVAL; } f = fdget(insn->imm); map = __bpf_map_get(f); if (IS_ERR(map)) { verbose(env, "fd %d is not pointing to valid bpf_map\n", insn->imm); return PTR_ERR(map); } err = check_map_prog_compatibility(env, map, env->prog); if (err) { fdput(f); return err; } /* store map pointer inside BPF_LD_IMM64 instruction */ insn[0].imm = (u32) (unsigned long) map; insn[1].imm = ((u64) (unsigned long) map) >> 32; /* check whether we recorded this map already */ for (j = 0; j < env->used_map_cnt; j++) if (env->used_maps[j] == map) { fdput(f); goto next_insn; } if (env->used_map_cnt >= MAX_USED_MAPS) { fdput(f); return -E2BIG; } /* hold the map. If the program is rejected by verifier, * the map will be released by release_maps() or it * will be used by the valid program until it's unloaded * and all maps are released in free_bpf_prog_info() */ map = bpf_map_inc(map, false); if (IS_ERR(map)) { fdput(f); return PTR_ERR(map); } env->used_maps[env->used_map_cnt++] = map; fdput(f); next_insn: insn++; i++; } } /* now all pseudo BPF_LD_IMM64 instructions load valid * 'struct bpf_map *' into a register instead of user map_fd. * These pointers will be used later by verifier to validate map access. */ return 0; } /* drop refcnt of maps used by the rejected program */ static void release_maps(struct bpf_verifier_env *env) { int i; for (i = 0; i < env->used_map_cnt; i++) bpf_map_put(env->used_maps[i]); } /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i; for (i = 0; i < insn_cnt; i++, insn++) if (insn->code == (BPF_LD | BPF_IMM | BPF_DW)) insn->src_reg = 0; } /* single env->prog->insni[off] instruction was replaced with the range * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying * [0, off) and [off, end) to new locations, so the patched range stays zero */ static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; int i; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); for (i = off; i < off + cnt - 1; i++) new_data[i].seen = true; env->insn_aux_data = new_data; vfree(old_data); return 0; } static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, const struct bpf_insn *patch, u32 len) { struct bpf_prog *new_prog; new_prog = bpf_patch_insn_single(env->prog, off, patch, len); if (!new_prog) return NULL; if (adjust_insn_aux_data(env, new_prog->len, off, len)) return NULL; return new_prog; } /* The verifier does more data flow analysis than llvm and will not explore * branches that are dead at run time. Malicious programs can have dead code * too. Therefore replace all dead at-run-time code with nops. */ static void sanitize_dead_code(struct bpf_verifier_env *env) { struct bpf_insn_aux_data *aux_data = env->insn_aux_data; struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0); struct bpf_insn *insn = env->prog->insnsi; const int insn_cnt = env->prog->len; int i; for (i = 0; i < insn_cnt; i++) { if (aux_data[i].seen) continue; memcpy(insn + i, &nop, sizeof(nop)); } } /* convert load instructions that access fields of 'struct __sk_buff' * into sequence of instructions that access fields of 'struct sk_buff' */ static int convert_ctx_accesses(struct bpf_verifier_env *env) { const struct bpf_verifier_ops *ops = env->ops; int i, cnt, size, ctx_field_size, delta = 0; const int insn_cnt = env->prog->len; struct bpf_insn insn_buf[16], *insn; struct bpf_prog *new_prog; enum bpf_access_type type; bool is_narrower_load; u32 target_size; if (ops->gen_prologue) { cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, env->prog); if (cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } else if (cnt) { new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); if (!new_prog) return -ENOMEM; env->prog = new_prog; delta += cnt - 1; } } if (!ops->convert_ctx_access) return 0; insn = env->prog->insnsi + delta; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || insn->code == (BPF_LDX | BPF_MEM | BPF_H) || insn->code == (BPF_LDX | BPF_MEM | BPF_W) || insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) type = BPF_READ; else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || insn->code == (BPF_STX | BPF_MEM | BPF_H) || insn->code == (BPF_STX | BPF_MEM | BPF_W) || insn->code == (BPF_STX | BPF_MEM | BPF_DW)) type = BPF_WRITE; else continue; if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX) continue; ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; size = BPF_LDST_BYTES(insn); /* If the read access is a narrower load of the field, * convert to a 4/8-byte load, to minimum program type specific * convert_ctx_access changes. If conversion is successful, * we will apply proper mask to the result. */ is_narrower_load = size < ctx_field_size; if (is_narrower_load) { u32 off = insn->off; u8 size_code; if (type == BPF_WRITE) { verbose(env, "bpf verifier narrow ctx access misconfigured\n"); return -EINVAL; } size_code = BPF_H; if (ctx_field_size == 4) size_code = BPF_W; else if (ctx_field_size == 8) size_code = BPF_DW; insn->off = off & ~(ctx_field_size - 1); insn->code = BPF_LDX | BPF_MEM | size_code; } target_size = 0; cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog, &target_size); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || (ctx_field_size && !target_size)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } if (is_narrower_load && size < target_size) { if (ctx_field_size <= 4) insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, (1 << size * 8) - 1); else insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, (1 << size * 8) - 1); } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; /* keep walking new program and skip insns we just inserted */ env->prog = new_prog; insn = new_prog->insnsi + i + delta; } return 0; } /* fixup insn->imm field of bpf_call instructions * and inline eligible helpers as explicit sequence of BPF instructions * * this function is called after eBPF program passed verification */ static int fixup_bpf_calls(struct bpf_verifier_env *env) { struct bpf_prog *prog = env->prog; struct bpf_insn *insn = prog->insnsi; const struct bpf_func_proto *fn; const int insn_cnt = prog->len; struct bpf_insn insn_buf[16]; struct bpf_prog *new_prog; struct bpf_map *map_ptr; int i, cnt, delta = 0; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code != (BPF_JMP | BPF_CALL)) continue; if (insn->imm == BPF_FUNC_get_route_realm) prog->dst_needed = 1; if (insn->imm == BPF_FUNC_get_prandom_u32) bpf_user_rnd_init_once(); if (insn->imm == BPF_FUNC_tail_call) { /* If we tail call into other programs, we * cannot make any assumptions since they can * be replaced dynamically during runtime in * the program array. */ prog->cb_access = 1; env->prog->aux->stack_depth = MAX_BPF_STACK; /* mark bpf_tail_call as different opcode to avoid * conditional branch in the interpeter for every normal * call and to prevent accidental JITing by JIT compiler * that doesn't support bpf_tail_call yet */ insn->imm = 0; insn->code = BPF_JMP | BPF_TAIL_CALL; continue; } /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup * handlers are currently limited to 64 bit only. */ if (ebpf_jit_enabled() && BITS_PER_LONG == 64 && insn->imm == BPF_FUNC_map_lookup_elem) { map_ptr = env->insn_aux_data[i + delta].map_ptr; if (map_ptr == BPF_MAP_PTR_POISON || !map_ptr->ops->map_gen_lookup) goto patch_call_imm; cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; /* keep walking new program and skip insns we just inserted */ env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (insn->imm == BPF_FUNC_redirect_map) { /* Note, we cannot use prog directly as imm as subsequent * rewrites would still change the prog pointer. The only * stable address we can use is aux, which also works with * prog clones during blinding. */ u64 addr = (unsigned long)prog->aux; struct bpf_insn r4_ld[] = { BPF_LD_IMM64(BPF_REG_4, addr), *insn, }; cnt = ARRAY_SIZE(r4_ld); new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; } patch_call_imm: fn = env->ops->get_func_proto(insn->imm); /* all functions that have prototype and verifier allowed * programs to call them, must be real in-kernel functions */ if (!fn->func) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(insn->imm), insn->imm); return -EFAULT; } insn->imm = fn->func - __bpf_call_base; } return 0; } static void free_states(struct bpf_verifier_env *env) { struct bpf_verifier_state_list *sl, *sln; int i; if (!env->explored_states) return; for (i = 0; i < env->prog->len; i++) { sl = env->explored_states[i]; if (sl) while (sl != STATE_LIST_MARK) { sln = sl->next; free_verifier_state(&sl->state, false); kfree(sl); sl = sln; } } kfree(env->explored_states); } int bpf_check(struct bpf_prog **prog, union bpf_attr *attr) { struct bpf_verifier_env *env; struct bpf_verifer_log *log; int ret = -EINVAL; /* no program is valid */ if (ARRAY_SIZE(bpf_verifier_ops) == 0) return -EINVAL; /* 'struct bpf_verifier_env' can be global, but since it's not small, * allocate/free it every time bpf_check() is called */ env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); if (!env) return -ENOMEM; log = &env->log; env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) * (*prog)->len); ret = -ENOMEM; if (!env->insn_aux_data) goto err_free_env; env->prog = *prog; env->ops = bpf_verifier_ops[env->prog->type]; /* grab the mutex to protect few globals used by verifier */ mutex_lock(&bpf_verifier_lock); if (attr->log_level || attr->log_buf || attr->log_size) { /* user requested verbose verifier output * and supplied buffer to store the verification trace */ log->level = attr->log_level; log->ubuf = (char __user *) (unsigned long) attr->log_buf; log->len_total = attr->log_size; ret = -EINVAL; /* log attributes have to be sane */ if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 || !log->level || !log->ubuf) goto err_unlock; } env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) env->strict_alignment = true; if (env->prog->aux->offload) { ret = bpf_prog_offload_verifier_prep(env); if (ret) goto err_unlock; } ret = replace_map_fd_with_map_ptr(env); if (ret < 0) goto skip_full_check; env->explored_states = kcalloc(env->prog->len, sizeof(struct bpf_verifier_state_list *), GFP_USER); ret = -ENOMEM; if (!env->explored_states) goto skip_full_check; ret = check_cfg(env); if (ret < 0) goto skip_full_check; env->allow_ptr_leaks = capable(CAP_SYS_ADMIN); ret = do_check(env); if (env->cur_state) { free_verifier_state(env->cur_state, true); env->cur_state = NULL; } skip_full_check: while (!pop_stack(env, NULL, NULL)); free_states(env); if (ret == 0) sanitize_dead_code(env); if (ret == 0) /* program is valid, convert *(u32*)(ctx + off) accesses */ ret = convert_ctx_accesses(env); if (ret == 0) ret = fixup_bpf_calls(env); if (log->level && bpf_verifier_log_full(log)) ret = -ENOSPC; if (log->level && !log->ubuf) { ret = -EFAULT; goto err_release_maps; } if (ret == 0 && env->used_map_cnt) { /* if program passed verifier, update used_maps in bpf_prog_info */ env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, sizeof(env->used_maps[0]), GFP_KERNEL); if (!env->prog->aux->used_maps) { ret = -ENOMEM; goto err_release_maps; } memcpy(env->prog->aux->used_maps, env->used_maps, sizeof(env->used_maps[0]) * env->used_map_cnt); env->prog->aux->used_map_cnt = env->used_map_cnt; /* program is valid. Convert pseudo bpf_ld_imm64 into generic * bpf_ld_imm64 instructions */ convert_pseudo_ld_imm64(env); } err_release_maps: if (!env->prog->aux->used_maps) /* if we didn't copy map pointers into bpf_prog_info, release * them now. Otherwise free_bpf_prog_info() will release them. */ release_maps(env); *prog = env->prog; err_unlock: mutex_unlock(&bpf_verifier_lock); vfree(env->insn_aux_data); err_free_env: kfree(env); return ret; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2988_0
crossvul-cpp_data_good_2820_0
/* * RTP H.264 Protocol (RFC3984) * Copyright (c) 2006 Ryan Martell * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @brief H.264 / RTP Code (RFC3984) * @author Ryan Martell <rdm4@martellventures.com> * * @note Notes: * Notes: * This currently supports packetization mode: * Single Nal Unit Mode (0), or * Non-Interleaved Mode (1). It currently does not support * Interleaved Mode (2). (This requires implementing STAP-B, MTAP16, MTAP24, * FU-B packet types) */ #include "libavutil/attributes.h" #include "libavutil/base64.h" #include "libavutil/intreadwrite.h" #include "libavutil/avstring.h" #include "avformat.h" #include "rtpdec.h" #include "rtpdec_formats.h" struct PayloadContext { // sdp setup parameters uint8_t profile_idc; uint8_t profile_iop; uint8_t level_idc; int packetization_mode; #ifdef DEBUG int packet_types_received[32]; #endif }; #ifdef DEBUG #define COUNT_NAL_TYPE(data, nal) data->packet_types_received[(nal) & 0x1f]++ #define NAL_COUNTERS data->packet_types_received #else #define COUNT_NAL_TYPE(data, nal) do { } while (0) #define NAL_COUNTERS NULL #endif #define NAL_MASK 0x1f static const uint8_t start_sequence[] = { 0, 0, 0, 1 }; static void parse_profile_level_id(AVFormatContext *s, PayloadContext *h264_data, const char *value) { char buffer[3]; // 6 characters=3 bytes, in hex. uint8_t profile_idc; uint8_t profile_iop; uint8_t level_idc; buffer[0] = value[0]; buffer[1] = value[1]; buffer[2] = '\0'; profile_idc = strtol(buffer, NULL, 16); buffer[0] = value[2]; buffer[1] = value[3]; profile_iop = strtol(buffer, NULL, 16); buffer[0] = value[4]; buffer[1] = value[5]; level_idc = strtol(buffer, NULL, 16); av_log(s, AV_LOG_DEBUG, "RTP Profile IDC: %x Profile IOP: %x Level: %x\n", profile_idc, profile_iop, level_idc); h264_data->profile_idc = profile_idc; h264_data->profile_iop = profile_iop; h264_data->level_idc = level_idc; } int ff_h264_parse_sprop_parameter_sets(AVFormatContext *s, uint8_t **data_ptr, int *size_ptr, const char *value) { char base64packet[1024]; uint8_t decoded_packet[1024]; int packet_size; while (*value) { char *dst = base64packet; while (*value && *value != ',' && (dst - base64packet) < sizeof(base64packet) - 1) { *dst++ = *value++; } *dst++ = '\0'; if (*value == ',') value++; packet_size = av_base64_decode(decoded_packet, base64packet, sizeof(decoded_packet)); if (packet_size > 0) { uint8_t *dest = av_realloc(*data_ptr, packet_size + sizeof(start_sequence) + *size_ptr + AV_INPUT_BUFFER_PADDING_SIZE); if (!dest) { av_log(s, AV_LOG_ERROR, "Unable to allocate memory for extradata!\n"); return AVERROR(ENOMEM); } *data_ptr = dest; memcpy(dest + *size_ptr, start_sequence, sizeof(start_sequence)); memcpy(dest + *size_ptr + sizeof(start_sequence), decoded_packet, packet_size); memset(dest + *size_ptr + sizeof(start_sequence) + packet_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); *size_ptr += sizeof(start_sequence) + packet_size; } } return 0; } static int sdp_parse_fmtp_config_h264(AVFormatContext *s, AVStream *stream, PayloadContext *h264_data, const char *attr, const char *value) { AVCodecParameters *par = stream->codecpar; if (!strcmp(attr, "packetization-mode")) { av_log(s, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value)); h264_data->packetization_mode = atoi(value); /* * Packetization Mode: * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed) * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed. * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A), * and 29 (FU-B) are allowed. */ if (h264_data->packetization_mode > 1) av_log(s, AV_LOG_ERROR, "Interleaved RTP mode is not supported yet.\n"); } else if (!strcmp(attr, "profile-level-id")) { if (strlen(value) == 6) parse_profile_level_id(s, h264_data, value); } else if (!strcmp(attr, "sprop-parameter-sets")) { int ret; if (*value == 0 || value[strlen(value) - 1] == ',') { av_log(s, AV_LOG_WARNING, "Missing PPS in sprop-parameter-sets, ignoring\n"); return 0; } par->extradata_size = 0; av_freep(&par->extradata); ret = ff_h264_parse_sprop_parameter_sets(s, &par->extradata, &par->extradata_size, value); av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)\n", par->extradata, par->extradata_size); return ret; } return 0; } void ff_h264_parse_framesize(AVCodecParameters *par, const char *p) { char buf1[50]; char *dst = buf1; // remove the protocol identifier while (*p && *p == ' ') p++; // strip spaces. while (*p && *p != ' ') p++; // eat protocol identifier while (*p && *p == ' ') p++; // strip trailing spaces. while (*p && *p != '-' && (dst - buf1) < sizeof(buf1) - 1) *dst++ = *p++; *dst = '\0'; // a='framesize:96 320-240' // set our parameters par->width = atoi(buf1); par->height = atoi(p + 1); // skip the - } int ff_h264_handle_aggregated_packet(AVFormatContext *ctx, PayloadContext *data, AVPacket *pkt, const uint8_t *buf, int len, int skip_between, int *nal_counters, int nal_mask) { int pass = 0; int total_length = 0; uint8_t *dst = NULL; int ret; // first we are going to figure out the total size for (pass = 0; pass < 2; pass++) { const uint8_t *src = buf; int src_len = len; while (src_len > 2) { uint16_t nal_size = AV_RB16(src); // consume the length of the aggregate src += 2; src_len -= 2; if (nal_size <= src_len) { if (pass == 0) { // counting total_length += sizeof(start_sequence) + nal_size; } else { // copying memcpy(dst, start_sequence, sizeof(start_sequence)); dst += sizeof(start_sequence); memcpy(dst, src, nal_size); if (nal_counters) nal_counters[(*src) & nal_mask]++; dst += nal_size; } } else { av_log(ctx, AV_LOG_ERROR, "nal size exceeds length: %d %d\n", nal_size, src_len); return AVERROR_INVALIDDATA; } // eat what we handled src += nal_size + skip_between; src_len -= nal_size + skip_between; } if (pass == 0) { /* now we know the total size of the packet (with the * start sequences added) */ if ((ret = av_new_packet(pkt, total_length)) < 0) return ret; dst = pkt->data; } } return 0; } int ff_h264_handle_frag_packet(AVPacket *pkt, const uint8_t *buf, int len, int start_bit, const uint8_t *nal_header, int nal_header_len) { int ret; int tot_len = len; int pos = 0; if (start_bit) tot_len += sizeof(start_sequence) + nal_header_len; if ((ret = av_new_packet(pkt, tot_len)) < 0) return ret; if (start_bit) { memcpy(pkt->data + pos, start_sequence, sizeof(start_sequence)); pos += sizeof(start_sequence); memcpy(pkt->data + pos, nal_header, nal_header_len); pos += nal_header_len; } memcpy(pkt->data + pos, buf, len); return 0; } static int h264_handle_packet_fu_a(AVFormatContext *ctx, PayloadContext *data, AVPacket *pkt, const uint8_t *buf, int len, int *nal_counters, int nal_mask) { uint8_t fu_indicator, fu_header, start_bit, nal_type, nal; if (len < 3) { av_log(ctx, AV_LOG_ERROR, "Too short data for FU-A H.264 RTP packet\n"); return AVERROR_INVALIDDATA; } fu_indicator = buf[0]; fu_header = buf[1]; start_bit = fu_header >> 7; nal_type = fu_header & 0x1f; nal = fu_indicator & 0xe0 | nal_type; // skip the fu_indicator and fu_header buf += 2; len -= 2; if (start_bit && nal_counters) nal_counters[nal_type & nal_mask]++; return ff_h264_handle_frag_packet(pkt, buf, len, start_bit, &nal, 1); } // return 0 on packet, no more left, 1 on packet, 1 on partial packet static int h264_handle_packet(AVFormatContext *ctx, PayloadContext *data, AVStream *st, AVPacket *pkt, uint32_t *timestamp, const uint8_t *buf, int len, uint16_t seq, int flags) { uint8_t nal; uint8_t type; int result = 0; if (!len) { av_log(ctx, AV_LOG_ERROR, "Empty H.264 RTP packet\n"); return AVERROR_INVALIDDATA; } nal = buf[0]; type = nal & 0x1f; /* Simplify the case (these are all the NAL types used internally by * the H.264 codec). */ if (type >= 1 && type <= 23) type = 1; switch (type) { case 0: // undefined, but pass them through case 1: if ((result = av_new_packet(pkt, len + sizeof(start_sequence))) < 0) return result; memcpy(pkt->data, start_sequence, sizeof(start_sequence)); memcpy(pkt->data + sizeof(start_sequence), buf, len); COUNT_NAL_TYPE(data, nal); break; case 24: // STAP-A (one packet, multiple nals) // consume the STAP-A NAL buf++; len--; result = ff_h264_handle_aggregated_packet(ctx, data, pkt, buf, len, 0, NAL_COUNTERS, NAL_MASK); break; case 25: // STAP-B case 26: // MTAP-16 case 27: // MTAP-24 case 29: // FU-B avpriv_report_missing_feature(ctx, "RTP H.264 NAL unit type %d", type); result = AVERROR_PATCHWELCOME; break; case 28: // FU-A (fragmented nal) result = h264_handle_packet_fu_a(ctx, data, pkt, buf, len, NAL_COUNTERS, NAL_MASK); break; case 30: // undefined case 31: // undefined default: av_log(ctx, AV_LOG_ERROR, "Undefined type (%d)\n", type); result = AVERROR_INVALIDDATA; break; } pkt->stream_index = st->index; return result; } static void h264_close_context(PayloadContext *data) { #ifdef DEBUG int ii; for (ii = 0; ii < 32; ii++) { if (data->packet_types_received[ii]) av_log(NULL, AV_LOG_DEBUG, "Received %d packets of type %d\n", data->packet_types_received[ii], ii); } #endif } static int parse_h264_sdp_line(AVFormatContext *s, int st_index, PayloadContext *h264_data, const char *line) { AVStream *stream; const char *p = line; if (st_index < 0) return 0; stream = s->streams[st_index]; if (av_strstart(p, "framesize:", &p)) { ff_h264_parse_framesize(stream->codecpar, p); } else if (av_strstart(p, "fmtp:", &p)) { return ff_parse_fmtp(s, stream, h264_data, p, sdp_parse_fmtp_config_h264); } else if (av_strstart(p, "cliprect:", &p)) { // could use this if we wanted. } return 0; } RTPDynamicProtocolHandler ff_h264_dynamic_handler = { .enc_name = "H264", .codec_type = AVMEDIA_TYPE_VIDEO, .codec_id = AV_CODEC_ID_H264, .need_parsing = AVSTREAM_PARSE_FULL, .priv_data_size = sizeof(PayloadContext), .parse_sdp_a_line = parse_h264_sdp_line, .close = h264_close_context, .parse_packet = h264_handle_packet, };
./CrossVul/dataset_final_sorted/CWE-119/c/good_2820_0
crossvul-cpp_data_good_943_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % GGGG IIIII FFFFF % % G I F % % G GG I FFF % % G G I F % % GGG IIIII F % % % % % % Read/Write Compuserv Graphics Interchange Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/profile.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/module.h" /* Define declarations. */ #define MaximumLZWBits 12 #define MaximumLZWCode (1UL << MaximumLZWBits) /* Typdef declarations. */ typedef struct _LZWCodeInfo { unsigned char buffer[280]; size_t count, bit; MagickBooleanType eof; } LZWCodeInfo; typedef struct _LZWStack { size_t *codes, *index, *top; } LZWStack; typedef struct _LZWInfo { Image *image; LZWStack *stack; MagickBooleanType genesis; size_t data_size, maximum_data_value, clear_code, end_code, bits, first_code, last_code, maximum_code, slot, *table[2]; LZWCodeInfo code_info; } LZWInfo; /* Forward declarations. */ static inline int GetNextLZWCode(LZWInfo *,const size_t); static MagickBooleanType WriteGIFImage(const ImageInfo *,Image *); static ssize_t ReadBlobBlock(Image *,unsigned char *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage uncompresses an image via GIF-coding. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(Image *image,const ssize_t opacity) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o opacity: The colormap index associated with the transparent color. % */ static LZWInfo *RelinquishLZWInfo(LZWInfo *lzw_info) { if (lzw_info->table[0] != (size_t *) NULL) lzw_info->table[0]=(size_t *) RelinquishMagickMemory( lzw_info->table[0]); if (lzw_info->table[1] != (size_t *) NULL) lzw_info->table[1]=(size_t *) RelinquishMagickMemory( lzw_info->table[1]); if (lzw_info->stack != (LZWStack *) NULL) { if (lzw_info->stack->codes != (size_t *) NULL) lzw_info->stack->codes=(size_t *) RelinquishMagickMemory( lzw_info->stack->codes); lzw_info->stack=(LZWStack *) RelinquishMagickMemory(lzw_info->stack); } lzw_info=(LZWInfo *) RelinquishMagickMemory(lzw_info); return((LZWInfo *) NULL); } static inline void ResetLZWInfo(LZWInfo *lzw_info) { size_t one; lzw_info->bits=lzw_info->data_size+1; one=1; lzw_info->maximum_code=one << lzw_info->bits; lzw_info->slot=lzw_info->maximum_data_value+3; lzw_info->genesis=MagickTrue; } static LZWInfo *AcquireLZWInfo(Image *image,const size_t data_size) { LZWInfo *lzw_info; register ssize_t i; size_t one; lzw_info=(LZWInfo *) AcquireMagickMemory(sizeof(*lzw_info)); if (lzw_info == (LZWInfo *) NULL) return((LZWInfo *) NULL); (void) memset(lzw_info,0,sizeof(*lzw_info)); lzw_info->image=image; lzw_info->data_size=data_size; one=1; lzw_info->maximum_data_value=(one << data_size)-1; lzw_info->clear_code=lzw_info->maximum_data_value+1; lzw_info->end_code=lzw_info->maximum_data_value+2; lzw_info->table[0]=(size_t *) AcquireQuantumMemory(MaximumLZWCode, sizeof(**lzw_info->table)); lzw_info->table[1]=(size_t *) AcquireQuantumMemory(MaximumLZWCode, sizeof(**lzw_info->table)); if ((lzw_info->table[0] == (size_t *) NULL) || (lzw_info->table[1] == (size_t *) NULL)) { lzw_info=RelinquishLZWInfo(lzw_info); return((LZWInfo *) NULL); } (void) memset(lzw_info->table[0],0,MaximumLZWCode* sizeof(**lzw_info->table)); (void) memset(lzw_info->table[1],0,MaximumLZWCode* sizeof(**lzw_info->table)); for (i=0; i <= (ssize_t) lzw_info->maximum_data_value; i++) { lzw_info->table[0][i]=0; lzw_info->table[1][i]=(size_t) i; } ResetLZWInfo(lzw_info); lzw_info->code_info.buffer[0]='\0'; lzw_info->code_info.buffer[1]='\0'; lzw_info->code_info.count=2; lzw_info->code_info.bit=8*lzw_info->code_info.count; lzw_info->code_info.eof=MagickFalse; lzw_info->genesis=MagickTrue; lzw_info->stack=(LZWStack *) AcquireMagickMemory(sizeof(*lzw_info->stack)); if (lzw_info->stack == (LZWStack *) NULL) { lzw_info=RelinquishLZWInfo(lzw_info); return((LZWInfo *) NULL); } lzw_info->stack->codes=(size_t *) AcquireQuantumMemory(2UL* MaximumLZWCode,sizeof(*lzw_info->stack->codes)); if (lzw_info->stack->codes == (size_t *) NULL) { lzw_info=RelinquishLZWInfo(lzw_info); return((LZWInfo *) NULL); } lzw_info->stack->index=lzw_info->stack->codes; lzw_info->stack->top=lzw_info->stack->codes+2*MaximumLZWCode; return(lzw_info); } static inline int GetNextLZWCode(LZWInfo *lzw_info,const size_t bits) { int code; register ssize_t i; size_t one; while (((lzw_info->code_info.bit+bits) > (8*lzw_info->code_info.count)) && (lzw_info->code_info.eof == MagickFalse)) { ssize_t count; lzw_info->code_info.buffer[0]=lzw_info->code_info.buffer[ lzw_info->code_info.count-2]; lzw_info->code_info.buffer[1]=lzw_info->code_info.buffer[ lzw_info->code_info.count-1]; lzw_info->code_info.bit-=8*(lzw_info->code_info.count-2); lzw_info->code_info.count=2; count=ReadBlobBlock(lzw_info->image,&lzw_info->code_info.buffer[ lzw_info->code_info.count]); if (count > 0) lzw_info->code_info.count+=count; else lzw_info->code_info.eof=MagickTrue; } if ((lzw_info->code_info.bit+bits) > (8*lzw_info->code_info.count)) return(-1); code=0; one=1; for (i=0; i < (ssize_t) bits; i++) { code|=((lzw_info->code_info.buffer[lzw_info->code_info.bit/8] & (one << (lzw_info->code_info.bit % 8))) != 0) << i; lzw_info->code_info.bit++; } return(code); } static inline int PopLZWStack(LZWStack *stack_info) { if (stack_info->index <= stack_info->codes) return(-1); stack_info->index--; return((int) *stack_info->index); } static inline void PushLZWStack(LZWStack *stack_info,const size_t value) { if (stack_info->index >= stack_info->top) return; *stack_info->index=value; stack_info->index++; } static int ReadBlobLZWByte(LZWInfo *lzw_info) { int code; size_t one, value; ssize_t count; if (lzw_info->stack->index != lzw_info->stack->codes) return(PopLZWStack(lzw_info->stack)); if (lzw_info->genesis != MagickFalse) { lzw_info->genesis=MagickFalse; do { lzw_info->first_code=(size_t) GetNextLZWCode(lzw_info,lzw_info->bits); lzw_info->last_code=lzw_info->first_code; } while (lzw_info->first_code == lzw_info->clear_code); return((int) lzw_info->first_code); } code=GetNextLZWCode(lzw_info,lzw_info->bits); if (code < 0) return(code); if ((size_t) code == lzw_info->clear_code) { ResetLZWInfo(lzw_info); return(ReadBlobLZWByte(lzw_info)); } if ((size_t) code == lzw_info->end_code) return(-1); if ((size_t) code < lzw_info->slot) value=(size_t) code; else { PushLZWStack(lzw_info->stack,lzw_info->first_code); value=lzw_info->last_code; } count=0; while (value > lzw_info->maximum_data_value) { if ((size_t) count > MaximumLZWCode) return(-1); count++; if ((size_t) value > MaximumLZWCode) return(-1); PushLZWStack(lzw_info->stack,lzw_info->table[1][value]); value=lzw_info->table[0][value]; } lzw_info->first_code=lzw_info->table[1][value]; PushLZWStack(lzw_info->stack,lzw_info->first_code); one=1; if (lzw_info->slot < MaximumLZWCode) { lzw_info->table[0][lzw_info->slot]=lzw_info->last_code; lzw_info->table[1][lzw_info->slot]=lzw_info->first_code; lzw_info->slot++; if ((lzw_info->slot >= lzw_info->maximum_code) && (lzw_info->bits < MaximumLZWBits)) { lzw_info->bits++; lzw_info->maximum_code=one << lzw_info->bits; } } lzw_info->last_code=(size_t) code; return(PopLZWStack(lzw_info->stack)); } static MagickBooleanType DecodeImage(Image *image,const ssize_t opacity) { ExceptionInfo *exception; IndexPacket index; int c; LZWInfo *lzw_info; ssize_t offset, y; unsigned char data_size; size_t pass; /* Allocate decoder tables. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=(&image->exception); data_size=(unsigned char) ReadBlobByte(image); if (data_size > MaximumLZWBits) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); lzw_info=AcquireLZWInfo(image,data_size); if (lzw_info == (LZWInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); pass=0; offset=0; for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; ) { c=ReadBlobLZWByte(lzw_info); if (c < 0) break; index=ConstrainColormapIndex(image,(ssize_t) c); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); SetPixelOpacity(q,(ssize_t) index == opacity ? TransparentOpacity : OpaqueOpacity); x++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (x < (ssize_t) image->columns) break; if (image->interlace == NoInterlace) offset++; else { switch (pass) { case 0: default: { offset+=8; break; } case 1: { offset+=8; break; } case 2: { offset+=4; break; } case 3: { offset+=2; break; } } if ((pass == 0) && (offset >= (ssize_t) image->rows)) { pass++; offset=4; } if ((pass == 1) && (offset >= (ssize_t) image->rows)) { pass++; offset=2; } if ((pass == 2) && (offset >= (ssize_t) image->rows)) { pass++; offset=1; } } } lzw_info=RelinquishLZWInfo(lzw_info); if (y < (ssize_t) image->rows) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EncodeImage compresses an image via GIF-coding. % % The format of the EncodeImage method is: % % MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image, % const size_t data_size) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the address of a structure of type Image. % % o data_size: The number of bits in the compressed packet. % */ static MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image, const size_t data_size) { #define MaxCode(number_bits) ((one << (number_bits))-1) #define MaxHashTable 5003 #define MaxGIFBits 12UL #define MaxGIFTable (1UL << MaxGIFBits) #define GIFOutputCode(code) \ { \ /* \ Emit a code. \ */ \ if (bits > 0) \ datum|=(size_t) (code) << bits; \ else \ datum=(size_t) (code); \ bits+=number_bits; \ while (bits >= 8) \ { \ /* \ Add a character to current packet. \ */ \ packet[length++]=(unsigned char) (datum & 0xff); \ if (length >= 254) \ { \ (void) WriteBlobByte(image,(unsigned char) length); \ (void) WriteBlob(image,length,packet); \ length=0; \ } \ datum>>=8; \ bits-=8; \ } \ if (free_code > max_code) \ { \ number_bits++; \ if (number_bits == MaxGIFBits) \ max_code=MaxGIFTable; \ else \ max_code=MaxCode(number_bits); \ } \ } IndexPacket index; short *hash_code, *hash_prefix, waiting_code; size_t bits, clear_code, datum, end_of_information_code, free_code, length, max_code, next_pixel, number_bits, one, pass; ssize_t displacement, offset, k, y; unsigned char *packet, *hash_suffix; /* Allocate encoder tables. */ assert(image != (Image *) NULL); one=1; packet=(unsigned char *) AcquireQuantumMemory(256,sizeof(*packet)); hash_code=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_code)); hash_prefix=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_prefix)); hash_suffix=(unsigned char *) AcquireQuantumMemory(MaxHashTable, sizeof(*hash_suffix)); if ((packet == (unsigned char *) NULL) || (hash_code == (short *) NULL) || (hash_prefix == (short *) NULL) || (hash_suffix == (unsigned char *) NULL)) { if (packet != (unsigned char *) NULL) packet=(unsigned char *) RelinquishMagickMemory(packet); if (hash_code != (short *) NULL) hash_code=(short *) RelinquishMagickMemory(hash_code); if (hash_prefix != (short *) NULL) hash_prefix=(short *) RelinquishMagickMemory(hash_prefix); if (hash_suffix != (unsigned char *) NULL) hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix); return(MagickFalse); } /* Initialize GIF encoder. */ (void) memset(packet,0,256*sizeof(*packet)); (void) memset(hash_code,0,MaxHashTable*sizeof(*hash_code)); (void) memset(hash_prefix,0,MaxHashTable*sizeof(*hash_prefix)); (void) memset(hash_suffix,0,MaxHashTable*sizeof(*hash_suffix)); number_bits=data_size; max_code=MaxCode(number_bits); clear_code=((short) one << (data_size-1)); end_of_information_code=clear_code+1; free_code=clear_code+2; length=0; datum=0; bits=0; GIFOutputCode(clear_code); /* Encode pixels. */ offset=0; pass=0; waiting_code=0; for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,offset,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); if (y == 0) { waiting_code=(short) (*indexes); p++; } for (x=(ssize_t) (y == 0 ? 1 : 0); x < (ssize_t) image->columns; x++) { /* Probe hash table. */ next_pixel=MagickFalse; displacement=1; index=(IndexPacket) ((size_t) GetPixelIndex(indexes+x) & 0xff); p++; k=(ssize_t) (((size_t) index << (MaxGIFBits-8))+waiting_code); if (k >= MaxHashTable) k-=MaxHashTable; if (k < 0) continue; if (hash_code[k] > 0) { if ((hash_prefix[k] == waiting_code) && (hash_suffix[k] == (unsigned char) index)) { waiting_code=hash_code[k]; continue; } if (k != 0) displacement=MaxHashTable-k; for ( ; ; ) { k-=displacement; if (k < 0) k+=MaxHashTable; if (hash_code[k] == 0) break; if ((hash_prefix[k] == waiting_code) && (hash_suffix[k] == (unsigned char) index)) { waiting_code=hash_code[k]; next_pixel=MagickTrue; break; } } if (next_pixel != MagickFalse) continue; } GIFOutputCode(waiting_code); if (free_code < MaxGIFTable) { hash_code[k]=(short) free_code++; hash_prefix[k]=waiting_code; hash_suffix[k]=(unsigned char) index; } else { /* Fill the hash table with empty entries. */ for (k=0; k < MaxHashTable; k++) hash_code[k]=0; /* Reset compressor and issue a clear code. */ free_code=clear_code+2; GIFOutputCode(clear_code); number_bits=data_size; max_code=MaxCode(number_bits); } waiting_code=(short) index; } if (image_info->interlace == NoInterlace) offset++; else switch (pass) { case 0: default: { offset+=8; if (offset >= (ssize_t) image->rows) { pass++; offset=4; } break; } case 1: { offset+=8; if (offset >= (ssize_t) image->rows) { pass++; offset=2; } break; } case 2: { offset+=4; if (offset >= (ssize_t) image->rows) { pass++; offset=1; } break; } case 3: { offset+=2; break; } } } /* Flush out the buffered code. */ GIFOutputCode(waiting_code); GIFOutputCode(end_of_information_code); if (bits > 0) { /* Add a character to current packet. */ packet[length++]=(unsigned char) (datum & 0xff); if (length >= 254) { (void) WriteBlobByte(image,(unsigned char) length); (void) WriteBlob(image,length,packet); length=0; } } /* Flush accumulated data. */ if (length > 0) { (void) WriteBlobByte(image,(unsigned char) length); (void) WriteBlob(image,length,packet); } /* Free encoder memory. */ hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix); hash_prefix=(short *) RelinquishMagickMemory(hash_prefix); hash_code=(short *) RelinquishMagickMemory(hash_code); packet=(unsigned char *) RelinquishMagickMemory(packet); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s G I F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsGIF() returns MagickTrue if the image format type, identified by the % magick string, is GIF. % % The format of the IsGIF method is: % % MagickBooleanType IsGIF(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsGIF(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((char *) magick,"GIF8",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d B l o b B l o c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadBlobBlock() reads data from the image file and returns it. The % amount of data is determined by first reading a count byte. The number % of bytes read is returned. % % The format of the ReadBlobBlock method is: % % ssize_t ReadBlobBlock(Image *image,unsigned char *data) % % A description of each parameter follows: % % o image: the image. % % o data: Specifies an area to place the information requested from % the file. % */ static ssize_t ReadBlobBlock(Image *image,unsigned char *data) { ssize_t count; unsigned char block_count; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(data != (unsigned char *) NULL); count=ReadBlob(image,1,&block_count); if (count != 1) return(0); count=ReadBlob(image,(size_t) block_count,data); if (count != (ssize_t) block_count) return(0); return(count); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d G I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadGIFImage() reads a Compuserve Graphics image file and returns it. % It allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadGIFImage method is: % % Image *ReadGIFImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static void *DestroyGIFProfile(void *profile) { return((void *) DestroyStringInfo((StringInfo *) profile)); } static MagickBooleanType PingGIFImage(Image *image) { unsigned char buffer[256], length, data_size; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (ReadBlob(image,1,&data_size) != 1) ThrowBinaryImageException(CorruptImageError,"CorruptImage", image->filename); if (data_size > MaximumLZWBits) ThrowBinaryImageException(CorruptImageError,"CorruptImage", image->filename); if (ReadBlob(image,1,&length) != 1) ThrowBinaryImageException(CorruptImageError,"CorruptImage", image->filename); while (length != 0) { if (ReadBlob(image,length,buffer) != (ssize_t) length) ThrowBinaryImageException(CorruptImageError,"CorruptImage", image->filename); if (ReadBlob(image,1,&length) != 1) ThrowBinaryImageException(CorruptImageError,"CorruptImage", image->filename); } return(MagickTrue); } static Image *ReadGIFImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BitSet(byte,bit) (((byte) & (bit)) == (bit)) #define LSBFirstOrder(x,y) (((y) << 8) | (x)) #define ThrowGIFException(exception,message) \ { \ if (profiles != (LinkedListInfo *) NULL) \ profiles=DestroyLinkedList(profiles,DestroyGIFProfile); \ if (global_colormap != (unsigned char *) NULL) \ global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap); \ if (meta_image != (Image *) NULL) \ meta_image=DestroyImage(meta_image); \ ThrowReaderException((exception),(message)); \ } Image *image, *meta_image; LinkedListInfo *profiles; MagickBooleanType status; register ssize_t i; register unsigned char *p; size_t duration, global_colors, image_count, local_colors, one; ssize_t count, opacity; unsigned char background, buffer[257], c, flag, *global_colormap, magick[12]; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a GIF file. */ count=ReadBlob(image,6,magick); if ((count != 6) || ((LocaleNCompare((char *) magick,"GIF87",5) != 0) && (LocaleNCompare((char *) magick,"GIF89",5) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) memset(buffer,0,sizeof(buffer)); meta_image=AcquireImage(image_info); /* metadata container */ meta_image->page.width=ReadBlobLSBShort(image); meta_image->page.height=ReadBlobLSBShort(image); meta_image->iterations=1; flag=(unsigned char) ReadBlobByte(image); background=(unsigned char) ReadBlobByte(image); c=(unsigned char) ReadBlobByte(image); /* reserved */ profiles=(LinkedListInfo *) NULL; one=1; global_colors=one << (((size_t) flag & 0x07)+1); global_colormap=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(global_colors,256),3UL*sizeof(*global_colormap)); if (global_colormap == (unsigned char *) NULL) ThrowGIFException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(global_colormap,0,3*MagickMax(global_colors,256)* sizeof(*global_colormap)); if (BitSet((int) flag,0x80) != 0) { count=ReadBlob(image,(size_t) (3*global_colors),global_colormap); if (count != (ssize_t) (3*global_colors)) ThrowGIFException(CorruptImageError,"InsufficientImageDataInFile"); } duration=0; opacity=(-1); image_count=0; for ( ; ; ) { count=ReadBlob(image,1,&c); if (count != 1) break; if (c == (unsigned char) ';') break; /* terminator */ if (c == (unsigned char) '!') { /* GIF Extension block. */ count=ReadBlob(image,1,&c); if (count != 1) ThrowGIFException(CorruptImageError,"UnableToReadExtensionBlock"); (void) memset(buffer,0,sizeof(buffer)); switch (c) { case 0xf9: { /* Read graphics control extension. */ while (ReadBlobBlock(image,buffer) != 0) ; meta_image->dispose=(DisposeType) ((buffer[0] >> 2) & 0x07); meta_image->delay=((size_t) buffer[2] << 8) | buffer[1]; if ((ssize_t) (buffer[0] & 0x01) == 0x01) opacity=(ssize_t) buffer[3]; break; } case 0xfe: { char *comments; size_t extent, offset; comments=AcquireString((char *) NULL); extent=MagickPathExtent; for (offset=0; ; offset+=count) { count=ReadBlobBlock(image,buffer); if (count == 0) break; buffer[count]='\0'; if (((ssize_t) (count+offset+MagickPathExtent)) >= (ssize_t) extent) { extent<<=1; comments=(char *) ResizeQuantumMemory(comments,extent+ MagickPathExtent,sizeof(*comments)); if (comments == (char *) NULL) ThrowGIFException(ResourceLimitError, "MemoryAllocationFailed"); } (void) CopyMagickString(&comments[offset],(char *) buffer,extent- offset); } (void) SetImageProperty(meta_image,"comment",comments); comments=DestroyString(comments); break; } case 0xff: { MagickBooleanType loop; /* Read Netscape Loop extension. */ loop=MagickFalse; if (ReadBlobBlock(image,buffer) != 0) loop=LocaleNCompare((char *) buffer,"NETSCAPE2.0",11) == 0 ? MagickTrue : MagickFalse; if (loop != MagickFalse) while (ReadBlobBlock(image,buffer) != 0) { meta_image->iterations=((size_t) buffer[2] << 8) | buffer[1]; if (meta_image->iterations != 0) meta_image->iterations++; } else { char name[MaxTextExtent]; int block_length, info_length, reserved_length; MagickBooleanType i8bim, icc, iptc, magick; StringInfo *profile; unsigned char *info; /* Store GIF application extension as a generic profile. */ icc=LocaleNCompare((char *) buffer,"ICCRGBG1012",11) == 0 ? MagickTrue : MagickFalse; magick=LocaleNCompare((char *) buffer,"ImageMagick",11) == 0 ? MagickTrue : MagickFalse; i8bim=LocaleNCompare((char *) buffer,"MGK8BIM0000",11) == 0 ? MagickTrue : MagickFalse; iptc=LocaleNCompare((char *) buffer,"MGKIPTC0000",11) == 0 ? MagickTrue : MagickFalse; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading GIF application extension"); info=(unsigned char *) AcquireQuantumMemory(255UL, sizeof(*info)); if (info == (unsigned char *) NULL) ThrowGIFException(ResourceLimitError, "MemoryAllocationFailed"); (void) memset(info,0,255UL*sizeof(*info)); reserved_length=255; for (info_length=0; ; ) { block_length=(int) ReadBlobBlock(image,&info[info_length]); if (block_length == 0) break; info_length+=block_length; if (info_length > (reserved_length-255)) { reserved_length+=4096; info=(unsigned char *) ResizeQuantumMemory(info,(size_t) reserved_length,sizeof(*info)); if (info == (unsigned char *) NULL) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowGIFException(ResourceLimitError, "MemoryAllocationFailed"); } } } profile=BlobToStringInfo(info,(size_t) info_length); if (profile == (StringInfo *) NULL) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowGIFException(ResourceLimitError, "MemoryAllocationFailed"); } if (i8bim != MagickFalse) (void) CopyMagickString(name,"8bim",sizeof(name)); else if (icc != MagickFalse) (void) CopyMagickString(name,"icc",sizeof(name)); else if (iptc != MagickFalse) (void) CopyMagickString(name,"iptc",sizeof(name)); else if (magick != MagickFalse) { (void) CopyMagickString(name,"magick",sizeof(name)); meta_image->gamma=StringToDouble((char *) info+6, (char **) NULL); } else (void) FormatLocaleString(name,sizeof(name),"gif:%.11s", buffer); info=(unsigned char *) RelinquishMagickMemory(info); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " profile name=%s",name); if (magick != MagickFalse) profile=DestroyStringInfo(profile); else { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); SetStringInfoName(profile,name); (void) AppendValueToLinkedList(profiles,profile); } } break; } default: { while (ReadBlobBlock(image,buffer) != 0) ; break; } } } if (c != (unsigned char) ',') continue; if (image_count != 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); } image_count++; /* Read image attributes. */ meta_image->page.x=(ssize_t) ReadBlobLSBShort(image); meta_image->page.y=(ssize_t) ReadBlobLSBShort(image); meta_image->scene=image->scene; (void) CloneImageProperties(image,meta_image); DestroyImageProperties(meta_image); image->storage_class=PseudoClass; image->compression=LZWCompression; image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); image->depth=8; flag=(unsigned char) ReadBlobByte(image); image->interlace=BitSet((int) flag,0x40) != 0 ? GIFInterlace : NoInterlace; local_colors=BitSet((int) flag,0x80) == 0 ? global_colors : one << ((size_t) (flag & 0x07)+1); image->colors=local_colors; if (opacity >= (ssize_t) image->colors) { image->colors++; opacity=(-1); } image->ticks_per_second=100; image->matte=opacity >= 0 ? MagickTrue : MagickFalse; if ((image->columns == 0) || (image->rows == 0)) ThrowGIFException(CorruptImageError,"NegativeOrZeroImageSize"); /* Inititialize colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowGIFException(ResourceLimitError,"MemoryAllocationFailed"); if (BitSet((int) flag,0x80) == 0) { /* Use global colormap. */ p=global_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].blue=ScaleCharToQuantum(*p++); if (i == opacity) { image->colormap[i].opacity=(Quantum) TransparentOpacity; image->transparent_color=image->colormap[opacity]; } } image->background_color=image->colormap[MagickMin((ssize_t) background, (ssize_t) image->colors-1)]; } else { unsigned char *colormap; /* Read local colormap. */ colormap=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(local_colors,256),3UL*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowGIFException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(colormap,0,3*MagickMax(local_colors,256)* sizeof(*colormap)); count=ReadBlob(image,(3*local_colors)*sizeof(*colormap),colormap); if (count != (ssize_t) (3*local_colors)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowGIFException(CorruptImageError,"InsufficientImageDataInFile"); } p=colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].blue=ScaleCharToQuantum(*p++); if (i == opacity) image->colormap[i].opacity=(Quantum) TransparentOpacity; } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } if (image->gamma == 1.0) { for (i=0; i < (ssize_t) image->colors; i++) if (IsGrayPixel(image->colormap+i) == MagickFalse) break; (void) SetImageColorspace(image,i == (ssize_t) image->colors ? LinearGRAYColorspace : RGBColorspace); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { if (profiles != (LinkedListInfo *) NULL) profiles=DestroyLinkedList(profiles,DestroyGIFProfile); global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); meta_image=DestroyImage(meta_image); InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Decode image. */ if (image_info->ping != MagickFalse) status=PingGIFImage(image); else status=DecodeImage(image,opacity); InheritException(exception,&image->exception); if ((image_info->ping == MagickFalse) && (status == MagickFalse)) ThrowGIFException(CorruptImageError,"CorruptImage"); if (profiles != (LinkedListInfo *) NULL) { StringInfo *profile; /* Set image profiles. */ ResetLinkedListIterator(profiles); profile=(StringInfo *) GetNextValueInLinkedList(profiles); while (profile != (StringInfo *) NULL) { (void) SetImageProfile(image,GetStringInfoName(profile),profile); profile=(StringInfo *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,DestroyGIFProfile); } duration+=image->delay*image->iterations; if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; opacity=(-1); status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) image->scene- 1,image->scene); if (status == MagickFalse) break; } image->duration=duration; if (profiles != (LinkedListInfo *) NULL) profiles=DestroyLinkedList(profiles,DestroyGIFProfile); meta_image=DestroyImage(meta_image); global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r G I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterGIFImage() adds properties for the GIF image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterGIFImage method is: % % size_t RegisterGIFImage(void) % */ ModuleExport size_t RegisterGIFImage(void) { MagickInfo *entry; entry=SetMagickInfo("GIF"); entry->decoder=(DecodeImageHandler *) ReadGIFImage; entry->encoder=(EncodeImageHandler *) WriteGIFImage; entry->magick=(IsImageFormatHandler *) IsGIF; entry->description=ConstantString("CompuServe graphics interchange format"); entry->mime_type=ConstantString("image/gif"); entry->module=ConstantString("GIF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("GIF87"); entry->decoder=(DecodeImageHandler *) ReadGIFImage; entry->encoder=(EncodeImageHandler *) WriteGIFImage; entry->magick=(IsImageFormatHandler *) IsGIF; entry->adjoin=MagickFalse; entry->description=ConstantString("CompuServe graphics interchange format"); entry->version=ConstantString("version 87a"); entry->mime_type=ConstantString("image/gif"); entry->module=ConstantString("GIF"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r G I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterGIFImage() removes format registrations made by the % GIF module from the list of supported formats. % % The format of the UnregisterGIFImage method is: % % UnregisterGIFImage(void) % */ ModuleExport void UnregisterGIFImage(void) { (void) UnregisterMagickInfo("GIF"); (void) UnregisterMagickInfo("GIF87"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e G I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteGIFImage() writes an image to a file in the Compuserve Graphics % image format. % % The format of the WriteGIFImage method is: % % MagickBooleanType WriteGIFImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteGIFImage(const ImageInfo *image_info,Image *image) { int c; ImageInfo *write_info; MagickBooleanType status; MagickOffsetType scene; RectangleInfo page; register ssize_t i; register unsigned char *q; size_t bits_per_pixel, delay, imageListLength, length, one; ssize_t j, opacity; unsigned char *colormap, *global_colormap; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Allocate colormap. */ global_colormap=(unsigned char *) AcquireQuantumMemory(768UL, sizeof(*global_colormap)); colormap=(unsigned char *) AcquireQuantumMemory(768UL,sizeof(*colormap)); if ((global_colormap == (unsigned char *) NULL) || (colormap == (unsigned char *) NULL)) { if (global_colormap != (unsigned char *) NULL) global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); if (colormap != (unsigned char *) NULL) colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < 768; i++) colormap[i]=(unsigned char) 0; /* Write GIF header. */ write_info=CloneImageInfo(image_info); if (LocaleCompare(write_info->magick,"GIF87") != 0) (void) WriteBlob(image,6,(unsigned char *) "GIF89a"); else { (void) WriteBlob(image,6,(unsigned char *) "GIF87a"); write_info->adjoin=MagickFalse; } /* Determine image bounding box. */ page.width=image->columns; if (image->page.width > page.width) page.width=image->page.width; page.height=image->rows; if (image->page.height > page.height) page.height=image->page.height; page.x=image->page.x; page.y=image->page.y; (void) WriteBlobLSBShort(image,(unsigned short) page.width); (void) WriteBlobLSBShort(image,(unsigned short) page.height); /* Write images to file. */ if ((write_info->adjoin != MagickFalse) && (GetNextImageInList(image) != (Image *) NULL)) write_info->interlace=NoInterlace; scene=0; one=1; imageListLength=GetImageListLength(image); do { (void) TransformImageColorspace(image,sRGBColorspace); opacity=(-1); if (IsOpaqueImage(image,&image->exception) != MagickFalse) { if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) SetImageType(image,PaletteType); } else { double alpha, beta; /* Identify transparent colormap index. */ if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) SetImageType(image,PaletteBilevelMatteType); for (i=0; i < (ssize_t) image->colors; i++) if (image->colormap[i].opacity != OpaqueOpacity) { if (opacity < 0) { opacity=i; continue; } alpha=fabs((double) image->colormap[i].opacity- TransparentOpacity); beta=fabs((double) image->colormap[opacity].opacity- TransparentOpacity); if (alpha < beta) opacity=i; } if (opacity == -1) { (void) SetImageType(image,PaletteBilevelMatteType); for (i=0; i < (ssize_t) image->colors; i++) if (image->colormap[i].opacity != OpaqueOpacity) { if (opacity < 0) { opacity=i; continue; } alpha=fabs((double) image->colormap[i].opacity- TransparentOpacity); beta=fabs((double) image->colormap[opacity].opacity- TransparentOpacity); if (alpha < beta) opacity=i; } } if (opacity >= 0) { image->colormap[opacity].red=image->transparent_color.red; image->colormap[opacity].green=image->transparent_color.green; image->colormap[opacity].blue=image->transparent_color.blue; } } if ((image->storage_class == DirectClass) || (image->colors > 256)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); for (bits_per_pixel=1; bits_per_pixel < 8; bits_per_pixel++) if ((one << bits_per_pixel) >= image->colors) break; q=colormap; for (i=0; i < (ssize_t) image->colors; i++) { *q++=ScaleQuantumToChar(image->colormap[i].red); *q++=ScaleQuantumToChar(image->colormap[i].green); *q++=ScaleQuantumToChar(image->colormap[i].blue); } for ( ; i < (ssize_t) (one << bits_per_pixel); i++) { *q++=(unsigned char) 0x0; *q++=(unsigned char) 0x0; *q++=(unsigned char) 0x0; } if ((GetPreviousImageInList(image) == (Image *) NULL) || (write_info->adjoin == MagickFalse)) { /* Write global colormap. */ c=0x80; c|=(8-1) << 4; /* color resolution */ c|=(bits_per_pixel-1); /* size of global colormap */ (void) WriteBlobByte(image,(unsigned char) c); for (j=0; j < (ssize_t) image->colors; j++) if (IsColorEqual(&image->background_color,image->colormap+j)) break; (void) WriteBlobByte(image,(unsigned char) (j == (ssize_t) image->colors ? 0 : j)); /* background color */ (void) WriteBlobByte(image,(unsigned char) 0x00); /* reserved */ length=(size_t) (3*(one << bits_per_pixel)); (void) WriteBlob(image,length,colormap); for (j=0; j < 768; j++) global_colormap[j]=colormap[j]; } if (LocaleCompare(write_info->magick,"GIF87") != 0) { const char *value; /* Write graphics control extension. */ (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xf9); (void) WriteBlobByte(image,(unsigned char) 0x04); c=image->dispose << 2; if (opacity >= 0) c|=0x01; (void) WriteBlobByte(image,(unsigned char) c); delay=(size_t) (100*image->delay/MagickMax((size_t) image->ticks_per_second,1)); (void) WriteBlobLSBShort(image,(unsigned short) delay); (void) WriteBlobByte(image,(unsigned char) (opacity >= 0 ? opacity : 0)); (void) WriteBlobByte(image,(unsigned char) 0x00); value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) { register const char *p; size_t count; /* Write comment extension. */ (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xfe); for (p=value; *p != '\0'; ) { count=MagickMin(strlen(p),255); (void) WriteBlobByte(image,(unsigned char) count); for (i=0; i < (ssize_t) count; i++) (void) WriteBlobByte(image,(unsigned char) *p++); } (void) WriteBlobByte(image,(unsigned char) 0x00); } if ((GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) != (Image *) NULL) && (image->iterations != 1)) { /* Write Netscape Loop extension. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","NETSCAPE2.0"); (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xff); (void) WriteBlobByte(image,(unsigned char) 0x0b); (void) WriteBlob(image,11,(unsigned char *) "NETSCAPE2.0"); (void) WriteBlobByte(image,(unsigned char) 0x03); (void) WriteBlobByte(image,(unsigned char) 0x01); (void) WriteBlobLSBShort(image,(unsigned short) (image->iterations ? image->iterations-1 : 0)); (void) WriteBlobByte(image,(unsigned char) 0x00); } if ((image->gamma != 1.0f/2.2f)) { char attributes[MaxTextExtent]; ssize_t count; /* Write ImageMagick extension. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","ImageMagick"); (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xff); (void) WriteBlobByte(image,(unsigned char) 0x0b); (void) WriteBlob(image,11,(unsigned char *) "ImageMagick"); count=FormatLocaleString(attributes,MaxTextExtent,"gamma=%g", image->gamma); (void) WriteBlobByte(image,(unsigned char) count); (void) WriteBlob(image,(size_t) count,(unsigned char *) attributes); (void) WriteBlobByte(image,(unsigned char) 0x00); } ResetImageProfileIterator(image); for ( ; ; ) { char *name; const StringInfo *profile; name=GetNextImageProfile(image); if (name == (const char *) NULL) break; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0) || (LocaleCompare(name,"IPTC") == 0) || (LocaleCompare(name,"8BIM") == 0) || (LocaleNCompare(name,"gif:",4) == 0)) { size_t length; ssize_t offset; unsigned char *datum; datum=GetStringInfoDatum(profile); length=GetStringInfoLength(profile); (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xff); (void) WriteBlobByte(image,(unsigned char) 0x0b); if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { /* Write ICC extension. */ (void) WriteBlob(image,11,(unsigned char *) "ICCRGBG1012"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","ICCRGBG1012"); } else if ((LocaleCompare(name,"IPTC") == 0)) { /* Write IPTC extension. */ (void) WriteBlob(image,11,(unsigned char *) "MGKIPTC0000"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","MGKIPTC0000"); } else if ((LocaleCompare(name,"8BIM") == 0)) { /* Write 8BIM extension. */ (void) WriteBlob(image,11,(unsigned char *) "MGK8BIM0000"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","MGK8BIM0000"); } else { char extension[MaxTextExtent]; /* Write generic extension. */ (void) CopyMagickString(extension,name+4, sizeof(extension)); (void) WriteBlob(image,11,(unsigned char *) extension); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s",name); } offset=0; while ((ssize_t) length > offset) { size_t block_length; if ((length-offset) < 255) block_length=length-offset; else block_length=255; (void) WriteBlobByte(image,(unsigned char) block_length); (void) WriteBlob(image,(size_t) block_length,datum+offset); offset+=(ssize_t) block_length; } (void) WriteBlobByte(image,(unsigned char) 0x00); } } } } (void) WriteBlobByte(image,','); /* image separator */ /* Write the image header. */ page.x=image->page.x; page.y=image->page.y; if ((image->page.width != 0) && (image->page.height != 0)) page=image->page; (void) WriteBlobLSBShort(image,(unsigned short) (page.x < 0 ? 0 : page.x)); (void) WriteBlobLSBShort(image,(unsigned short) (page.y < 0 ? 0 : page.y)); (void) WriteBlobLSBShort(image,(unsigned short) image->columns); (void) WriteBlobLSBShort(image,(unsigned short) image->rows); c=0x00; if (write_info->interlace != NoInterlace) c|=0x40; /* pixel data is interlaced */ for (j=0; j < (ssize_t) (3*image->colors); j++) if (colormap[j] != global_colormap[j]) break; if (j == (ssize_t) (3*image->colors)) (void) WriteBlobByte(image,(unsigned char) c); else { c|=0x80; c|=(bits_per_pixel-1); /* size of local colormap */ (void) WriteBlobByte(image,(unsigned char) c); length=(size_t) (3*(one << bits_per_pixel)); (void) WriteBlob(image,length,colormap); } /* Write the image data. */ c=(int) MagickMax(bits_per_pixel,2); (void) WriteBlobByte(image,(unsigned char) c); status=EncodeImage(write_info,image,(size_t) MagickMax(bits_per_pixel,2)+1); if (status == MagickFalse) { global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); write_info=DestroyImageInfo(write_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) WriteBlobByte(image,(unsigned char) 0x00); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); scene++; status=SetImageProgress(image,SaveImagesTag,scene,imageListLength); if (status == MagickFalse) break; } while (write_info->adjoin != MagickFalse); (void) WriteBlobByte(image,';'); /* terminator */ global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); write_info=DestroyImageInfo(write_info); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_943_0
crossvul-cpp_data_bad_2273_0
#include <linux/ceph/ceph_debug.h> #include <linux/err.h> #include <linux/module.h> #include <linux/random.h> #include <linux/slab.h> #include <linux/ceph/decode.h> #include <linux/ceph/auth.h> #include "crypto.h" #include "auth_x.h" #include "auth_x_protocol.h" #define TEMP_TICKET_BUF_LEN 256 static void ceph_x_validate_tickets(struct ceph_auth_client *ac, int *pneed); static int ceph_x_is_authenticated(struct ceph_auth_client *ac) { struct ceph_x_info *xi = ac->private; int need; ceph_x_validate_tickets(ac, &need); dout("ceph_x_is_authenticated want=%d need=%d have=%d\n", ac->want_keys, need, xi->have_keys); return (ac->want_keys & xi->have_keys) == ac->want_keys; } static int ceph_x_should_authenticate(struct ceph_auth_client *ac) { struct ceph_x_info *xi = ac->private; int need; ceph_x_validate_tickets(ac, &need); dout("ceph_x_should_authenticate want=%d need=%d have=%d\n", ac->want_keys, need, xi->have_keys); return need != 0; } static int ceph_x_encrypt_buflen(int ilen) { return sizeof(struct ceph_x_encrypt_header) + ilen + 16 + sizeof(u32); } static int ceph_x_encrypt(struct ceph_crypto_key *secret, void *ibuf, int ilen, void *obuf, size_t olen) { struct ceph_x_encrypt_header head = { .struct_v = 1, .magic = cpu_to_le64(CEPHX_ENC_MAGIC) }; size_t len = olen - sizeof(u32); int ret; ret = ceph_encrypt2(secret, obuf + sizeof(u32), &len, &head, sizeof(head), ibuf, ilen); if (ret) return ret; ceph_encode_32(&obuf, len); return len + sizeof(u32); } static int ceph_x_decrypt(struct ceph_crypto_key *secret, void **p, void *end, void *obuf, size_t olen) { struct ceph_x_encrypt_header head; size_t head_len = sizeof(head); int len, ret; len = ceph_decode_32(p); if (*p + len > end) return -EINVAL; dout("ceph_x_decrypt len %d\n", len); ret = ceph_decrypt2(secret, &head, &head_len, obuf, &olen, *p, len); if (ret) return ret; if (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC) return -EPERM; *p += len; return olen; } /* * get existing (or insert new) ticket handler */ static struct ceph_x_ticket_handler * get_ticket_handler(struct ceph_auth_client *ac, int service) { struct ceph_x_ticket_handler *th; struct ceph_x_info *xi = ac->private; struct rb_node *parent = NULL, **p = &xi->ticket_handlers.rb_node; while (*p) { parent = *p; th = rb_entry(parent, struct ceph_x_ticket_handler, node); if (service < th->service) p = &(*p)->rb_left; else if (service > th->service) p = &(*p)->rb_right; else return th; } /* add it */ th = kzalloc(sizeof(*th), GFP_NOFS); if (!th) return ERR_PTR(-ENOMEM); th->service = service; rb_link_node(&th->node, parent, p); rb_insert_color(&th->node, &xi->ticket_handlers); return th; } static void remove_ticket_handler(struct ceph_auth_client *ac, struct ceph_x_ticket_handler *th) { struct ceph_x_info *xi = ac->private; dout("remove_ticket_handler %p %d\n", th, th->service); rb_erase(&th->node, &xi->ticket_handlers); ceph_crypto_key_destroy(&th->session_key); if (th->ticket_blob) ceph_buffer_put(th->ticket_blob); kfree(th); } static int process_one_ticket(struct ceph_auth_client *ac, struct ceph_crypto_key *secret, void **p, void *end, void *dbuf, void *ticket_buf) { struct ceph_x_info *xi = ac->private; int type; u8 tkt_struct_v, blob_struct_v; struct ceph_x_ticket_handler *th; void *dp, *dend; int dlen; char is_enc; struct timespec validity; struct ceph_crypto_key old_key; void *tp, *tpend; struct ceph_timespec new_validity; struct ceph_crypto_key new_session_key; struct ceph_buffer *new_ticket_blob; unsigned long new_expires, new_renew_after; u64 new_secret_id; int ret; ceph_decode_need(p, end, sizeof(u32) + 1, bad); type = ceph_decode_32(p); dout(" ticket type %d %s\n", type, ceph_entity_type_name(type)); tkt_struct_v = ceph_decode_8(p); if (tkt_struct_v != 1) goto bad; th = get_ticket_handler(ac, type); if (IS_ERR(th)) { ret = PTR_ERR(th); goto out; } /* blob for me */ dlen = ceph_x_decrypt(secret, p, end, dbuf, TEMP_TICKET_BUF_LEN); if (dlen <= 0) { ret = dlen; goto out; } dout(" decrypted %d bytes\n", dlen); dp = dbuf; dend = dp + dlen; tkt_struct_v = ceph_decode_8(&dp); if (tkt_struct_v != 1) goto bad; memcpy(&old_key, &th->session_key, sizeof(old_key)); ret = ceph_crypto_key_decode(&new_session_key, &dp, dend); if (ret) goto out; ceph_decode_copy(&dp, &new_validity, sizeof(new_validity)); ceph_decode_timespec(&validity, &new_validity); new_expires = get_seconds() + validity.tv_sec; new_renew_after = new_expires - (validity.tv_sec / 4); dout(" expires=%lu renew_after=%lu\n", new_expires, new_renew_after); /* ticket blob for service */ ceph_decode_8_safe(p, end, is_enc, bad); tp = ticket_buf; if (is_enc) { /* encrypted */ dout(" encrypted ticket\n"); dlen = ceph_x_decrypt(&old_key, p, end, ticket_buf, TEMP_TICKET_BUF_LEN); if (dlen < 0) { ret = dlen; goto out; } dlen = ceph_decode_32(&tp); } else { /* unencrypted */ ceph_decode_32_safe(p, end, dlen, bad); ceph_decode_need(p, end, dlen, bad); ceph_decode_copy(p, ticket_buf, dlen); } tpend = tp + dlen; dout(" ticket blob is %d bytes\n", dlen); ceph_decode_need(&tp, tpend, 1 + sizeof(u64), bad); blob_struct_v = ceph_decode_8(&tp); new_secret_id = ceph_decode_64(&tp); ret = ceph_decode_buffer(&new_ticket_blob, &tp, tpend); if (ret) goto out; /* all is well, update our ticket */ ceph_crypto_key_destroy(&th->session_key); if (th->ticket_blob) ceph_buffer_put(th->ticket_blob); th->session_key = new_session_key; th->ticket_blob = new_ticket_blob; th->validity = new_validity; th->secret_id = new_secret_id; th->expires = new_expires; th->renew_after = new_renew_after; dout(" got ticket service %d (%s) secret_id %lld len %d\n", type, ceph_entity_type_name(type), th->secret_id, (int)th->ticket_blob->vec.iov_len); xi->have_keys |= th->service; out: return ret; bad: ret = -EINVAL; goto out; } static int ceph_x_proc_ticket_reply(struct ceph_auth_client *ac, struct ceph_crypto_key *secret, void *buf, void *end) { void *p = buf; char *dbuf; char *ticket_buf; u8 reply_struct_v; u32 num; int ret; dbuf = kmalloc(TEMP_TICKET_BUF_LEN, GFP_NOFS); if (!dbuf) return -ENOMEM; ret = -ENOMEM; ticket_buf = kmalloc(TEMP_TICKET_BUF_LEN, GFP_NOFS); if (!ticket_buf) goto out_dbuf; ceph_decode_8_safe(&p, end, reply_struct_v, bad); if (reply_struct_v != 1) return -EINVAL; ceph_decode_32_safe(&p, end, num, bad); dout("%d tickets\n", num); while (num--) { ret = process_one_ticket(ac, secret, &p, end, dbuf, ticket_buf); if (ret) goto out; } ret = 0; out: kfree(ticket_buf); out_dbuf: kfree(dbuf); return ret; bad: ret = -EINVAL; goto out; } static int ceph_x_build_authorizer(struct ceph_auth_client *ac, struct ceph_x_ticket_handler *th, struct ceph_x_authorizer *au) { int maxlen; struct ceph_x_authorize_a *msg_a; struct ceph_x_authorize_b msg_b; void *p, *end; int ret; int ticket_blob_len = (th->ticket_blob ? th->ticket_blob->vec.iov_len : 0); dout("build_authorizer for %s %p\n", ceph_entity_type_name(th->service), au); maxlen = sizeof(*msg_a) + sizeof(msg_b) + ceph_x_encrypt_buflen(ticket_blob_len); dout(" need len %d\n", maxlen); if (au->buf && au->buf->alloc_len < maxlen) { ceph_buffer_put(au->buf); au->buf = NULL; } if (!au->buf) { au->buf = ceph_buffer_new(maxlen, GFP_NOFS); if (!au->buf) return -ENOMEM; } au->service = th->service; au->secret_id = th->secret_id; msg_a = au->buf->vec.iov_base; msg_a->struct_v = 1; msg_a->global_id = cpu_to_le64(ac->global_id); msg_a->service_id = cpu_to_le32(th->service); msg_a->ticket_blob.struct_v = 1; msg_a->ticket_blob.secret_id = cpu_to_le64(th->secret_id); msg_a->ticket_blob.blob_len = cpu_to_le32(ticket_blob_len); if (ticket_blob_len) { memcpy(msg_a->ticket_blob.blob, th->ticket_blob->vec.iov_base, th->ticket_blob->vec.iov_len); } dout(" th %p secret_id %lld %lld\n", th, th->secret_id, le64_to_cpu(msg_a->ticket_blob.secret_id)); p = msg_a + 1; p += ticket_blob_len; end = au->buf->vec.iov_base + au->buf->vec.iov_len; get_random_bytes(&au->nonce, sizeof(au->nonce)); msg_b.struct_v = 1; msg_b.nonce = cpu_to_le64(au->nonce); ret = ceph_x_encrypt(&th->session_key, &msg_b, sizeof(msg_b), p, end - p); if (ret < 0) goto out_buf; p += ret; au->buf->vec.iov_len = p - au->buf->vec.iov_base; dout(" built authorizer nonce %llx len %d\n", au->nonce, (int)au->buf->vec.iov_len); BUG_ON(au->buf->vec.iov_len > maxlen); return 0; out_buf: ceph_buffer_put(au->buf); au->buf = NULL; return ret; } static int ceph_x_encode_ticket(struct ceph_x_ticket_handler *th, void **p, void *end) { ceph_decode_need(p, end, 1 + sizeof(u64), bad); ceph_encode_8(p, 1); ceph_encode_64(p, th->secret_id); if (th->ticket_blob) { const char *buf = th->ticket_blob->vec.iov_base; u32 len = th->ticket_blob->vec.iov_len; ceph_encode_32_safe(p, end, len, bad); ceph_encode_copy_safe(p, end, buf, len, bad); } else { ceph_encode_32_safe(p, end, 0, bad); } return 0; bad: return -ERANGE; } static void ceph_x_validate_tickets(struct ceph_auth_client *ac, int *pneed) { int want = ac->want_keys; struct ceph_x_info *xi = ac->private; int service; *pneed = ac->want_keys & ~(xi->have_keys); for (service = 1; service <= want; service <<= 1) { struct ceph_x_ticket_handler *th; if (!(ac->want_keys & service)) continue; if (*pneed & service) continue; th = get_ticket_handler(ac, service); if (IS_ERR(th)) { *pneed |= service; continue; } if (get_seconds() >= th->renew_after) *pneed |= service; if (get_seconds() >= th->expires) xi->have_keys &= ~service; } } static int ceph_x_build_request(struct ceph_auth_client *ac, void *buf, void *end) { struct ceph_x_info *xi = ac->private; int need; struct ceph_x_request_header *head = buf; int ret; struct ceph_x_ticket_handler *th = get_ticket_handler(ac, CEPH_ENTITY_TYPE_AUTH); if (IS_ERR(th)) return PTR_ERR(th); ceph_x_validate_tickets(ac, &need); dout("build_request want %x have %x need %x\n", ac->want_keys, xi->have_keys, need); if (need & CEPH_ENTITY_TYPE_AUTH) { struct ceph_x_authenticate *auth = (void *)(head + 1); void *p = auth + 1; struct ceph_x_challenge_blob tmp; char tmp_enc[40]; u64 *u; if (p > end) return -ERANGE; dout(" get_auth_session_key\n"); head->op = cpu_to_le16(CEPHX_GET_AUTH_SESSION_KEY); /* encrypt and hash */ get_random_bytes(&auth->client_challenge, sizeof(u64)); tmp.client_challenge = auth->client_challenge; tmp.server_challenge = cpu_to_le64(xi->server_challenge); ret = ceph_x_encrypt(&xi->secret, &tmp, sizeof(tmp), tmp_enc, sizeof(tmp_enc)); if (ret < 0) return ret; auth->struct_v = 1; auth->key = 0; for (u = (u64 *)tmp_enc; u + 1 <= (u64 *)(tmp_enc + ret); u++) auth->key ^= *(__le64 *)u; dout(" server_challenge %llx client_challenge %llx key %llx\n", xi->server_challenge, le64_to_cpu(auth->client_challenge), le64_to_cpu(auth->key)); /* now encode the old ticket if exists */ ret = ceph_x_encode_ticket(th, &p, end); if (ret < 0) return ret; return p - buf; } if (need) { void *p = head + 1; struct ceph_x_service_ticket_request *req; if (p > end) return -ERANGE; head->op = cpu_to_le16(CEPHX_GET_PRINCIPAL_SESSION_KEY); ret = ceph_x_build_authorizer(ac, th, &xi->auth_authorizer); if (ret) return ret; ceph_encode_copy(&p, xi->auth_authorizer.buf->vec.iov_base, xi->auth_authorizer.buf->vec.iov_len); req = p; req->keys = cpu_to_le32(need); p += sizeof(*req); return p - buf; } return 0; } static int ceph_x_handle_reply(struct ceph_auth_client *ac, int result, void *buf, void *end) { struct ceph_x_info *xi = ac->private; struct ceph_x_reply_header *head = buf; struct ceph_x_ticket_handler *th; int len = end - buf; int op; int ret; if (result) return result; /* XXX hmm? */ if (xi->starting) { /* it's a hello */ struct ceph_x_server_challenge *sc = buf; if (len != sizeof(*sc)) return -EINVAL; xi->server_challenge = le64_to_cpu(sc->server_challenge); dout("handle_reply got server challenge %llx\n", xi->server_challenge); xi->starting = false; xi->have_keys &= ~CEPH_ENTITY_TYPE_AUTH; return -EAGAIN; } op = le16_to_cpu(head->op); result = le32_to_cpu(head->result); dout("handle_reply op %d result %d\n", op, result); switch (op) { case CEPHX_GET_AUTH_SESSION_KEY: /* verify auth key */ ret = ceph_x_proc_ticket_reply(ac, &xi->secret, buf + sizeof(*head), end); break; case CEPHX_GET_PRINCIPAL_SESSION_KEY: th = get_ticket_handler(ac, CEPH_ENTITY_TYPE_AUTH); if (IS_ERR(th)) return PTR_ERR(th); ret = ceph_x_proc_ticket_reply(ac, &th->session_key, buf + sizeof(*head), end); break; default: return -EINVAL; } if (ret) return ret; if (ac->want_keys == xi->have_keys) return 0; return -EAGAIN; } static int ceph_x_create_authorizer( struct ceph_auth_client *ac, int peer_type, struct ceph_auth_handshake *auth) { struct ceph_x_authorizer *au; struct ceph_x_ticket_handler *th; int ret; th = get_ticket_handler(ac, peer_type); if (IS_ERR(th)) return PTR_ERR(th); au = kzalloc(sizeof(*au), GFP_NOFS); if (!au) return -ENOMEM; ret = ceph_x_build_authorizer(ac, th, au); if (ret) { kfree(au); return ret; } auth->authorizer = (struct ceph_authorizer *) au; auth->authorizer_buf = au->buf->vec.iov_base; auth->authorizer_buf_len = au->buf->vec.iov_len; auth->authorizer_reply_buf = au->reply_buf; auth->authorizer_reply_buf_len = sizeof (au->reply_buf); return 0; } static int ceph_x_update_authorizer( struct ceph_auth_client *ac, int peer_type, struct ceph_auth_handshake *auth) { struct ceph_x_authorizer *au; struct ceph_x_ticket_handler *th; th = get_ticket_handler(ac, peer_type); if (IS_ERR(th)) return PTR_ERR(th); au = (struct ceph_x_authorizer *)auth->authorizer; if (au->secret_id < th->secret_id) { dout("ceph_x_update_authorizer service %u secret %llu < %llu\n", au->service, au->secret_id, th->secret_id); return ceph_x_build_authorizer(ac, th, au); } return 0; } static int ceph_x_verify_authorizer_reply(struct ceph_auth_client *ac, struct ceph_authorizer *a, size_t len) { struct ceph_x_authorizer *au = (void *)a; struct ceph_x_ticket_handler *th; int ret = 0; struct ceph_x_authorize_reply reply; void *p = au->reply_buf; void *end = p + sizeof(au->reply_buf); th = get_ticket_handler(ac, au->service); if (IS_ERR(th)) return PTR_ERR(th); ret = ceph_x_decrypt(&th->session_key, &p, end, &reply, sizeof(reply)); if (ret < 0) return ret; if (ret != sizeof(reply)) return -EPERM; if (au->nonce + 1 != le64_to_cpu(reply.nonce_plus_one)) ret = -EPERM; else ret = 0; dout("verify_authorizer_reply nonce %llx got %llx ret %d\n", au->nonce, le64_to_cpu(reply.nonce_plus_one), ret); return ret; } static void ceph_x_destroy_authorizer(struct ceph_auth_client *ac, struct ceph_authorizer *a) { struct ceph_x_authorizer *au = (void *)a; ceph_buffer_put(au->buf); kfree(au); } static void ceph_x_reset(struct ceph_auth_client *ac) { struct ceph_x_info *xi = ac->private; dout("reset\n"); xi->starting = true; xi->server_challenge = 0; } static void ceph_x_destroy(struct ceph_auth_client *ac) { struct ceph_x_info *xi = ac->private; struct rb_node *p; dout("ceph_x_destroy %p\n", ac); ceph_crypto_key_destroy(&xi->secret); while ((p = rb_first(&xi->ticket_handlers)) != NULL) { struct ceph_x_ticket_handler *th = rb_entry(p, struct ceph_x_ticket_handler, node); remove_ticket_handler(ac, th); } if (xi->auth_authorizer.buf) ceph_buffer_put(xi->auth_authorizer.buf); kfree(ac->private); ac->private = NULL; } static void ceph_x_invalidate_authorizer(struct ceph_auth_client *ac, int peer_type) { struct ceph_x_ticket_handler *th; th = get_ticket_handler(ac, peer_type); if (!IS_ERR(th)) memset(&th->validity, 0, sizeof(th->validity)); } static const struct ceph_auth_client_ops ceph_x_ops = { .name = "x", .is_authenticated = ceph_x_is_authenticated, .should_authenticate = ceph_x_should_authenticate, .build_request = ceph_x_build_request, .handle_reply = ceph_x_handle_reply, .create_authorizer = ceph_x_create_authorizer, .update_authorizer = ceph_x_update_authorizer, .verify_authorizer_reply = ceph_x_verify_authorizer_reply, .destroy_authorizer = ceph_x_destroy_authorizer, .invalidate_authorizer = ceph_x_invalidate_authorizer, .reset = ceph_x_reset, .destroy = ceph_x_destroy, }; int ceph_x_init(struct ceph_auth_client *ac) { struct ceph_x_info *xi; int ret; dout("ceph_x_init %p\n", ac); ret = -ENOMEM; xi = kzalloc(sizeof(*xi), GFP_NOFS); if (!xi) goto out; ret = -EINVAL; if (!ac->key) { pr_err("no secret set (for auth_x protocol)\n"); goto out_nomem; } ret = ceph_crypto_key_clone(&xi->secret, ac->key); if (ret < 0) { pr_err("cannot clone key: %d\n", ret); goto out_nomem; } xi->starting = true; xi->ticket_handlers = RB_ROOT; ac->protocol = CEPH_AUTH_CEPHX; ac->private = xi; ac->ops = &ceph_x_ops; return 0; out_nomem: kfree(xi); out: return ret; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2273_0
crossvul-cpp_data_bad_5281_0
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 2006-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <andrey@mysql.com> | | Ulf Wendel <uwendel@mysql.com> | | Georg Richter <georg@mysql.com> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_globals.h" #include "mysqlnd.h" #include "mysqlnd_priv.h" #include "mysqlnd_wireprotocol.h" #include "mysqlnd_statistics.h" #include "mysqlnd_debug.h" #include "zend_ini.h" #define MYSQLND_SILENT 1 #define MYSQLND_DUMP_HEADER_N_BODY #define PACKET_READ_HEADER_AND_BODY(packet, conn, buf, buf_size, packet_type_as_text, packet_type) \ { \ DBG_INF_FMT("buf=%p size=%u", (buf), (buf_size)); \ if (FAIL == mysqlnd_read_header((conn)->net, &((packet)->header), (conn)->stats, ((conn)->error_info) TSRMLS_CC)) {\ CONN_SET_STATE(conn, CONN_QUIT_SENT); \ SET_CLIENT_ERROR(*conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone);\ php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", mysqlnd_server_gone); \ DBG_ERR_FMT("Can't read %s's header", (packet_type_as_text)); \ DBG_RETURN(FAIL);\ }\ if ((buf_size) < (packet)->header.size) { \ DBG_ERR_FMT("Packet buffer %u wasn't big enough %u, %u bytes will be unread", \ (buf_size), (packet)->header.size, (packet)->header.size - (buf_size)); \ DBG_RETURN(FAIL); \ }\ if (FAIL == conn->net->data->m.receive_ex((conn)->net, (buf), (packet)->header.size, (conn)->stats, ((conn)->error_info) TSRMLS_CC)) { \ CONN_SET_STATE(conn, CONN_QUIT_SENT); \ SET_CLIENT_ERROR(*conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone);\ php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", mysqlnd_server_gone); \ DBG_ERR_FMT("Empty '%s' packet body", (packet_type_as_text)); \ DBG_RETURN(FAIL);\ } \ MYSQLND_INC_CONN_STATISTIC_W_VALUE2(conn->stats, packet_type_to_statistic_byte_count[packet_type], \ MYSQLND_HEADER_SIZE + (packet)->header.size, \ packet_type_to_statistic_packet_count[packet_type], \ 1); \ } #define BAIL_IF_NO_MORE_DATA \ if ((size_t)(p - begin) > packet->header.size) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Premature end of data (mysqlnd_wireprotocol.c:%u)", __LINE__); \ goto premature_end; \ } \ static const char *unknown_sqlstate= "HY000"; const char * const mysqlnd_empty_string = ""; /* Used in mysqlnd_debug.c */ const char mysqlnd_read_header_name[] = "mysqlnd_read_header"; const char mysqlnd_read_body_name[] = "mysqlnd_read_body"; #define ERROR_MARKER 0xFF #define EODATA_MARKER 0xFE /* {{{ mysqlnd_command_to_text */ const char * const mysqlnd_command_to_text[COM_END] = { "SLEEP", "QUIT", "INIT_DB", "QUERY", "FIELD_LIST", "CREATE_DB", "DROP_DB", "REFRESH", "SHUTDOWN", "STATISTICS", "PROCESS_INFO", "CONNECT", "PROCESS_KILL", "DEBUG", "PING", "TIME", "DELAYED_INSERT", "CHANGE_USER", "BINLOG_DUMP", "TABLE_DUMP", "CONNECT_OUT", "REGISTER_SLAVE", "STMT_PREPARE", "STMT_EXECUTE", "STMT_SEND_LONG_DATA", "STMT_CLOSE", "STMT_RESET", "SET_OPTION", "STMT_FETCH", "DAEMON", "BINLOG_DUMP_GTID", "RESET_CONNECTION" }; /* }}} */ static enum_mysqlnd_collected_stats packet_type_to_statistic_byte_count[PROT_LAST] = { STAT_LAST, STAT_LAST, STAT_BYTES_RECEIVED_OK, STAT_BYTES_RECEIVED_EOF, STAT_LAST, STAT_BYTES_RECEIVED_RSET_HEADER, STAT_BYTES_RECEIVED_RSET_FIELD_META, STAT_BYTES_RECEIVED_RSET_ROW, STAT_BYTES_RECEIVED_PREPARE_RESPONSE, STAT_BYTES_RECEIVED_CHANGE_USER, }; static enum_mysqlnd_collected_stats packet_type_to_statistic_packet_count[PROT_LAST] = { STAT_LAST, STAT_LAST, STAT_PACKETS_RECEIVED_OK, STAT_PACKETS_RECEIVED_EOF, STAT_LAST, STAT_PACKETS_RECEIVED_RSET_HEADER, STAT_PACKETS_RECEIVED_RSET_FIELD_META, STAT_PACKETS_RECEIVED_RSET_ROW, STAT_PACKETS_RECEIVED_PREPARE_RESPONSE, STAT_PACKETS_RECEIVED_CHANGE_USER, }; /* {{{ php_mysqlnd_net_field_length Get next field's length */ unsigned long php_mysqlnd_net_field_length(zend_uchar **packet) { register zend_uchar *p= (zend_uchar *)*packet; if (*p < 251) { (*packet)++; return (unsigned long) *p; } switch (*p) { case 251: (*packet)++; return MYSQLND_NULL_LENGTH; case 252: (*packet) += 3; return (unsigned long) uint2korr(p+1); case 253: (*packet) += 4; return (unsigned long) uint3korr(p+1); default: (*packet) += 9; return (unsigned long) uint4korr(p+1); } } /* }}} */ /* {{{ php_mysqlnd_net_field_length_ll Get next field's length */ uint64_t php_mysqlnd_net_field_length_ll(zend_uchar **packet) { register zend_uchar *p= (zend_uchar *)*packet; if (*p < 251) { (*packet)++; return (uint64_t) *p; } switch (*p) { case 251: (*packet)++; return (uint64_t) MYSQLND_NULL_LENGTH; case 252: (*packet) += 3; return (uint64_t) uint2korr(p + 1); case 253: (*packet) += 4; return (uint64_t) uint3korr(p + 1); default: (*packet) += 9; return (uint64_t) uint8korr(p + 1); } } /* }}} */ /* {{{ php_mysqlnd_net_store_length */ zend_uchar * php_mysqlnd_net_store_length(zend_uchar *packet, uint64_t length) { if (length < (uint64_t) L64(251)) { *packet = (zend_uchar) length; return packet + 1; } if (length < (uint64_t) L64(65536)) { *packet++ = 252; int2store(packet,(unsigned int) length); return packet + 2; } if (length < (uint64_t) L64(16777216)) { *packet++ = 253; int3store(packet,(ulong) length); return packet + 3; } *packet++ = 254; int8store(packet, length); return packet + 8; } /* }}} */ /* {{{ php_mysqlnd_net_store_length_size */ size_t php_mysqlnd_net_store_length_size(uint64_t length) { if (length < (uint64_t) L64(251)) { return 1; } if (length < (uint64_t) L64(65536)) { return 3; } if (length < (uint64_t) L64(16777216)) { return 4; } return 9; } /* }}} */ /* {{{ php_mysqlnd_read_error_from_line */ static enum_func_status php_mysqlnd_read_error_from_line(zend_uchar *buf, size_t buf_len, char *error, int error_buf_len, unsigned int *error_no, char *sqlstate TSRMLS_DC) { zend_uchar *p = buf; int error_msg_len= 0; DBG_ENTER("php_mysqlnd_read_error_from_line"); *error_no = CR_UNKNOWN_ERROR; memcpy(sqlstate, unknown_sqlstate, MYSQLND_SQLSTATE_LENGTH); if (buf_len > 2) { *error_no = uint2korr(p); p+= 2; /* sqlstate is following. No need to check for buf_left_len as we checked > 2 above, if it was >=2 then we would need a check */ if (*p == '#') { ++p; if ((buf_len - (p - buf)) >= MYSQLND_SQLSTATE_LENGTH) { memcpy(sqlstate, p, MYSQLND_SQLSTATE_LENGTH); p+= MYSQLND_SQLSTATE_LENGTH; } else { goto end; } } if ((buf_len - (p - buf)) > 0) { error_msg_len = MIN((int)((buf_len - (p - buf))), (int) (error_buf_len - 1)); memcpy(error, p, error_msg_len); } } end: sqlstate[MYSQLND_SQLSTATE_LENGTH] = '\0'; error[error_msg_len]= '\0'; DBG_RETURN(FAIL); } /* }}} */ /* {{{ mysqlnd_read_header */ static enum_func_status mysqlnd_read_header(MYSQLND_NET * net, MYSQLND_PACKET_HEADER * header, MYSQLND_STATS * conn_stats, MYSQLND_ERROR_INFO * error_info TSRMLS_DC) { zend_uchar buffer[MYSQLND_HEADER_SIZE]; DBG_ENTER(mysqlnd_read_header_name); DBG_INF_FMT("compressed=%u", net->data->compressed); if (FAIL == net->data->m.receive_ex(net, buffer, MYSQLND_HEADER_SIZE, conn_stats, error_info TSRMLS_CC)) { DBG_RETURN(FAIL); } header->size = uint3korr(buffer); header->packet_no = uint1korr(buffer + 3); #ifdef MYSQLND_DUMP_HEADER_N_BODY DBG_INF_FMT("HEADER: prot_packet_no=%u size=%3u", header->packet_no, header->size); #endif MYSQLND_INC_CONN_STATISTIC_W_VALUE2(conn_stats, STAT_PROTOCOL_OVERHEAD_IN, MYSQLND_HEADER_SIZE, STAT_PACKETS_RECEIVED, 1); if (net->data->compressed || net->packet_no == header->packet_no) { /* Have to increase the number, so we can send correct number back. It will round at 255 as this is unsigned char. The server needs this for simple flow control checking. */ net->packet_no++; DBG_RETURN(PASS); } DBG_ERR_FMT("Logical link: packets out of order. Expected %u received %u. Packet size="MYSQLND_SZ_T_SPEC, net->packet_no, header->packet_no, header->size); php_error(E_WARNING, "Packets out of order. Expected %u received %u. Packet size="MYSQLND_SZ_T_SPEC, net->packet_no, header->packet_no, header->size); DBG_RETURN(FAIL); } /* }}} */ /* {{{ php_mysqlnd_greet_read */ static enum_func_status php_mysqlnd_greet_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { zend_uchar buf[2048]; zend_uchar *p = buf; zend_uchar *begin = buf; zend_uchar *pad_start = NULL; MYSQLND_PACKET_GREET *packet= (MYSQLND_PACKET_GREET *) _packet; DBG_ENTER("php_mysqlnd_greet_read"); PACKET_READ_HEADER_AND_BODY(packet, conn, buf, sizeof(buf), "greeting", PROT_GREET_PACKET); BAIL_IF_NO_MORE_DATA; packet->auth_plugin_data = packet->intern_auth_plugin_data; packet->auth_plugin_data_len = sizeof(packet->intern_auth_plugin_data); if (packet->header.size < sizeof(buf)) { /* Null-terminate the string, so strdup can work even if the packets have a string at the end, which is not ASCIIZ */ buf[packet->header.size] = '\0'; } packet->protocol_version = uint1korr(p); p++; BAIL_IF_NO_MORE_DATA; if (ERROR_MARKER == packet->protocol_version) { php_mysqlnd_read_error_from_line(p, packet->header.size - 1, packet->error, sizeof(packet->error), &packet->error_no, packet->sqlstate TSRMLS_CC); /* The server doesn't send sqlstate in the greet packet. It's a bug#26426 , so we have to set it correctly ourselves. It's probably "Too many connections, which has SQL state 08004". */ if (packet->error_no == 1040) { memcpy(packet->sqlstate, "08004", MYSQLND_SQLSTATE_LENGTH); } DBG_RETURN(PASS); } packet->server_version = estrdup((char *)p); p+= strlen(packet->server_version) + 1; /* eat the '\0' */ BAIL_IF_NO_MORE_DATA; packet->thread_id = uint4korr(p); p+=4; BAIL_IF_NO_MORE_DATA; memcpy(packet->auth_plugin_data, p, SCRAMBLE_LENGTH_323); p+= SCRAMBLE_LENGTH_323; BAIL_IF_NO_MORE_DATA; /* pad1 */ p++; BAIL_IF_NO_MORE_DATA; packet->server_capabilities = uint2korr(p); p+= 2; BAIL_IF_NO_MORE_DATA; packet->charset_no = uint1korr(p); p++; BAIL_IF_NO_MORE_DATA; packet->server_status = uint2korr(p); p+= 2; BAIL_IF_NO_MORE_DATA; /* pad2 */ pad_start = p; p+= 13; BAIL_IF_NO_MORE_DATA; if ((size_t) (p - buf) < packet->header.size) { /* auth_plugin_data is split into two parts */ memcpy(packet->auth_plugin_data + SCRAMBLE_LENGTH_323, p, SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323); p+= SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323; p++; /* 0x0 at the end of the scramble and thus last byte in the packet in 5.1 and previous */ } else { packet->pre41 = TRUE; } /* Is this a 5.5+ server ? */ if ((size_t) (p - buf) < packet->header.size) { /* backtrack one byte, the 0x0 at the end of the scramble in 5.1 and previous */ p--; /* Additional 16 bits for server capabilities */ packet->server_capabilities |= uint2korr(pad_start) << 16; /* And a length of the server scramble in one byte */ packet->auth_plugin_data_len = uint1korr(pad_start + 2); if (packet->auth_plugin_data_len > SCRAMBLE_LENGTH) { /* more data*/ zend_uchar * new_auth_plugin_data = emalloc(packet->auth_plugin_data_len); if (!new_auth_plugin_data) { goto premature_end; } /* copy what we already have */ memcpy(new_auth_plugin_data, packet->auth_plugin_data, SCRAMBLE_LENGTH); /* add additional scramble data 5.5+ sent us */ memcpy(new_auth_plugin_data + SCRAMBLE_LENGTH, p, packet->auth_plugin_data_len - SCRAMBLE_LENGTH); p+= (packet->auth_plugin_data_len - SCRAMBLE_LENGTH); packet->auth_plugin_data = new_auth_plugin_data; } } if (packet->server_capabilities & CLIENT_PLUGIN_AUTH) { BAIL_IF_NO_MORE_DATA; /* The server is 5.5.x and supports authentication plugins */ packet->auth_protocol = estrdup((char *)p); p+= strlen(packet->auth_protocol) + 1; /* eat the '\0' */ } DBG_INF_FMT("proto=%u server=%s thread_id=%u", packet->protocol_version, packet->server_version, packet->thread_id); DBG_INF_FMT("server_capabilities=%u charset_no=%u server_status=%i auth_protocol=%s scramble_length=%u", packet->server_capabilities, packet->charset_no, packet->server_status, packet->auth_protocol? packet->auth_protocol:"n/a", packet->auth_plugin_data_len); DBG_RETURN(PASS); premature_end: DBG_ERR_FMT("GREET packet %d bytes shorter than expected", p - begin - packet->header.size); php_error_docref(NULL TSRMLS_CC, E_WARNING, "GREET packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", p - begin - packet->header.size); DBG_RETURN(FAIL); } /* }}} */ /* {{{ php_mysqlnd_greet_free_mem */ static void php_mysqlnd_greet_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { MYSQLND_PACKET_GREET *p= (MYSQLND_PACKET_GREET *) _packet; if (p->server_version) { efree(p->server_version); p->server_version = NULL; } if (p->auth_plugin_data && p->auth_plugin_data != p->intern_auth_plugin_data) { efree(p->auth_plugin_data); p->auth_plugin_data = NULL; } if (p->auth_protocol) { efree(p->auth_protocol); p->auth_protocol = NULL; } if (!stack_allocation) { mnd_pefree(p, p->header.persistent); } } /* }}} */ #define AUTH_WRITE_BUFFER_LEN (MYSQLND_HEADER_SIZE + MYSQLND_MAX_ALLOWED_USER_LEN + SCRAMBLE_LENGTH + MYSQLND_MAX_ALLOWED_DB_LEN + 1 + 4096) /* {{{ php_mysqlnd_auth_write */ static size_t php_mysqlnd_auth_write(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { zend_uchar buffer[AUTH_WRITE_BUFFER_LEN]; zend_uchar *p = buffer + MYSQLND_HEADER_SIZE; /* start after the header */ int len; MYSQLND_PACKET_AUTH * packet= (MYSQLND_PACKET_AUTH *) _packet; DBG_ENTER("php_mysqlnd_auth_write"); if (!packet->is_change_user_packet) { int4store(p, packet->client_flags); p+= 4; int4store(p, packet->max_packet_size); p+= 4; int1store(p, packet->charset_no); p++; memset(p, 0, 23); /* filler */ p+= 23; } if (packet->send_auth_data || packet->is_change_user_packet) { len = MIN(strlen(packet->user), MYSQLND_MAX_ALLOWED_USER_LEN); memcpy(p, packet->user, len); p+= len; *p++ = '\0'; /* defensive coding */ if (packet->auth_data == NULL) { packet->auth_data_len = 0; } if (packet->auth_data_len > 0xFF) { const char * const msg = "Authentication data too long. " "Won't fit into the buffer and will be truncated. Authentication will thus fail"; SET_CLIENT_ERROR(*conn->error_info, CR_UNKNOWN_ERROR, UNKNOWN_SQLSTATE, msg); php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", msg); DBG_RETURN(0); } int1store(p, packet->auth_data_len); ++p; /*!!!!! is the buffer big enough ??? */ if ((sizeof(buffer) - (p - buffer)) < packet->auth_data_len) { DBG_ERR("the stack buffer was not enough!!"); DBG_RETURN(0); } if (packet->auth_data_len) { memcpy(p, packet->auth_data, packet->auth_data_len); p+= packet->auth_data_len; } if (packet->db) { /* CLIENT_CONNECT_WITH_DB should have been set */ size_t real_db_len = MIN(MYSQLND_MAX_ALLOWED_DB_LEN, packet->db_len); memcpy(p, packet->db, real_db_len); p+= real_db_len; *p++= '\0'; } else if (packet->is_change_user_packet) { *p++= '\0'; } /* no \0 for no DB */ if (packet->is_change_user_packet) { if (packet->charset_no) { int2store(p, packet->charset_no); p+= 2; } } if (packet->auth_plugin_name) { size_t len = MIN(strlen(packet->auth_plugin_name), sizeof(buffer) - (p - buffer) - 1); memcpy(p, packet->auth_plugin_name, len); p+= len; *p++= '\0'; } if (packet->connect_attr && zend_hash_num_elements(packet->connect_attr)) { HashPosition pos_value; const char ** entry_value; size_t ca_payload_len = 0; zend_hash_internal_pointer_reset_ex(packet->connect_attr, &pos_value); while (SUCCESS == zend_hash_get_current_data_ex(packet->connect_attr, (void **)&entry_value, &pos_value)) { char *s_key; unsigned int s_len; unsigned long num_key; size_t value_len = strlen(*entry_value); if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(packet->connect_attr, &s_key, &s_len, &num_key, 0, &pos_value)) { ca_payload_len += php_mysqlnd_net_store_length_size(s_len); ca_payload_len += s_len; ca_payload_len += php_mysqlnd_net_store_length_size(value_len); ca_payload_len += value_len; } zend_hash_move_forward_ex(conn->options->connect_attr, &pos_value); } if ((sizeof(buffer) - (p - buffer)) >= (ca_payload_len + php_mysqlnd_net_store_length_size(ca_payload_len))) { p = php_mysqlnd_net_store_length(p, ca_payload_len); zend_hash_internal_pointer_reset_ex(packet->connect_attr, &pos_value); while (SUCCESS == zend_hash_get_current_data_ex(packet->connect_attr, (void **)&entry_value, &pos_value)) { char *s_key; unsigned int s_len; unsigned long num_key; size_t value_len = strlen(*entry_value); if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(packet->connect_attr, &s_key, &s_len, &num_key, 0, &pos_value)) { /* copy key */ p = php_mysqlnd_net_store_length(p, s_len); memcpy(p, s_key, s_len); p+= s_len; /* copy value */ p = php_mysqlnd_net_store_length(p, value_len); memcpy(p, *entry_value, value_len); p+= value_len; } zend_hash_move_forward_ex(conn->options->connect_attr, &pos_value); } } else { /* cannot put the data - skip */ } } } if (packet->is_change_user_packet) { if (PASS != conn->m->simple_command(conn, COM_CHANGE_USER, buffer + MYSQLND_HEADER_SIZE, p - buffer - MYSQLND_HEADER_SIZE, PROT_LAST /* the caller will handle the OK packet */, packet->silent, TRUE TSRMLS_CC)) { DBG_RETURN(0); } DBG_RETURN(p - buffer - MYSQLND_HEADER_SIZE); } else { size_t sent = conn->net->data->m.send_ex(conn->net, buffer, p - buffer - MYSQLND_HEADER_SIZE, conn->stats, conn->error_info TSRMLS_CC); if (!sent) { CONN_SET_STATE(conn, CONN_QUIT_SENT); } DBG_RETURN(sent); } } /* }}} */ /* {{{ php_mysqlnd_auth_free_mem */ static void php_mysqlnd_auth_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { if (!stack_allocation) { MYSQLND_PACKET_AUTH * p = (MYSQLND_PACKET_AUTH *) _packet; mnd_pefree(p, p->header.persistent); } } /* }}} */ #define AUTH_RESP_BUFFER_SIZE 2048 /* {{{ php_mysqlnd_auth_response_read */ static enum_func_status php_mysqlnd_auth_response_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { zend_uchar local_buf[AUTH_RESP_BUFFER_SIZE]; size_t buf_len = conn->net->cmd_buffer.buffer? conn->net->cmd_buffer.length: AUTH_RESP_BUFFER_SIZE; zend_uchar *buf = conn->net->cmd_buffer.buffer? (zend_uchar *) conn->net->cmd_buffer.buffer : local_buf; zend_uchar *p = buf; zend_uchar *begin = buf; unsigned long i; register MYSQLND_PACKET_AUTH_RESPONSE * packet= (MYSQLND_PACKET_AUTH_RESPONSE *) _packet; DBG_ENTER("php_mysqlnd_auth_response_read"); /* leave space for terminating safety \0 */ buf_len--; PACKET_READ_HEADER_AND_BODY(packet, conn, buf, buf_len, "OK", PROT_OK_PACKET); BAIL_IF_NO_MORE_DATA; /* zero-terminate the buffer for safety. We are sure there is place for the \0 because buf_len is -1 the size of the buffer pointed */ buf[packet->header.size] = '\0'; /* Should be always 0x0 or ERROR_MARKER for error */ packet->response_code = uint1korr(p); p++; BAIL_IF_NO_MORE_DATA; if (ERROR_MARKER == packet->response_code) { php_mysqlnd_read_error_from_line(p, packet->header.size - 1, packet->error, sizeof(packet->error), &packet->error_no, packet->sqlstate TSRMLS_CC); DBG_RETURN(PASS); } if (0xFE == packet->response_code) { /* Authentication Switch Response */ if (packet->header.size > (size_t) (p - buf)) { packet->new_auth_protocol = mnd_pestrdup((char *)p, FALSE); packet->new_auth_protocol_len = strlen(packet->new_auth_protocol); p+= packet->new_auth_protocol_len + 1; /* +1 for the \0 */ packet->new_auth_protocol_data_len = packet->header.size - (size_t) (p - buf); if (packet->new_auth_protocol_data_len) { packet->new_auth_protocol_data = mnd_emalloc(packet->new_auth_protocol_data_len); memcpy(packet->new_auth_protocol_data, p, packet->new_auth_protocol_data_len); } DBG_INF_FMT("The server requested switching auth plugin to : %s", packet->new_auth_protocol); DBG_INF_FMT("Server salt : [%d][%.*s]", packet->new_auth_protocol_data_len, packet->new_auth_protocol_data_len, packet->new_auth_protocol_data); } } else { /* Everything was fine! */ packet->affected_rows = php_mysqlnd_net_field_length_ll(&p); BAIL_IF_NO_MORE_DATA; packet->last_insert_id = php_mysqlnd_net_field_length_ll(&p); BAIL_IF_NO_MORE_DATA; packet->server_status = uint2korr(p); p+= 2; BAIL_IF_NO_MORE_DATA; packet->warning_count = uint2korr(p); p+= 2; BAIL_IF_NO_MORE_DATA; /* There is a message */ if (packet->header.size > (size_t) (p - buf) && (i = php_mysqlnd_net_field_length(&p))) { packet->message_len = MIN(i, buf_len - (p - begin)); packet->message = mnd_pestrndup((char *)p, packet->message_len, FALSE); } else { packet->message = NULL; packet->message_len = 0; } DBG_INF_FMT("OK packet: aff_rows=%lld last_ins_id=%ld server_status=%u warnings=%u", packet->affected_rows, packet->last_insert_id, packet->server_status, packet->warning_count); } DBG_RETURN(PASS); premature_end: DBG_ERR_FMT("OK packet %d bytes shorter than expected", p - begin - packet->header.size); php_error_docref(NULL TSRMLS_CC, E_WARNING, "AUTH_RESPONSE packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", p - begin - packet->header.size); DBG_RETURN(FAIL); } /* }}} */ /* {{{ php_mysqlnd_auth_response_free_mem */ static void php_mysqlnd_auth_response_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { MYSQLND_PACKET_AUTH_RESPONSE * p = (MYSQLND_PACKET_AUTH_RESPONSE *) _packet; if (p->message) { mnd_efree(p->message); p->message = NULL; } if (p->new_auth_protocol) { mnd_efree(p->new_auth_protocol); p->new_auth_protocol = NULL; } p->new_auth_protocol_len = 0; if (p->new_auth_protocol_data) { mnd_efree(p->new_auth_protocol_data); p->new_auth_protocol_data = NULL; } p->new_auth_protocol_data_len = 0; if (!stack_allocation) { mnd_pefree(p, p->header.persistent); } } /* }}} */ /* {{{ php_mysqlnd_change_auth_response_write */ static size_t php_mysqlnd_change_auth_response_write(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { MYSQLND_PACKET_CHANGE_AUTH_RESPONSE *packet= (MYSQLND_PACKET_CHANGE_AUTH_RESPONSE *) _packet; zend_uchar * buffer = conn->net->cmd_buffer.length >= packet->auth_data_len? conn->net->cmd_buffer.buffer : mnd_emalloc(packet->auth_data_len); zend_uchar *p = buffer + MYSQLND_HEADER_SIZE; /* start after the header */ DBG_ENTER("php_mysqlnd_change_auth_response_write"); if (packet->auth_data_len) { memcpy(p, packet->auth_data, packet->auth_data_len); p+= packet->auth_data_len; } { size_t sent = conn->net->data->m.send_ex(conn->net, buffer, p - buffer - MYSQLND_HEADER_SIZE, conn->stats, conn->error_info TSRMLS_CC); if (buffer != conn->net->cmd_buffer.buffer) { mnd_efree(buffer); } if (!sent) { CONN_SET_STATE(conn, CONN_QUIT_SENT); } DBG_RETURN(sent); } } /* }}} */ /* {{{ php_mysqlnd_change_auth_response_free_mem */ static void php_mysqlnd_change_auth_response_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { if (!stack_allocation) { MYSQLND_PACKET_CHANGE_AUTH_RESPONSE * p = (MYSQLND_PACKET_CHANGE_AUTH_RESPONSE *) _packet; mnd_pefree(p, p->header.persistent); } } /* }}} */ #define OK_BUFFER_SIZE 2048 /* {{{ php_mysqlnd_ok_read */ static enum_func_status php_mysqlnd_ok_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { zend_uchar local_buf[OK_BUFFER_SIZE]; size_t buf_len = conn->net->cmd_buffer.buffer? conn->net->cmd_buffer.length : OK_BUFFER_SIZE; zend_uchar *buf = conn->net->cmd_buffer.buffer? (zend_uchar *) conn->net->cmd_buffer.buffer : local_buf; zend_uchar *p = buf; zend_uchar *begin = buf; unsigned long i; register MYSQLND_PACKET_OK *packet= (MYSQLND_PACKET_OK *) _packet; DBG_ENTER("php_mysqlnd_ok_read"); PACKET_READ_HEADER_AND_BODY(packet, conn, buf, buf_len, "OK", PROT_OK_PACKET); BAIL_IF_NO_MORE_DATA; /* Should be always 0x0 or ERROR_MARKER for error */ packet->field_count = uint1korr(p); p++; BAIL_IF_NO_MORE_DATA; if (ERROR_MARKER == packet->field_count) { php_mysqlnd_read_error_from_line(p, packet->header.size - 1, packet->error, sizeof(packet->error), &packet->error_no, packet->sqlstate TSRMLS_CC); DBG_INF_FMT("conn->server_status=%u", conn->upsert_status->server_status); DBG_RETURN(PASS); } /* Everything was fine! */ packet->affected_rows = php_mysqlnd_net_field_length_ll(&p); BAIL_IF_NO_MORE_DATA; packet->last_insert_id = php_mysqlnd_net_field_length_ll(&p); BAIL_IF_NO_MORE_DATA; packet->server_status = uint2korr(p); p+= 2; BAIL_IF_NO_MORE_DATA; packet->warning_count = uint2korr(p); p+= 2; BAIL_IF_NO_MORE_DATA; /* There is a message */ if (packet->header.size > (size_t) (p - buf) && (i = php_mysqlnd_net_field_length(&p))) { packet->message_len = MIN(i, buf_len - (p - begin)); packet->message = mnd_pestrndup((char *)p, packet->message_len, FALSE); } else { packet->message = NULL; packet->message_len = 0; } DBG_INF_FMT("OK packet: aff_rows=%lld last_ins_id=%ld server_status=%u warnings=%u", packet->affected_rows, packet->last_insert_id, packet->server_status, packet->warning_count); BAIL_IF_NO_MORE_DATA; DBG_RETURN(PASS); premature_end: DBG_ERR_FMT("OK packet %d bytes shorter than expected", p - begin - packet->header.size); php_error_docref(NULL TSRMLS_CC, E_WARNING, "OK packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", p - begin - packet->header.size); DBG_RETURN(FAIL); } /* }}} */ /* {{{ php_mysqlnd_ok_free_mem */ static void php_mysqlnd_ok_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { MYSQLND_PACKET_OK *p= (MYSQLND_PACKET_OK *) _packet; if (p->message) { mnd_efree(p->message); p->message = NULL; } if (!stack_allocation) { mnd_pefree(p, p->header.persistent); } } /* }}} */ /* {{{ php_mysqlnd_eof_read */ static enum_func_status php_mysqlnd_eof_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { /* EOF packet is since 4.1 five bytes long, but we can get also an error, make it bigger. Error : error_code + '#' + sqlstate + MYSQLND_ERRMSG_SIZE */ MYSQLND_PACKET_EOF *packet= (MYSQLND_PACKET_EOF *) _packet; size_t buf_len = conn->net->cmd_buffer.length; zend_uchar *buf = (zend_uchar *) conn->net->cmd_buffer.buffer; zend_uchar *p = buf; zend_uchar *begin = buf; DBG_ENTER("php_mysqlnd_eof_read"); PACKET_READ_HEADER_AND_BODY(packet, conn, buf, buf_len, "EOF", PROT_EOF_PACKET); BAIL_IF_NO_MORE_DATA; /* Should be always EODATA_MARKER */ packet->field_count = uint1korr(p); p++; BAIL_IF_NO_MORE_DATA; if (ERROR_MARKER == packet->field_count) { php_mysqlnd_read_error_from_line(p, packet->header.size - 1, packet->error, sizeof(packet->error), &packet->error_no, packet->sqlstate TSRMLS_CC); DBG_RETURN(PASS); } /* 4.1 sends 1 byte EOF packet after metadata of PREPARE/EXECUTE but 5 bytes after the result. This is not according to the Docs@Forge!!! */ if (packet->header.size > 1) { packet->warning_count = uint2korr(p); p+= 2; BAIL_IF_NO_MORE_DATA; packet->server_status = uint2korr(p); p+= 2; BAIL_IF_NO_MORE_DATA; } else { packet->warning_count = 0; packet->server_status = 0; } BAIL_IF_NO_MORE_DATA; DBG_INF_FMT("EOF packet: fields=%u status=%u warnings=%u", packet->field_count, packet->server_status, packet->warning_count); DBG_RETURN(PASS); premature_end: DBG_ERR_FMT("EOF packet %d bytes shorter than expected", p - begin - packet->header.size); php_error_docref(NULL TSRMLS_CC, E_WARNING, "EOF packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", p - begin - packet->header.size); DBG_RETURN(FAIL); } /* }}} */ /* {{{ php_mysqlnd_eof_free_mem */ static void php_mysqlnd_eof_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { if (!stack_allocation) { mnd_pefree(_packet, ((MYSQLND_PACKET_EOF *)_packet)->header.persistent); } } /* }}} */ /* {{{ php_mysqlnd_cmd_write */ size_t php_mysqlnd_cmd_write(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { /* Let's have some space, which we can use, if not enough, we will allocate new buffer */ MYSQLND_PACKET_COMMAND * packet= (MYSQLND_PACKET_COMMAND *) _packet; MYSQLND_NET * net = conn->net; unsigned int error_reporting = EG(error_reporting); size_t sent = 0; DBG_ENTER("php_mysqlnd_cmd_write"); /* Reset packet_no, or we will get bad handshake! Every command starts a new TX and packet numbers are reset to 0. */ net->packet_no = 0; net->compressed_envelope_packet_no = 0; /* this is for the response */ if (error_reporting) { EG(error_reporting) = 0; } MYSQLND_INC_CONN_STATISTIC(conn->stats, STAT_PACKETS_SENT_CMD); #ifdef MYSQLND_DO_WIRE_CHECK_BEFORE_COMMAND net->data->m.consume_uneaten_data(net, packet->command TSRMLS_CC); #endif if (!packet->argument || !packet->arg_len) { zend_uchar buffer[MYSQLND_HEADER_SIZE + 1]; int1store(buffer + MYSQLND_HEADER_SIZE, packet->command); sent = net->data->m.send_ex(net, buffer, 1, conn->stats, conn->error_info TSRMLS_CC); } else { size_t tmp_len = packet->arg_len + 1 + MYSQLND_HEADER_SIZE; zend_uchar *tmp, *p; tmp = (tmp_len > net->cmd_buffer.length)? mnd_emalloc(tmp_len):net->cmd_buffer.buffer; if (!tmp) { goto end; } p = tmp + MYSQLND_HEADER_SIZE; /* skip the header */ int1store(p, packet->command); p++; memcpy(p, packet->argument, packet->arg_len); sent = net->data->m.send_ex(net, tmp, tmp_len - MYSQLND_HEADER_SIZE, conn->stats, conn->error_info TSRMLS_CC); if (tmp != net->cmd_buffer.buffer) { MYSQLND_INC_CONN_STATISTIC(conn->stats, STAT_CMD_BUFFER_TOO_SMALL); mnd_efree(tmp); } } end: if (error_reporting) { /* restore error reporting */ EG(error_reporting) = error_reporting; } if (!sent) { CONN_SET_STATE(conn, CONN_QUIT_SENT); } DBG_RETURN(sent); } /* }}} */ /* {{{ php_mysqlnd_cmd_free_mem */ static void php_mysqlnd_cmd_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { if (!stack_allocation) { MYSQLND_PACKET_COMMAND * p = (MYSQLND_PACKET_COMMAND *) _packet; mnd_pefree(p, p->header.persistent); } } /* }}} */ /* {{{ php_mysqlnd_rset_header_read */ static enum_func_status php_mysqlnd_rset_header_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { enum_func_status ret = PASS; size_t buf_len = conn->net->cmd_buffer.length; zend_uchar *buf = (zend_uchar *) conn->net->cmd_buffer.buffer; zend_uchar *p = buf; zend_uchar *begin = buf; size_t len; MYSQLND_PACKET_RSET_HEADER *packet= (MYSQLND_PACKET_RSET_HEADER *) _packet; DBG_ENTER("php_mysqlnd_rset_header_read"); PACKET_READ_HEADER_AND_BODY(packet, conn, buf, buf_len, "resultset header", PROT_RSET_HEADER_PACKET); BAIL_IF_NO_MORE_DATA; /* Don't increment. First byte is ERROR_MARKER on error, but otherwise is starting byte of encoded sequence for length. */ if (ERROR_MARKER == *p) { /* Error */ p++; BAIL_IF_NO_MORE_DATA; php_mysqlnd_read_error_from_line(p, packet->header.size - 1, packet->error_info.error, sizeof(packet->error_info.error), &packet->error_info.error_no, packet->error_info.sqlstate TSRMLS_CC); DBG_INF_FMT("conn->server_status=%u", conn->upsert_status->server_status); DBG_RETURN(PASS); } packet->field_count = php_mysqlnd_net_field_length(&p); BAIL_IF_NO_MORE_DATA; switch (packet->field_count) { case MYSQLND_NULL_LENGTH: DBG_INF("LOAD LOCAL"); /* First byte in the packet is the field count. Thus, the name is size - 1. And we add 1 for a trailing \0. Because we have BAIL_IF_NO_MORE_DATA before the switch, we are guaranteed that packet->header.size is > 0. Which means that len can't underflow, that would lead to 0 byte allocation but 2^32 or 2^64 bytes copied. */ len = packet->header.size - 1; packet->info_or_local_file = mnd_emalloc(len + 1); if (packet->info_or_local_file) { memcpy(packet->info_or_local_file, p, len); packet->info_or_local_file[len] = '\0'; packet->info_or_local_file_len = len; } else { SET_OOM_ERROR(*conn->error_info); ret = FAIL; } break; case 0x00: DBG_INF("UPSERT"); packet->affected_rows = php_mysqlnd_net_field_length_ll(&p); BAIL_IF_NO_MORE_DATA; packet->last_insert_id = php_mysqlnd_net_field_length_ll(&p); BAIL_IF_NO_MORE_DATA; packet->server_status = uint2korr(p); p+=2; BAIL_IF_NO_MORE_DATA; packet->warning_count = uint2korr(p); p+=2; BAIL_IF_NO_MORE_DATA; /* Check for additional textual data */ if (packet->header.size > (size_t) (p - buf) && (len = php_mysqlnd_net_field_length(&p))) { packet->info_or_local_file = mnd_emalloc(len + 1); if (packet->info_or_local_file) { memcpy(packet->info_or_local_file, p, len); packet->info_or_local_file[len] = '\0'; packet->info_or_local_file_len = len; } else { SET_OOM_ERROR(*conn->error_info); ret = FAIL; } } DBG_INF_FMT("affected_rows=%llu last_insert_id=%llu server_status=%u warning_count=%u", packet->affected_rows, packet->last_insert_id, packet->server_status, packet->warning_count); break; default: DBG_INF("SELECT"); /* Result set */ break; } BAIL_IF_NO_MORE_DATA; DBG_RETURN(ret); premature_end: DBG_ERR_FMT("RSET_HEADER packet %d bytes shorter than expected", p - begin - packet->header.size); php_error_docref(NULL TSRMLS_CC, E_WARNING, "RSET_HEADER packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", p - begin - packet->header.size); DBG_RETURN(FAIL); } /* }}} */ /* {{{ php_mysqlnd_rset_header_free_mem */ static void php_mysqlnd_rset_header_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { MYSQLND_PACKET_RSET_HEADER *p= (MYSQLND_PACKET_RSET_HEADER *) _packet; DBG_ENTER("php_mysqlnd_rset_header_free_mem"); if (p->info_or_local_file) { mnd_efree(p->info_or_local_file); p->info_or_local_file = NULL; } if (!stack_allocation) { mnd_pefree(p, p->header.persistent); } DBG_VOID_RETURN; } /* }}} */ static size_t rset_field_offsets[] = { STRUCT_OFFSET(MYSQLND_FIELD, catalog), STRUCT_OFFSET(MYSQLND_FIELD, catalog_length), STRUCT_OFFSET(MYSQLND_FIELD, db), STRUCT_OFFSET(MYSQLND_FIELD, db_length), STRUCT_OFFSET(MYSQLND_FIELD, table), STRUCT_OFFSET(MYSQLND_FIELD, table_length), STRUCT_OFFSET(MYSQLND_FIELD, org_table), STRUCT_OFFSET(MYSQLND_FIELD, org_table_length), STRUCT_OFFSET(MYSQLND_FIELD, name), STRUCT_OFFSET(MYSQLND_FIELD, name_length), STRUCT_OFFSET(MYSQLND_FIELD, org_name), STRUCT_OFFSET(MYSQLND_FIELD, org_name_length) }; /* {{{ php_mysqlnd_rset_field_read */ static enum_func_status php_mysqlnd_rset_field_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { /* Should be enough for the metadata of a single row */ MYSQLND_PACKET_RES_FIELD *packet= (MYSQLND_PACKET_RES_FIELD *) _packet; size_t buf_len = conn->net->cmd_buffer.length, total_len = 0; zend_uchar *buf = (zend_uchar *) conn->net->cmd_buffer.buffer; zend_uchar *p = buf; zend_uchar *begin = buf; char *root_ptr; unsigned long len; MYSQLND_FIELD *meta; unsigned int i, field_count = sizeof(rset_field_offsets)/sizeof(size_t); DBG_ENTER("php_mysqlnd_rset_field_read"); PACKET_READ_HEADER_AND_BODY(packet, conn, buf, buf_len, "field", PROT_RSET_FLD_PACKET); if (packet->skip_parsing) { DBG_RETURN(PASS); } BAIL_IF_NO_MORE_DATA; if (ERROR_MARKER == *p) { /* Error */ p++; BAIL_IF_NO_MORE_DATA; php_mysqlnd_read_error_from_line(p, packet->header.size - 1, packet->error_info.error, sizeof(packet->error_info.error), &packet->error_info.error_no, packet->error_info.sqlstate TSRMLS_CC); DBG_ERR_FMT("Server error : (%u) %s", packet->error_info.error_no, packet->error_info.error); DBG_RETURN(PASS); } else if (EODATA_MARKER == *p && packet->header.size < 8) { /* Premature EOF. That should be COM_FIELD_LIST */ DBG_INF("Premature EOF. That should be COM_FIELD_LIST"); packet->stupid_list_fields_eof = TRUE; DBG_RETURN(PASS); } meta = packet->metadata; for (i = 0; i < field_count; i += 2) { len = php_mysqlnd_net_field_length(&p); BAIL_IF_NO_MORE_DATA; switch ((len)) { case 0: *(const char **)(((char*)meta) + rset_field_offsets[i]) = mysqlnd_empty_string; *(unsigned int *)(((char*)meta) + rset_field_offsets[i+1]) = 0; break; case MYSQLND_NULL_LENGTH: goto faulty_or_fake; default: *(const char **)(((char *)meta) + rset_field_offsets[i]) = (const char *)p; *(unsigned int *)(((char*)meta) + rset_field_offsets[i+1]) = len; p += len; total_len += len + 1; break; } BAIL_IF_NO_MORE_DATA; } /* 1 byte length */ if (12 != *p) { DBG_ERR_FMT("Protocol error. Server sent false length. Expected 12 got %d", (int) *p); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Protocol error. Server sent false length. Expected 12"); } p++; BAIL_IF_NO_MORE_DATA; meta->charsetnr = uint2korr(p); p += 2; BAIL_IF_NO_MORE_DATA; meta->length = uint4korr(p); p += 4; BAIL_IF_NO_MORE_DATA; meta->type = uint1korr(p); p += 1; BAIL_IF_NO_MORE_DATA; meta->flags = uint2korr(p); p += 2; BAIL_IF_NO_MORE_DATA; meta->decimals = uint1korr(p); p += 1; BAIL_IF_NO_MORE_DATA; /* 2 byte filler */ p +=2; BAIL_IF_NO_MORE_DATA; /* Should we set NUM_FLAG (libmysql does it) ? */ if ( (meta->type <= MYSQL_TYPE_INT24 && (meta->type != MYSQL_TYPE_TIMESTAMP || meta->length == 14 || meta->length == 8) ) || meta->type == MYSQL_TYPE_YEAR) { meta->flags |= NUM_FLAG; } /* def could be empty, thus don't allocate on the root. NULL_LENGTH (0xFB) comes from COM_FIELD_LIST when the default value is NULL. Otherwise the string is length encoded. */ if (packet->header.size > (size_t) (p - buf) && (len = php_mysqlnd_net_field_length(&p)) && len != MYSQLND_NULL_LENGTH) { BAIL_IF_NO_MORE_DATA; DBG_INF_FMT("Def found, length %lu, persistent=%u", len, packet->persistent_alloc); meta->def = mnd_pemalloc(len + 1, packet->persistent_alloc); if (!meta->def) { SET_OOM_ERROR(*conn->error_info); DBG_RETURN(FAIL); } memcpy(meta->def, p, len); meta->def[len] = '\0'; meta->def_length = len; p += len; } DBG_INF_FMT("allocing root. persistent=%u", packet->persistent_alloc); root_ptr = meta->root = mnd_pemalloc(total_len, packet->persistent_alloc); if (!root_ptr) { SET_OOM_ERROR(*conn->error_info); DBG_RETURN(FAIL); } meta->root_len = total_len; /* Now do allocs */ if (meta->catalog && meta->catalog != mysqlnd_empty_string) { len = meta->catalog_length; meta->catalog = memcpy(root_ptr, meta->catalog, len); *(root_ptr +=len) = '\0'; root_ptr++; } if (meta->db && meta->db != mysqlnd_empty_string) { len = meta->db_length; meta->db = memcpy(root_ptr, meta->db, len); *(root_ptr +=len) = '\0'; root_ptr++; } if (meta->table && meta->table != mysqlnd_empty_string) { len = meta->table_length; meta->table = memcpy(root_ptr, meta->table, len); *(root_ptr +=len) = '\0'; root_ptr++; } if (meta->org_table && meta->org_table != mysqlnd_empty_string) { len = meta->org_table_length; meta->org_table = memcpy(root_ptr, meta->org_table, len); *(root_ptr +=len) = '\0'; root_ptr++; } if (meta->name && meta->name != mysqlnd_empty_string) { len = meta->name_length; meta->name = memcpy(root_ptr, meta->name, len); *(root_ptr +=len) = '\0'; root_ptr++; } if (meta->org_name && meta->org_name != mysqlnd_empty_string) { len = meta->org_name_length; meta->org_name = memcpy(root_ptr, meta->org_name, len); *(root_ptr +=len) = '\0'; root_ptr++; } DBG_INF_FMT("FIELD=[%s.%s.%s]", meta->db? meta->db:"*NA*", meta->table? meta->table:"*NA*", meta->name? meta->name:"*NA*"); DBG_RETURN(PASS); faulty_or_fake: DBG_ERR_FMT("Protocol error. Server sent NULL_LENGTH. The server is faulty"); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Protocol error. Server sent NULL_LENGTH." " The server is faulty"); DBG_RETURN(FAIL); premature_end: DBG_ERR_FMT("RSET field packet %d bytes shorter than expected", p - begin - packet->header.size); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Result set field packet "MYSQLND_SZ_T_SPEC" bytes " "shorter than expected", p - begin - packet->header.size); DBG_RETURN(FAIL); } /* }}} */ /* {{{ php_mysqlnd_rset_field_free_mem */ static void php_mysqlnd_rset_field_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { MYSQLND_PACKET_RES_FIELD *p= (MYSQLND_PACKET_RES_FIELD *) _packet; /* p->metadata was passed to us as temporal buffer */ if (!stack_allocation) { mnd_pefree(p, p->header.persistent); } } /* }}} */ /* {{{ php_mysqlnd_read_row_ex */ static enum_func_status php_mysqlnd_read_row_ex(MYSQLND_CONN_DATA * conn, MYSQLND_MEMORY_POOL * result_set_memory_pool, MYSQLND_MEMORY_POOL_CHUNK ** buffer, size_t * data_size, zend_bool persistent_alloc, unsigned int prealloc_more_bytes TSRMLS_DC) { enum_func_status ret = PASS; MYSQLND_PACKET_HEADER header; zend_uchar * p = NULL; zend_bool first_iteration = TRUE; DBG_ENTER("php_mysqlnd_read_row_ex"); /* To ease the process the server splits everything in packets up to 2^24 - 1. Even in the case the payload is evenly divisible by this value, the last packet will be empty, namely 0 bytes. Thus, we can read every packet and ask for next one if they have 2^24 - 1 sizes. But just read the header of a zero-length byte, don't read the body, there is no such. */ *data_size = prealloc_more_bytes; while (1) { if (FAIL == mysqlnd_read_header(conn->net, &header, conn->stats, conn->error_info TSRMLS_CC)) { ret = FAIL; break; } *data_size += header.size; if (first_iteration) { first_iteration = FALSE; /* We need a trailing \0 for the last string, in case of text-mode, to be able to implement read-only variables. Thus, we add + 1. */ *buffer = result_set_memory_pool->get_chunk(result_set_memory_pool, *data_size + 1 TSRMLS_CC); if (!*buffer) { ret = FAIL; break; } p = (*buffer)->ptr; } else if (!first_iteration) { /* Empty packet after MYSQLND_MAX_PACKET_SIZE packet. That's ok, break */ if (!header.size) { break; } /* We have to realloc the buffer. We need a trailing \0 for the last string, in case of text-mode, to be able to implement read-only variables. */ if (FAIL == (*buffer)->resize_chunk((*buffer), *data_size + 1 TSRMLS_CC)) { SET_OOM_ERROR(*conn->error_info); ret = FAIL; break; } /* The position could have changed, recalculate */ p = (*buffer)->ptr + (*data_size - header.size); } if (PASS != (ret = conn->net->data->m.receive_ex(conn->net, p, header.size, conn->stats, conn->error_info TSRMLS_CC))) { DBG_ERR("Empty row packet body"); php_error(E_WARNING, "Empty row packet body"); break; } if (header.size < MYSQLND_MAX_PACKET_SIZE) { break; } } if (ret == FAIL && *buffer) { (*buffer)->free_chunk((*buffer) TSRMLS_CC); *buffer = NULL; } *data_size -= prealloc_more_bytes; DBG_RETURN(ret); } /* }}} */ /* {{{ php_mysqlnd_rowp_read_binary_protocol */ enum_func_status php_mysqlnd_rowp_read_binary_protocol(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields, unsigned int field_count, const MYSQLND_FIELD * fields_metadata, zend_bool as_int_or_float, MYSQLND_STATS * stats TSRMLS_DC) { unsigned int i; zend_uchar * p = row_buffer->ptr; zend_uchar * null_ptr, bit; zval **current_field, **end_field, **start_field; DBG_ENTER("php_mysqlnd_rowp_read_binary_protocol"); if (!fields) { DBG_RETURN(FAIL); } end_field = (start_field = fields) + field_count; /* skip the first byte, not EODATA_MARKER -> 0x0, status */ p++; null_ptr= p; p += (field_count + 9)/8; /* skip null bits */ bit = 4; /* first 2 bits are reserved */ for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { DBG_INF("Directly creating zval"); MAKE_STD_ZVAL(*current_field); if (!*current_field) { DBG_RETURN(FAIL); } } for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { enum_mysqlnd_collected_stats statistic; zend_uchar * orig_p = p; DBG_INF_FMT("Into zval=%p decoding column %u [%s.%s.%s] type=%u field->flags&unsigned=%u flags=%u is_bit=%u", *current_field, i, fields_metadata[i].db, fields_metadata[i].table, fields_metadata[i].name, fields_metadata[i].type, fields_metadata[i].flags & UNSIGNED_FLAG, fields_metadata[i].flags, fields_metadata[i].type == MYSQL_TYPE_BIT); if (*null_ptr & bit) { DBG_INF("It's null"); ZVAL_NULL(*current_field); statistic = STAT_BINARY_TYPE_FETCHED_NULL; } else { enum_mysqlnd_field_types type = fields_metadata[i].type; mysqlnd_ps_fetch_functions[type].func(*current_field, &fields_metadata[i], 0, &p TSRMLS_CC); if (MYSQLND_G(collect_statistics)) { switch (fields_metadata[i].type) { case MYSQL_TYPE_DECIMAL: statistic = STAT_BINARY_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_TINY: statistic = STAT_BINARY_TYPE_FETCHED_INT8; break; case MYSQL_TYPE_SHORT: statistic = STAT_BINARY_TYPE_FETCHED_INT16; break; case MYSQL_TYPE_LONG: statistic = STAT_BINARY_TYPE_FETCHED_INT32; break; case MYSQL_TYPE_FLOAT: statistic = STAT_BINARY_TYPE_FETCHED_FLOAT; break; case MYSQL_TYPE_DOUBLE: statistic = STAT_BINARY_TYPE_FETCHED_DOUBLE; break; case MYSQL_TYPE_NULL: statistic = STAT_BINARY_TYPE_FETCHED_NULL; break; case MYSQL_TYPE_TIMESTAMP: statistic = STAT_BINARY_TYPE_FETCHED_TIMESTAMP; break; case MYSQL_TYPE_LONGLONG: statistic = STAT_BINARY_TYPE_FETCHED_INT64; break; case MYSQL_TYPE_INT24: statistic = STAT_BINARY_TYPE_FETCHED_INT24; break; case MYSQL_TYPE_DATE: statistic = STAT_BINARY_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_TIME: statistic = STAT_BINARY_TYPE_FETCHED_TIME; break; case MYSQL_TYPE_DATETIME: statistic = STAT_BINARY_TYPE_FETCHED_DATETIME; break; case MYSQL_TYPE_YEAR: statistic = STAT_BINARY_TYPE_FETCHED_YEAR; break; case MYSQL_TYPE_NEWDATE: statistic = STAT_BINARY_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_VARCHAR: statistic = STAT_BINARY_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_BIT: statistic = STAT_BINARY_TYPE_FETCHED_BIT; break; case MYSQL_TYPE_NEWDECIMAL: statistic = STAT_BINARY_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_ENUM: statistic = STAT_BINARY_TYPE_FETCHED_ENUM; break; case MYSQL_TYPE_SET: statistic = STAT_BINARY_TYPE_FETCHED_SET; break; case MYSQL_TYPE_TINY_BLOB: statistic = STAT_BINARY_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_BINARY_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_LONG_BLOB: statistic = STAT_BINARY_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_BLOB: statistic = STAT_BINARY_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_VAR_STRING: statistic = STAT_BINARY_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_STRING: statistic = STAT_BINARY_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_GEOMETRY: statistic = STAT_BINARY_TYPE_FETCHED_GEOMETRY; break; default: statistic = STAT_BINARY_TYPE_FETCHED_OTHER; break; } } } MYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_PS, (Z_TYPE_PP(current_field) == IS_STRING)? Z_STRLEN_PP(current_field) : (p - orig_p)); if (!((bit<<=1) & 255)) { bit = 1; /* to the following byte */ null_ptr++; } } DBG_RETURN(PASS); } /* }}} */ /* {{{ php_mysqlnd_rowp_read_text_protocol */ enum_func_status php_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields, unsigned int field_count, const MYSQLND_FIELD * fields_metadata, zend_bool as_int_or_float, zend_bool copy_data, MYSQLND_STATS * stats TSRMLS_DC) { unsigned int i; zend_bool last_field_was_string = FALSE; zval **current_field, **end_field, **start_field; zend_uchar * p = row_buffer->ptr; size_t data_size = row_buffer->app; zend_uchar * bit_area = (zend_uchar*) row_buffer->ptr + data_size + 1; /* we allocate from here */ DBG_ENTER("php_mysqlnd_rowp_read_text_protocol_aux"); if (!fields) { DBG_RETURN(FAIL); } end_field = (start_field = fields) + field_count; for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { DBG_INF("Directly creating zval"); MAKE_STD_ZVAL(*current_field); if (!*current_field) { DBG_RETURN(FAIL); } } for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { /* Don't reverse the order. It is significant!*/ zend_uchar *this_field_len_pos = p; /* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */ unsigned long len = php_mysqlnd_net_field_length(&p); if (copy_data == FALSE && current_field > start_field && last_field_was_string) { /* Normal queries: We have to put \0 now to the end of the previous field, if it was a string. IS_NULL doesn't matter. Because we have already read our length, then we can overwrite it in the row buffer. This statement terminates the previous field, not the current one. NULL_LENGTH is encoded in one byte, so we can stick a \0 there. Any string's length is encoded in at least one byte, so we can stick a \0 there. */ *this_field_len_pos = '\0'; } /* NULL or NOT NULL, this is the question! */ if (len == MYSQLND_NULL_LENGTH) { ZVAL_NULL(*current_field); last_field_was_string = FALSE; } else { #if defined(MYSQLND_STRING_TO_INT_CONVERSION) struct st_mysqlnd_perm_bind perm_bind = mysqlnd_ps_fetch_functions[fields_metadata[i].type]; #endif if (MYSQLND_G(collect_statistics)) { enum_mysqlnd_collected_stats statistic; switch (fields_metadata[i].type) { case MYSQL_TYPE_DECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_TINY: statistic = STAT_TEXT_TYPE_FETCHED_INT8; break; case MYSQL_TYPE_SHORT: statistic = STAT_TEXT_TYPE_FETCHED_INT16; break; case MYSQL_TYPE_LONG: statistic = STAT_TEXT_TYPE_FETCHED_INT32; break; case MYSQL_TYPE_FLOAT: statistic = STAT_TEXT_TYPE_FETCHED_FLOAT; break; case MYSQL_TYPE_DOUBLE: statistic = STAT_TEXT_TYPE_FETCHED_DOUBLE; break; case MYSQL_TYPE_NULL: statistic = STAT_TEXT_TYPE_FETCHED_NULL; break; case MYSQL_TYPE_TIMESTAMP: statistic = STAT_TEXT_TYPE_FETCHED_TIMESTAMP; break; case MYSQL_TYPE_LONGLONG: statistic = STAT_TEXT_TYPE_FETCHED_INT64; break; case MYSQL_TYPE_INT24: statistic = STAT_TEXT_TYPE_FETCHED_INT24; break; case MYSQL_TYPE_DATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_TIME: statistic = STAT_TEXT_TYPE_FETCHED_TIME; break; case MYSQL_TYPE_DATETIME: statistic = STAT_TEXT_TYPE_FETCHED_DATETIME; break; case MYSQL_TYPE_YEAR: statistic = STAT_TEXT_TYPE_FETCHED_YEAR; break; case MYSQL_TYPE_NEWDATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_VARCHAR: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_BIT: statistic = STAT_TEXT_TYPE_FETCHED_BIT; break; case MYSQL_TYPE_NEWDECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_ENUM: statistic = STAT_TEXT_TYPE_FETCHED_ENUM; break; case MYSQL_TYPE_SET: statistic = STAT_TEXT_TYPE_FETCHED_SET; break; case MYSQL_TYPE_JSON: statistic = STAT_TEXT_TYPE_FETCHED_JSON; break; case MYSQL_TYPE_TINY_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_LONG_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_VAR_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_GEOMETRY: statistic = STAT_TEXT_TYPE_FETCHED_GEOMETRY; break; default: statistic = STAT_TEXT_TYPE_FETCHED_OTHER; break; } MYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_TEXT, len); } #ifdef MYSQLND_STRING_TO_INT_CONVERSION if (as_int_or_float && perm_bind.php_type == IS_LONG) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; if (perm_bind.pack_len < SIZEOF_LONG) { /* direct conversion */ int64_t v = #ifndef PHP_WIN32 atoll((char *) p); #else _atoi64((char *) p); #endif ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } else { uint64_t v = #ifndef PHP_WIN32 (uint64_t) atoll((char *) p); #else (uint64_t) _atoi64((char *) p); #endif zend_bool uns = fields_metadata[i].flags & UNSIGNED_FLAG? TRUE:FALSE; /* We have to make it ASCIIZ temporarily */ #if SIZEOF_LONG==8 if (uns == TRUE && v > 9223372036854775807L) #elif SIZEOF_LONG==4 if ((uns == TRUE && v > L64(2147483647)) || (uns == FALSE && (( L64(2147483647) < (int64_t) v) || (L64(-2147483648) > (int64_t) v)))) #else #error Need fix for this architecture #endif /* SIZEOF */ { ZVAL_STRINGL(*current_field, (char *)p, len, 0); } else { ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } } *(p + len) = save; } else if (as_int_or_float && perm_bind.php_type == IS_DOUBLE) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; ZVAL_DOUBLE(*current_field, atof((char *) p)); *(p + len) = save; } else #endif /* MYSQLND_STRING_TO_INT_CONVERSION */ if (fields_metadata[i].type == MYSQL_TYPE_BIT) { /* BIT fields are specially handled. As they come as bit mask, we have to convert it to human-readable representation. As the bits take less space in the protocol than the numbers they represent, we don't have enough space in the packet buffer to overwrite inside. Thus, a bit more space is pre-allocated at the end of the buffer, see php_mysqlnd_rowp_read(). And we add the strings at the end. Definitely not nice, _hackish_ :(, but works. */ zend_uchar *start = bit_area; ps_fetch_from_1_to_8_bytes(*current_field, &(fields_metadata[i]), 0, &p, len TSRMLS_CC); /* We have advanced in ps_fetch_from_1_to_8_bytes. We should go back because later in this function there will be an advancement. */ p -= len; if (Z_TYPE_PP(current_field) == IS_LONG) { bit_area += 1 + sprintf((char *)start, "%ld", Z_LVAL_PP(current_field)); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } else if (Z_TYPE_PP(current_field) == IS_STRING){ memcpy(bit_area, Z_STRVAL_PP(current_field), Z_STRLEN_PP(current_field)); bit_area += Z_STRLEN_PP(current_field); *bit_area++ = '\0'; zval_dtor(*current_field); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } } else { ZVAL_STRINGL(*current_field, (char *)p, len, copy_data); } p += len; last_field_was_string = TRUE; } } if (copy_data == FALSE && last_field_was_string) { /* Normal queries: The buffer has one more byte at the end, because we need it */ row_buffer->ptr[data_size] = '\0'; } DBG_RETURN(PASS); } /* }}} */ /* {{{ php_mysqlnd_rowp_read_text_protocol_zval */ enum_func_status php_mysqlnd_rowp_read_text_protocol_zval(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields, unsigned int field_count, const MYSQLND_FIELD * fields_metadata, zend_bool as_int_or_float, MYSQLND_STATS * stats TSRMLS_DC) { enum_func_status ret; DBG_ENTER("php_mysqlnd_rowp_read_text_protocol_zval"); ret = php_mysqlnd_rowp_read_text_protocol_aux(row_buffer, fields, field_count, fields_metadata, as_int_or_float, FALSE, stats TSRMLS_CC); DBG_RETURN(ret); } /* }}} */ /* {{{ php_mysqlnd_rowp_read_text_protocol_c */ enum_func_status php_mysqlnd_rowp_read_text_protocol_c(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields, unsigned int field_count, const MYSQLND_FIELD * fields_metadata, zend_bool as_int_or_float, MYSQLND_STATS * stats TSRMLS_DC) { enum_func_status ret; DBG_ENTER("php_mysqlnd_rowp_read_text_protocol_c"); ret = php_mysqlnd_rowp_read_text_protocol_aux(row_buffer, fields, field_count, fields_metadata, as_int_or_float, TRUE, stats TSRMLS_CC); DBG_RETURN(ret); } /* }}} */ /* {{{ php_mysqlnd_rowp_read */ /* if normal statements => packet->fields is created by this function, if PS => packet->fields is passed from outside */ static enum_func_status php_mysqlnd_rowp_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { zend_uchar *p; enum_func_status ret = PASS; MYSQLND_PACKET_ROW *packet= (MYSQLND_PACKET_ROW *) _packet; size_t post_alloc_for_bit_fields = 0; size_t data_size = 0; DBG_ENTER("php_mysqlnd_rowp_read"); if (!packet->binary_protocol && packet->bit_fields_count) { /* For every field we need terminating \0 */ post_alloc_for_bit_fields = packet->bit_fields_total_len + packet->bit_fields_count; } ret = php_mysqlnd_read_row_ex(conn, packet->result_set_memory_pool, &packet->row_buffer, &data_size, packet->persistent_alloc, post_alloc_for_bit_fields TSRMLS_CC); if (FAIL == ret) { goto end; } MYSQLND_INC_CONN_STATISTIC_W_VALUE2(conn->stats, packet_type_to_statistic_byte_count[PROT_ROW_PACKET], MYSQLND_HEADER_SIZE + packet->header.size, packet_type_to_statistic_packet_count[PROT_ROW_PACKET], 1); /* packet->row_buffer->ptr is of size 'data_size + 1' */ packet->header.size = data_size; packet->row_buffer->app = data_size; if (ERROR_MARKER == (*(p = packet->row_buffer->ptr))) { /* Error message as part of the result set, not good but we should not hang. See: Bug #27876 : SF with cyrillic variable name fails during execution */ ret = FAIL; php_mysqlnd_read_error_from_line(p + 1, data_size - 1, packet->error_info.error, sizeof(packet->error_info.error), &packet->error_info.error_no, packet->error_info.sqlstate TSRMLS_CC); } else if (EODATA_MARKER == *p && data_size < 8) { /* EOF */ packet->eof = TRUE; p++; if (data_size > 1) { packet->warning_count = uint2korr(p); p += 2; packet->server_status = uint2korr(p); /* Seems we have 3 bytes reserved for future use */ DBG_INF_FMT("server_status=%u warning_count=%u", packet->server_status, packet->warning_count); } } else { MYSQLND_INC_CONN_STATISTIC(conn->stats, packet->binary_protocol? STAT_ROWS_FETCHED_FROM_SERVER_PS: STAT_ROWS_FETCHED_FROM_SERVER_NORMAL); packet->eof = FALSE; /* packet->field_count is set by the user of the packet */ if (!packet->skip_extraction) { if (!packet->fields) { DBG_INF("Allocating packet->fields"); /* old-API will probably set packet->fields to NULL every time, though for unbuffered sets it makes not much sense as the zvals in this buffer matter, not the buffer. Constantly allocating and deallocating brings nothing. For PS - if stmt_store() is performed, thus we don't have a cursor, it will behave just like old-API buffered. Cursors will behave like a bit different, but mostly like old-API unbuffered and thus will populate this array with value. */ packet->fields = (zval **) mnd_pecalloc(packet->field_count, sizeof(zval *), packet->persistent_alloc); } } else { MYSQLND_INC_CONN_STATISTIC(conn->stats, packet->binary_protocol? STAT_ROWS_SKIPPED_PS: STAT_ROWS_SKIPPED_NORMAL); } } end: DBG_RETURN(ret); } /* }}} */ /* {{{ php_mysqlnd_rowp_free_mem */ static void php_mysqlnd_rowp_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { MYSQLND_PACKET_ROW *p; DBG_ENTER("php_mysqlnd_rowp_free_mem"); p = (MYSQLND_PACKET_ROW *) _packet; if (p->row_buffer) { p->row_buffer->free_chunk(p->row_buffer TSRMLS_CC); p->row_buffer = NULL; } DBG_INF_FMT("stack_allocation=%u persistent=%u", (int)stack_allocation, (int)p->header.persistent); /* Don't free packet->fields : - normal queries -> store_result() | fetch_row_unbuffered() will transfer the ownership and NULL it. - PS will pass in it the bound variables, we have to use them! and of course not free the array. As it is passed to us, we should not clean it ourselves. */ if (!stack_allocation) { mnd_pefree(p, p->header.persistent); } DBG_VOID_RETURN; } /* }}} */ /* {{{ php_mysqlnd_stats_read */ static enum_func_status php_mysqlnd_stats_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { MYSQLND_PACKET_STATS *packet= (MYSQLND_PACKET_STATS *) _packet; size_t buf_len = conn->net->cmd_buffer.length; zend_uchar *buf = (zend_uchar *) conn->net->cmd_buffer.buffer; DBG_ENTER("php_mysqlnd_stats_read"); PACKET_READ_HEADER_AND_BODY(packet, conn, buf, buf_len, "statistics", PROT_STATS_PACKET); packet->message = mnd_emalloc(packet->header.size + 1); memcpy(packet->message, buf, packet->header.size); packet->message[packet->header.size] = '\0'; packet->message_len = packet->header.size; DBG_RETURN(PASS); } /* }}} */ /* {{{ php_mysqlnd_stats_free_mem */ static void php_mysqlnd_stats_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { MYSQLND_PACKET_STATS *p= (MYSQLND_PACKET_STATS *) _packet; if (p->message) { mnd_efree(p->message); p->message = NULL; } if (!stack_allocation) { mnd_pefree(p, p->header.persistent); } } /* }}} */ /* 1 + 4 (id) + 2 (field_c) + 2 (param_c) + 1 (filler) + 2 (warnings ) */ #define PREPARE_RESPONSE_SIZE_41 9 #define PREPARE_RESPONSE_SIZE_50 12 /* {{{ php_mysqlnd_prepare_read */ static enum_func_status php_mysqlnd_prepare_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { /* In case of an error, we should have place to put it */ size_t buf_len = conn->net->cmd_buffer.length; zend_uchar *buf = (zend_uchar *) conn->net->cmd_buffer.buffer; zend_uchar *p = buf; zend_uchar *begin = buf; unsigned int data_size; MYSQLND_PACKET_PREPARE_RESPONSE *packet= (MYSQLND_PACKET_PREPARE_RESPONSE *) _packet; DBG_ENTER("php_mysqlnd_prepare_read"); PACKET_READ_HEADER_AND_BODY(packet, conn, buf, buf_len, "prepare", PROT_PREPARE_RESP_PACKET); BAIL_IF_NO_MORE_DATA; data_size = packet->header.size; packet->error_code = uint1korr(p); p++; BAIL_IF_NO_MORE_DATA; if (ERROR_MARKER == packet->error_code) { php_mysqlnd_read_error_from_line(p, data_size - 1, packet->error_info.error, sizeof(packet->error_info.error), &packet->error_info.error_no, packet->error_info.sqlstate TSRMLS_CC); DBG_RETURN(PASS); } if (data_size != PREPARE_RESPONSE_SIZE_41 && data_size != PREPARE_RESPONSE_SIZE_50 && !(data_size > PREPARE_RESPONSE_SIZE_50)) { DBG_ERR_FMT("Wrong COM_STMT_PREPARE response size. Received %u", data_size); php_error(E_WARNING, "Wrong COM_STMT_PREPARE response size. Received %u", data_size); DBG_RETURN(FAIL); } packet->stmt_id = uint4korr(p); p += 4; BAIL_IF_NO_MORE_DATA; /* Number of columns in result set */ packet->field_count = uint2korr(p); p += 2; BAIL_IF_NO_MORE_DATA; packet->param_count = uint2korr(p); p += 2; BAIL_IF_NO_MORE_DATA; if (data_size > 9) { /* 0x0 filler sent by the server for 5.0+ clients */ p++; BAIL_IF_NO_MORE_DATA; packet->warning_count = uint2korr(p); } DBG_INF_FMT("Prepare packet read: stmt_id=%u fields=%u params=%u", packet->stmt_id, packet->field_count, packet->param_count); BAIL_IF_NO_MORE_DATA; DBG_RETURN(PASS); premature_end: DBG_ERR_FMT("PREPARE packet %d bytes shorter than expected", p - begin - packet->header.size); php_error_docref(NULL TSRMLS_CC, E_WARNING, "PREPARE packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", p - begin - packet->header.size); DBG_RETURN(FAIL); } /* }}} */ /* {{{ php_mysqlnd_prepare_free_mem */ static void php_mysqlnd_prepare_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { MYSQLND_PACKET_PREPARE_RESPONSE *p= (MYSQLND_PACKET_PREPARE_RESPONSE *) _packet; if (!stack_allocation) { mnd_pefree(p, p->header.persistent); } } /* }}} */ /* {{{ php_mysqlnd_chg_user_read */ static enum_func_status php_mysqlnd_chg_user_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { /* There could be an error message */ size_t buf_len = conn->net->cmd_buffer.length; zend_uchar *buf = (zend_uchar *) conn->net->cmd_buffer.buffer; zend_uchar *p = buf; zend_uchar *begin = buf; MYSQLND_PACKET_CHG_USER_RESPONSE *packet= (MYSQLND_PACKET_CHG_USER_RESPONSE *) _packet; DBG_ENTER("php_mysqlnd_chg_user_read"); PACKET_READ_HEADER_AND_BODY(packet, conn, buf, buf_len, "change user response", PROT_CHG_USER_RESP_PACKET); BAIL_IF_NO_MORE_DATA; /* Don't increment. First byte is ERROR_MARKER on error, but otherwise is starting byte of encoded sequence for length. */ /* Should be always 0x0 or ERROR_MARKER for error */ packet->response_code = uint1korr(p); p++; if (packet->header.size == 1 && buf[0] == EODATA_MARKER && packet->server_capabilities & CLIENT_SECURE_CONNECTION) { /* We don't handle 3.23 authentication */ packet->server_asked_323_auth = TRUE; DBG_RETURN(FAIL); } if (ERROR_MARKER == packet->response_code) { php_mysqlnd_read_error_from_line(p, packet->header.size - 1, packet->error_info.error, sizeof(packet->error_info.error), &packet->error_info.error_no, packet->error_info.sqlstate TSRMLS_CC); } BAIL_IF_NO_MORE_DATA; if (packet->response_code == 0xFE && packet->header.size > (size_t) (p - buf)) { packet->new_auth_protocol = mnd_pestrdup((char *)p, FALSE); packet->new_auth_protocol_len = strlen(packet->new_auth_protocol); p+= packet->new_auth_protocol_len + 1; /* +1 for the \0 */ packet->new_auth_protocol_data_len = packet->header.size - (size_t) (p - buf); if (packet->new_auth_protocol_data_len) { packet->new_auth_protocol_data = mnd_emalloc(packet->new_auth_protocol_data_len); memcpy(packet->new_auth_protocol_data, p, packet->new_auth_protocol_data_len); } DBG_INF_FMT("The server requested switching auth plugin to : %s", packet->new_auth_protocol); DBG_INF_FMT("Server salt : [%*s]", packet->new_auth_protocol_data_len, packet->new_auth_protocol_data); } DBG_RETURN(PASS); premature_end: DBG_ERR_FMT("CHANGE_USER packet %d bytes shorter than expected", p - begin - packet->header.size); php_error_docref(NULL TSRMLS_CC, E_WARNING, "CHANGE_USER packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", p - begin - packet->header.size); DBG_RETURN(FAIL); } /* }}} */ /* {{{ php_mysqlnd_chg_user_free_mem */ static void php_mysqlnd_chg_user_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { MYSQLND_PACKET_CHG_USER_RESPONSE * p = (MYSQLND_PACKET_CHG_USER_RESPONSE *) _packet; if (p->new_auth_protocol) { mnd_efree(p->new_auth_protocol); p->new_auth_protocol = NULL; } p->new_auth_protocol_len = 0; if (p->new_auth_protocol_data) { mnd_efree(p->new_auth_protocol_data); p->new_auth_protocol_data = NULL; } p->new_auth_protocol_data_len = 0; if (!stack_allocation) { mnd_pefree(p, p->header.persistent); } } /* }}} */ /* {{{ php_mysqlnd_sha256_pk_request_write */ static size_t php_mysqlnd_sha256_pk_request_write(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { zend_uchar buffer[MYSQLND_HEADER_SIZE + 1]; size_t sent; DBG_ENTER("php_mysqlnd_sha256_pk_request_write"); int1store(buffer + MYSQLND_HEADER_SIZE, '\1'); sent = conn->net->data->m.send_ex(conn->net, buffer, 1, conn->stats, conn->error_info TSRMLS_CC); DBG_RETURN(sent); } /* }}} */ /* {{{ php_mysqlnd_sha256_pk_request_free_mem */ static void php_mysqlnd_sha256_pk_request_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { if (!stack_allocation) { MYSQLND_PACKET_SHA256_PK_REQUEST * p = (MYSQLND_PACKET_SHA256_PK_REQUEST *) _packet; mnd_pefree(p, p->header.persistent); } } /* }}} */ #define SHA256_PK_REQUEST_RESP_BUFFER_SIZE 2048 /* {{{ php_mysqlnd_sha256_pk_request_response_read */ static enum_func_status php_mysqlnd_sha256_pk_request_response_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC) { zend_uchar buf[SHA256_PK_REQUEST_RESP_BUFFER_SIZE]; zend_uchar *p = buf; zend_uchar *begin = buf; MYSQLND_PACKET_SHA256_PK_REQUEST_RESPONSE * packet= (MYSQLND_PACKET_SHA256_PK_REQUEST_RESPONSE *) _packet; DBG_ENTER("php_mysqlnd_sha256_pk_request_response_read"); /* leave space for terminating safety \0 */ PACKET_READ_HEADER_AND_BODY(packet, conn, buf, sizeof(buf), "SHA256_PK_REQUEST_RESPONSE", PROT_SHA256_PK_REQUEST_RESPONSE_PACKET); BAIL_IF_NO_MORE_DATA; p++; BAIL_IF_NO_MORE_DATA; packet->public_key_len = packet->header.size - (p - buf); packet->public_key = mnd_emalloc(packet->public_key_len + 1); memcpy(packet->public_key, p, packet->public_key_len); packet->public_key[packet->public_key_len] = '\0'; DBG_RETURN(PASS); premature_end: DBG_ERR_FMT("OK packet %d bytes shorter than expected", p - begin - packet->header.size); php_error_docref(NULL TSRMLS_CC, E_WARNING, "SHA256_PK_REQUEST_RESPONSE packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", p - begin - packet->header.size); DBG_RETURN(FAIL); } /* }}} */ /* {{{ php_mysqlnd_sha256_pk_request_response_free_mem */ static void php_mysqlnd_sha256_pk_request_response_free_mem(void * _packet, zend_bool stack_allocation TSRMLS_DC) { MYSQLND_PACKET_SHA256_PK_REQUEST_RESPONSE * p = (MYSQLND_PACKET_SHA256_PK_REQUEST_RESPONSE *) _packet; if (p->public_key) { mnd_efree(p->public_key); p->public_key = NULL; } p->public_key_len = 0; if (!stack_allocation) { mnd_pefree(p, p->header.persistent); } } /* }}} */ /* {{{ packet_methods */ static mysqlnd_packet_methods packet_methods[PROT_LAST] = { { sizeof(MYSQLND_PACKET_GREET), php_mysqlnd_greet_read, NULL, /* write */ php_mysqlnd_greet_free_mem, }, /* PROT_GREET_PACKET */ { sizeof(MYSQLND_PACKET_AUTH), NULL, /* read */ php_mysqlnd_auth_write, php_mysqlnd_auth_free_mem, }, /* PROT_AUTH_PACKET */ { sizeof(MYSQLND_PACKET_AUTH_RESPONSE), php_mysqlnd_auth_response_read, /* read */ NULL, /* write */ php_mysqlnd_auth_response_free_mem, }, /* PROT_AUTH_RESP_PACKET */ { sizeof(MYSQLND_PACKET_CHANGE_AUTH_RESPONSE), NULL, /* read */ php_mysqlnd_change_auth_response_write, /* write */ php_mysqlnd_change_auth_response_free_mem, }, /* PROT_CHANGE_AUTH_RESP_PACKET */ { sizeof(MYSQLND_PACKET_OK), php_mysqlnd_ok_read, /* read */ NULL, /* write */ php_mysqlnd_ok_free_mem, }, /* PROT_OK_PACKET */ { sizeof(MYSQLND_PACKET_EOF), php_mysqlnd_eof_read, /* read */ NULL, /* write */ php_mysqlnd_eof_free_mem, }, /* PROT_EOF_PACKET */ { sizeof(MYSQLND_PACKET_COMMAND), NULL, /* read */ php_mysqlnd_cmd_write, /* write */ php_mysqlnd_cmd_free_mem, }, /* PROT_CMD_PACKET */ { sizeof(MYSQLND_PACKET_RSET_HEADER), php_mysqlnd_rset_header_read, /* read */ NULL, /* write */ php_mysqlnd_rset_header_free_mem, }, /* PROT_RSET_HEADER_PACKET */ { sizeof(MYSQLND_PACKET_RES_FIELD), php_mysqlnd_rset_field_read, /* read */ NULL, /* write */ php_mysqlnd_rset_field_free_mem, }, /* PROT_RSET_FLD_PACKET */ { sizeof(MYSQLND_PACKET_ROW), php_mysqlnd_rowp_read, /* read */ NULL, /* write */ php_mysqlnd_rowp_free_mem, }, /* PROT_ROW_PACKET */ { sizeof(MYSQLND_PACKET_STATS), php_mysqlnd_stats_read, /* read */ NULL, /* write */ php_mysqlnd_stats_free_mem, }, /* PROT_STATS_PACKET */ { sizeof(MYSQLND_PACKET_PREPARE_RESPONSE), php_mysqlnd_prepare_read, /* read */ NULL, /* write */ php_mysqlnd_prepare_free_mem, }, /* PROT_PREPARE_RESP_PACKET */ { sizeof(MYSQLND_PACKET_CHG_USER_RESPONSE), php_mysqlnd_chg_user_read, /* read */ NULL, /* write */ php_mysqlnd_chg_user_free_mem, }, /* PROT_CHG_USER_RESP_PACKET */ { sizeof(MYSQLND_PACKET_SHA256_PK_REQUEST), NULL, /* read */ php_mysqlnd_sha256_pk_request_write, php_mysqlnd_sha256_pk_request_free_mem, }, /* PROT_SHA256_PK_REQUEST_PACKET */ { sizeof(MYSQLND_PACKET_SHA256_PK_REQUEST_RESPONSE), php_mysqlnd_sha256_pk_request_response_read, NULL, /* write */ php_mysqlnd_sha256_pk_request_response_free_mem, } /* PROT_SHA256_PK_REQUEST_RESPONSE_PACKET */ }; /* }}} */ /* {{{ mysqlnd_protocol::get_greet_packet */ static struct st_mysqlnd_packet_greet * MYSQLND_METHOD(mysqlnd_protocol, get_greet_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_greet * packet = mnd_pecalloc(1, packet_methods[PROT_GREET_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_greet_packet"); if (packet) { packet->header.m = &packet_methods[PROT_GREET_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_auth_packet */ static struct st_mysqlnd_packet_auth * MYSQLND_METHOD(mysqlnd_protocol, get_auth_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_auth * packet = mnd_pecalloc(1, packet_methods[PROT_AUTH_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_auth_packet"); if (packet) { packet->header.m = &packet_methods[PROT_AUTH_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_auth_response_packet */ static struct st_mysqlnd_packet_auth_response * MYSQLND_METHOD(mysqlnd_protocol, get_auth_response_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_auth_response * packet = mnd_pecalloc(1, packet_methods[PROT_AUTH_RESP_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_auth_response_packet"); if (packet) { packet->header.m = &packet_methods[PROT_AUTH_RESP_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_change_auth_response_packet */ static struct st_mysqlnd_packet_change_auth_response * MYSQLND_METHOD(mysqlnd_protocol, get_change_auth_response_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_change_auth_response * packet = mnd_pecalloc(1, packet_methods[PROT_CHANGE_AUTH_RESP_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_change_auth_response_packet"); if (packet) { packet->header.m = &packet_methods[PROT_CHANGE_AUTH_RESP_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_ok_packet */ static struct st_mysqlnd_packet_ok * MYSQLND_METHOD(mysqlnd_protocol, get_ok_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_ok * packet = mnd_pecalloc(1, packet_methods[PROT_OK_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_ok_packet"); if (packet) { packet->header.m = &packet_methods[PROT_OK_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_eof_packet */ static struct st_mysqlnd_packet_eof * MYSQLND_METHOD(mysqlnd_protocol, get_eof_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_eof * packet = mnd_pecalloc(1, packet_methods[PROT_EOF_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_eof_packet"); if (packet) { packet->header.m = &packet_methods[PROT_EOF_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_command_packet */ static struct st_mysqlnd_packet_command * MYSQLND_METHOD(mysqlnd_protocol, get_command_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_command * packet = mnd_pecalloc(1, packet_methods[PROT_CMD_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_command_packet"); if (packet) { packet->header.m = &packet_methods[PROT_CMD_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_rset_packet */ static struct st_mysqlnd_packet_rset_header * MYSQLND_METHOD(mysqlnd_protocol, get_rset_header_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_rset_header * packet = mnd_pecalloc(1, packet_methods[PROT_RSET_HEADER_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_rset_header_packet"); if (packet) { packet->header.m = &packet_methods[PROT_RSET_HEADER_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_result_field_packet */ static struct st_mysqlnd_packet_res_field * MYSQLND_METHOD(mysqlnd_protocol, get_result_field_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_res_field * packet = mnd_pecalloc(1, packet_methods[PROT_RSET_FLD_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_result_field_packet"); if (packet) { packet->header.m = &packet_methods[PROT_RSET_FLD_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_row_packet */ static struct st_mysqlnd_packet_row * MYSQLND_METHOD(mysqlnd_protocol, get_row_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_row * packet = mnd_pecalloc(1, packet_methods[PROT_ROW_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_row_packet"); if (packet) { packet->header.m = &packet_methods[PROT_ROW_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_stats_packet */ static struct st_mysqlnd_packet_stats * MYSQLND_METHOD(mysqlnd_protocol, get_stats_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_stats * packet = mnd_pecalloc(1, packet_methods[PROT_STATS_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_stats_packet"); if (packet) { packet->header.m = &packet_methods[PROT_STATS_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_prepare_response_packet */ static struct st_mysqlnd_packet_prepare_response * MYSQLND_METHOD(mysqlnd_protocol, get_prepare_response_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_prepare_response * packet = mnd_pecalloc(1, packet_methods[PROT_PREPARE_RESP_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_prepare_response_packet"); if (packet) { packet->header.m = &packet_methods[PROT_PREPARE_RESP_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_change_user_response_packet */ static struct st_mysqlnd_packet_chg_user_resp* MYSQLND_METHOD(mysqlnd_protocol, get_change_user_response_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_chg_user_resp * packet = mnd_pecalloc(1, packet_methods[PROT_CHG_USER_RESP_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_change_user_response_packet"); if (packet) { packet->header.m = &packet_methods[PROT_CHG_USER_RESP_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_sha256_pk_request_packet */ static struct st_mysqlnd_packet_sha256_pk_request * MYSQLND_METHOD(mysqlnd_protocol, get_sha256_pk_request_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_sha256_pk_request * packet = mnd_pecalloc(1, packet_methods[PROT_SHA256_PK_REQUEST_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_sha256_pk_request_packet"); if (packet) { packet->header.m = &packet_methods[PROT_SHA256_PK_REQUEST_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ /* {{{ mysqlnd_protocol::get_sha256_pk_request_response_packet */ static struct st_mysqlnd_packet_sha256_pk_request_response * MYSQLND_METHOD(mysqlnd_protocol, get_sha256_pk_request_response_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC) { struct st_mysqlnd_packet_sha256_pk_request_response * packet = mnd_pecalloc(1, packet_methods[PROT_SHA256_PK_REQUEST_RESPONSE_PACKET].struct_size, persistent); DBG_ENTER("mysqlnd_protocol::get_sha256_pk_request_response_packet"); if (packet) { packet->header.m = &packet_methods[PROT_SHA256_PK_REQUEST_RESPONSE_PACKET]; packet->header.persistent = persistent; } DBG_RETURN(packet); } /* }}} */ MYSQLND_CLASS_METHODS_START(mysqlnd_protocol) MYSQLND_METHOD(mysqlnd_protocol, get_greet_packet), MYSQLND_METHOD(mysqlnd_protocol, get_auth_packet), MYSQLND_METHOD(mysqlnd_protocol, get_auth_response_packet), MYSQLND_METHOD(mysqlnd_protocol, get_change_auth_response_packet), MYSQLND_METHOD(mysqlnd_protocol, get_ok_packet), MYSQLND_METHOD(mysqlnd_protocol, get_command_packet), MYSQLND_METHOD(mysqlnd_protocol, get_eof_packet), MYSQLND_METHOD(mysqlnd_protocol, get_rset_header_packet), MYSQLND_METHOD(mysqlnd_protocol, get_result_field_packet), MYSQLND_METHOD(mysqlnd_protocol, get_row_packet), MYSQLND_METHOD(mysqlnd_protocol, get_stats_packet), MYSQLND_METHOD(mysqlnd_protocol, get_prepare_response_packet), MYSQLND_METHOD(mysqlnd_protocol, get_change_user_response_packet), MYSQLND_METHOD(mysqlnd_protocol, get_sha256_pk_request_packet), MYSQLND_METHOD(mysqlnd_protocol, get_sha256_pk_request_response_packet) MYSQLND_CLASS_METHODS_END; /* {{{ mysqlnd_protocol_init */ PHPAPI MYSQLND_PROTOCOL * mysqlnd_protocol_init(zend_bool persistent TSRMLS_DC) { MYSQLND_PROTOCOL * ret; DBG_ENTER("mysqlnd_protocol_init"); ret = MYSQLND_CLASS_METHOD_TABLE_NAME(mysqlnd_object_factory).get_protocol_decoder(persistent TSRMLS_CC); DBG_RETURN(ret); } /* }}} */ /* {{{ mysqlnd_protocol_free */ PHPAPI void mysqlnd_protocol_free(MYSQLND_PROTOCOL * const protocol TSRMLS_DC) { DBG_ENTER("mysqlnd_protocol_free"); if (protocol) { zend_bool pers = protocol->persistent; mnd_pefree(protocol, pers); } DBG_VOID_RETURN; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5281_0
crossvul-cpp_data_bad_344_8
/* * cryptoflex-tool.c: Tool for doing various Cryptoflex related stuff * * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include "libopensc/sc-ossl-compat.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/err.h> #include "libopensc/pkcs15.h" #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "util.h" static const char *app_name = "cryptoflex-tool"; static char * opt_reader = NULL; static int opt_wait = 0; static int opt_key_num = 1, opt_pin_num = -1; static int verbose = 0; static int opt_exponent = 3; static int opt_mod_length = 1024; static int opt_key_count = 1; static int opt_pin_attempts = 10; static int opt_puk_attempts = 10; static const char *opt_appdf = NULL, *opt_prkeyf = NULL, *opt_pubkeyf = NULL; static u8 *pincode = NULL; static const struct option options[] = { { "list-keys", 0, NULL, 'l' }, { "create-key-files", 1, NULL, 'c' }, { "create-pin-file", 1, NULL, 'P' }, { "generate-key", 0, NULL, 'g' }, { "read-key", 0, NULL, 'R' }, { "verify-pin", 0, NULL, 'V' }, { "key-num", 1, NULL, 'k' }, { "app-df", 1, NULL, 'a' }, { "prkey-file", 1, NULL, 'p' }, { "pubkey-file", 1, NULL, 'u' }, { "exponent", 1, NULL, 'e' }, { "modulus-length", 1, NULL, 'm' }, { "reader", 1, NULL, 'r' }, { "wait", 0, NULL, 'w' }, { "verbose", 0, NULL, 'v' }, { NULL, 0, NULL, 0 } }; static const char *option_help[] = { "Lists all keys in a public key file", "Creates new RSA key files for <arg> keys", "Creates a new CHV<arg> file", "Generates a new RSA key pair", "Reads a public key from the card", "Verifies CHV1 before issuing commands", "Selects which key number to operate on [1]", "Selects the DF to operate in", "Private key file", "Public key file", "The RSA exponent to use in key generation [3]", "Modulus length to use in key generation [1024]", "Uses reader <arg>", "Wait for card insertion", "Verbose operation. Use several times to enable debug output.", }; static sc_context_t *ctx = NULL; static sc_card_t *card = NULL; static char *getpin(const char *prompt) { char *buf, pass[20]; int i; printf("%s", prompt); fflush(stdout); if (fgets(pass, 20, stdin) == NULL) return NULL; for (i = 0; i < 20; i++) if (pass[i] == '\n') pass[i] = 0; if (strlen(pass) == 0) return NULL; buf = malloc(8); if (buf == NULL) return NULL; if (strlen(pass) > 8) { fprintf(stderr, "PIN code too long.\n"); free(buf); return NULL; } memset(buf, 0, 8); strlcpy(buf, pass, 8); return buf; } static int verify_pin(int pin) { char prompt[50]; int r, tries_left = -1; if (pincode == NULL) { sprintf(prompt, "Please enter CHV%d: ", pin); pincode = (u8 *) getpin(prompt); if (pincode == NULL || strlen((char *) pincode) == 0) return -1; } if (pin != 1 && pin != 2) return -3; r = sc_verify(card, SC_AC_CHV, pin, pincode, 8, &tries_left); if (r) { memset(pincode, 0, 8); free(pincode); pincode = NULL; fprintf(stderr, "PIN code verification failed: %s\n", sc_strerror(r)); return -1; } return 0; } static int select_app_df(void) { sc_path_t path; sc_file_t *file; char str[80]; int r; strcpy(str, "3F00"); if (opt_appdf != NULL) strlcat(str, opt_appdf, sizeof str); sc_format_path(str, &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select application DF: %s\n", sc_strerror(r)); return -1; } if (file->type != SC_FILE_TYPE_DF) { fprintf(stderr, "Selected application DF is not a DF.\n"); return -1; } sc_file_free(file); if (opt_pin_num >= 0) return verify_pin(opt_pin_num); else return 0; } static void invert_buf(u8 *dest, const u8 *src, size_t c) { size_t i; for (i = 0; i < c; i++) dest[i] = src[c-1-i]; } static BIGNUM * cf2bn(const u8 *buf, size_t bufsize, BIGNUM *num) { u8 tmp[512]; invert_buf(tmp, buf, bufsize); return BN_bin2bn(tmp, bufsize, num); } static int bn2cf(const BIGNUM *num, u8 *buf) { u8 tmp[512]; int r; r = BN_bn2bin(num, tmp); if (r <= 0) return r; invert_buf(buf, tmp, r); return r; } static int parse_public_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *n, *e; int base; base = (keysize - 7) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid public key.\n"); return -1; } p += 3; n = BN_new(); if (n == NULL) return -1; cf2bn(p, 2 * base, n); p += 2 * base; p += base; p += 2 * base; e = BN_new(); if (e == NULL) return -1; cf2bn(p, 4, e); if (RSA_set0_key(rsa, n, e, NULL) != 1) return -1; return 0; } static int gen_d(RSA *rsa) { BN_CTX *bnctx; BIGNUM *r0, *r1, *r2; const BIGNUM *rsa_p, *rsa_q, *rsa_n, *rsa_e, *rsa_d; BIGNUM *rsa_n_new, *rsa_e_new, *rsa_d_new; bnctx = BN_CTX_new(); if (bnctx == NULL) return -1; BN_CTX_start(bnctx); r0 = BN_CTX_get(bnctx); r1 = BN_CTX_get(bnctx); r2 = BN_CTX_get(bnctx); RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); RSA_get0_factors(rsa, &rsa_p, &rsa_q); BN_sub(r1, rsa_p, BN_value_one()); BN_sub(r2, rsa_q, BN_value_one()); BN_mul(r0, r1, r2, bnctx); if ((rsa_d_new = BN_mod_inverse(NULL, rsa_e, r0, bnctx)) == NULL) { fprintf(stderr, "BN_mod_inverse() failed.\n"); return -1; } /* RSA_set0_key will free previous value, and replace with new value * Thus the need to copy the contents of rsa_n and rsa_e */ rsa_n_new = BN_dup(rsa_n); rsa_e_new = BN_dup(rsa_e); if (RSA_set0_key(rsa, rsa_n_new, rsa_e_new, rsa_d_new) != 1) return -1; BN_CTX_end(bnctx); BN_CTX_free(bnctx); return 0; } static int parse_private_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *bn_p, *q, *dmp1, *dmq1, *iqmp; int base; base = (keysize - 3) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid private key.\n"); return -1; } p += 3; bn_p = BN_new(); if (bn_p == NULL) return -1; cf2bn(p, base, bn_p); p += base; q = BN_new(); if (q == NULL) return -1; cf2bn(p, base, q); p += base; iqmp = BN_new(); if (iqmp == NULL) return -1; cf2bn(p, base, iqmp); p += base; dmp1 = BN_new(); if (dmp1 == NULL) return -1; cf2bn(p, base, dmp1); p += base; dmq1 = BN_new(); if (dmq1 == NULL) return -1; cf2bn(p, base, dmq1); p += base; if (RSA_set0_factors(rsa, bn_p, q) != 1) return -1; if (RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp) != 1) return -1; if (gen_d(rsa)) return -1; return 0; } static int read_public_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_public_key(p, keysize, rsa); } static int read_private_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; const sc_acl_entry_t *e; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } e = sc_file_get_acl_entry(file, SC_AC_OP_READ); if (e == NULL || e->method == SC_AC_NEVER) return 10; bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_private_key(p, keysize, rsa); } static int read_key(void) { RSA *rsa = RSA_new(); u8 buf[1024], *p = buf; u8 b64buf[2048]; int r; if (rsa == NULL) return -1; r = read_public_key(rsa); if (r) return r; r = i2d_RSA_PUBKEY(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding public key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----\n", b64buf); r = read_private_key(rsa); if (r == 10) return 0; else if (r) return r; p = buf; r = i2d_RSAPrivateKey(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding private key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n", b64buf); return 0; } static int list_keys(void) { int r, idx = 0; sc_path_t path; u8 buf[2048], *p = buf; size_t keysize, i; int mod_lens[] = { 512, 768, 1024, 2048 }; size_t sizes[] = { 167, 247, 327, 647 }; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } do { int mod_len = -1; r = sc_read_binary(card, idx, buf, 3, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; idx += keysize; for (i = 0; i < sizeof(sizes)/sizeof(sizes[ 0]); i++) if (sizes[i] == keysize) mod_len = mod_lens[i]; if (mod_len < 0) printf("Key %d -- unknown modulus length\n", p[2] & 0x0F); else printf("Key %d -- Modulus length %d\n", p[2] & 0x0F, mod_len); } while (1); return 0; } static int generate_key(void) { sc_apdu_t apdu; u8 sbuf[4]; u8 p2; int r; switch (opt_mod_length) { case 512: p2 = 0x40; break; case 768: p2 = 0x60; break; case 1024: p2 = 0x80; break; case 2048: p2 = 0x00; break; default: fprintf(stderr, "Invalid modulus length.\n"); return 2; } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, (u8) opt_key_num-1, p2); apdu.cla = 0xF0; apdu.lc = 4; apdu.datalen = 4; apdu.data = sbuf; sbuf[0] = opt_exponent & 0xFF; sbuf[1] = (opt_exponent >> 8) & 0xFF; sbuf[2] = (opt_exponent >> 16) & 0xFF; sbuf[3] = (opt_exponent >> 24) & 0xFF; r = select_app_df(); if (r) return 1; if (verbose) printf("Generating key...\n"); r = sc_transmit_apdu(card, &apdu); if (r) { fprintf(stderr, "APDU transmit failed: %s\n", sc_strerror(r)); if (r == SC_ERROR_TRANSMIT_FAILED) fprintf(stderr, "Reader has timed out. It is still possible that the key generation has\n" "succeeded.\n"); return 1; } if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { printf("Key generation successful.\n"); return 0; } if (apdu.sw1 == 0x69 && apdu.sw2 == 0x82) fprintf(stderr, "CHV1 not verified or invalid exponent value.\n"); else fprintf(stderr, "Card returned SW1=%02X, SW2=%02X.\n", apdu.sw1, apdu.sw2); return 1; } static int create_key_files(void) { sc_file_t *file; int mod_lens[] = { 512, 768, 1024, 2048 }; int sizes[] = { 163, 243, 323, 643 }; int size = -1; int r; size_t i; for (i = 0; i < sizeof(mod_lens) / sizeof(int); i++) if (mod_lens[i] == opt_mod_length) { size = sizes[i]; break; } if (size == -1) { fprintf(stderr, "Invalid modulus length.\n"); return 1; } if (verbose) printf("Creating key files for %d keys.\n", opt_key_count); file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x0012; file->size = opt_key_count * size + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create private key file: %s\n", sc_strerror(r)); return 1; } file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x1012; file->size = opt_key_count * (size + 4) + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create public key file: %s\n", sc_strerror(r)); return 1; } if (verbose) printf("Key files generated successfully.\n"); return 0; } static int read_rsa_privkey(RSA **rsa_out) { RSA *rsa = NULL; BIO *in = NULL; int r; in = BIO_new(BIO_s_file()); if (opt_prkeyf == NULL) { fprintf(stderr, "Private key file must be set.\n"); return 2; } r = BIO_read_filename(in, opt_prkeyf); if (r <= 0) { perror(opt_prkeyf); return 2; } rsa = PEM_read_bio_RSAPrivateKey(in, NULL, NULL, NULL); if (rsa == NULL) { fprintf(stderr, "Unable to load private key.\n"); return 2; } BIO_free(in); *rsa_out = rsa; return 0; } static int encode_private_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_p, *rsa_q, *rsa_dmp1, *rsa_dmq1, *rsa_iqmp; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 3) >> 8; *p++ = (5 * base + 3) & 0xFF; *p++ = opt_key_num; RSA_get0_factors(rsa, &rsa_p, &rsa_q); r = bn2cf(rsa_p, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_q, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; RSA_get0_crt_params(rsa, &rsa_dmp1, &rsa_dmq1, &rsa_iqmp); r = bn2cf(rsa_iqmp, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmp1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmq1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int encode_public_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_n, *rsa_e; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 7) >> 8; *p++ = (5 * base + 7) & 0xFF; *p++ = opt_key_num; RSA_get0_key(rsa, &rsa_n, &rsa_e, NULL); r = bn2cf(rsa_n, bnbuf); if (r != 2*base) { fprintf(stderr, "Invalid public key.\n"); return 2; } memcpy(p, bnbuf, 2*base); p += 2*base; memset(p, 0, base); p += base; memset(bnbuf, 0, 2*base); memcpy(p, bnbuf, 2*base); p += 2*base; r = bn2cf(rsa_e, bnbuf); memcpy(p, bnbuf, 4); p += 4; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int update_public_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write public key: %s\n", sc_strerror(r)); return 2; } return 0; } static int update_private_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write private key: %s\n", sc_strerror(r)); return 2; } return 0; } static int store_key(void) { u8 prv[1024], pub[1024]; size_t prvsize, pubsize; int r; RSA *rsa; r = read_rsa_privkey(&rsa); if (r) return r; r = encode_private_key(rsa, prv, &prvsize); if (r) return r; r = encode_public_key(rsa, pub, &pubsize); if (r) return r; if (verbose) printf("Storing private key...\n"); r = select_app_df(); if (r) return r; r = update_private_key(prv, prvsize); if (r) return r; if (verbose) printf("Storing public key...\n"); r = select_app_df(); if (r) return r; r = update_public_key(pub, pubsize); if (r) return r; return 0; } static int create_pin_file(const sc_path_t *inpath, int chv, const char *key_id) { char prompt[40], *pin, *puk; char buf[30], *p = buf; sc_path_t file_id, path; sc_file_t *file; size_t len; int r; file_id = *inpath; if (file_id.len < 2) return -1; if (chv == 1) sc_format_path("I0000", &file_id); else if (chv == 2) sc_format_path("I0100", &file_id); else return -1; r = sc_select_file(card, inpath, NULL); if (r) return -1; r = sc_select_file(card, &file_id, NULL); if (r == 0) return 0; sprintf(prompt, "Please enter CHV%d%s: ", chv, key_id); pin = getpin(prompt); if (pin == NULL) return -1; sprintf(prompt, "Please enter PUK for CHV%d%s: ", chv, key_id); puk = getpin(prompt); if (puk == NULL) { free(pin); return -1; } memset(p, 0xFF, 3); p += 3; memcpy(p, pin, 8); p += 8; *p++ = opt_pin_attempts; *p++ = opt_pin_attempts; memcpy(p, puk, 8); p += 8; *p++ = opt_puk_attempts; *p++ = opt_puk_attempts; len = p - buf; free(pin); free(puk); file = sc_file_new(); file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); if (inpath->len == 2 && inpath->value[0] == 0x3F && inpath->value[1] == 0x00) sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_AUT, 1); else sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 2); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_AUT, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_AUT, 1); file->size = len; file->id = (file_id.value[0] << 8) | file_id.value[1]; r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "PIN file creation failed: %s\n", sc_strerror(r)); return r; } path = *inpath; sc_append_path(&path, &file_id); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select created PIN file: %s\n", sc_strerror(r)); return r; } r = sc_update_binary(card, 0, (const u8 *) buf, len, 0); if (r < 0) { fprintf(stderr, "Unable to update created PIN file: %s\n", sc_strerror(r)); return r; } return 0; } static int create_pin(void) { sc_path_t path; char buf[80]; if (opt_pin_num != 1 && opt_pin_num != 2) { fprintf(stderr, "Invalid PIN number. Possible values: 1, 2.\n"); return 2; } strcpy(buf, "3F00"); if (opt_appdf != NULL) strlcat(buf, opt_appdf, sizeof buf); sc_format_path(buf, &path); return create_pin_file(&path, opt_pin_num, ""); } int main(int argc, char *argv[]) { int err = 0, r, c, long_optind = 0; int action_count = 0; int do_read_key = 0; int do_generate_key = 0; int do_create_key_files = 0; int do_list_keys = 0; int do_store_key = 0; int do_create_pin_file = 0; sc_context_param_t ctx_param; while (1) { c = getopt_long(argc, argv, "P:Vslgc:Rk:r:p:u:e:m:vwa:", options, &long_optind); if (c == -1) break; if (c == '?') util_print_usage_and_die(app_name, options, option_help, NULL); switch (c) { case 'l': do_list_keys = 1; action_count++; break; case 'P': do_create_pin_file = 1; opt_pin_num = atoi(optarg); action_count++; break; case 'R': do_read_key = 1; action_count++; break; case 'g': do_generate_key = 1; action_count++; break; case 'c': do_create_key_files = 1; opt_key_count = atoi(optarg); action_count++; break; case 's': do_store_key = 1; action_count++; break; case 'k': opt_key_num = atoi(optarg); if (opt_key_num < 1 || opt_key_num > 15) { fprintf(stderr, "Key number invalid.\n"); exit(2); } break; case 'V': opt_pin_num = 1; break; case 'e': opt_exponent = atoi(optarg); break; case 'm': opt_mod_length = atoi(optarg); break; case 'p': opt_prkeyf = optarg; break; case 'u': opt_pubkeyf = optarg; break; case 'r': opt_reader = optarg; break; case 'v': verbose++; break; case 'w': opt_wait = 1; break; case 'a': opt_appdf = optarg; break; } } if (action_count == 0) util_print_usage_and_die(app_name, options, option_help, NULL); memset(&ctx_param, 0, sizeof(ctx_param)); ctx_param.ver = 0; ctx_param.app_name = app_name; r = sc_context_create(&ctx, &ctx_param); if (r) { fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r)); return 1; } if (verbose > 1) { ctx->debug = verbose; sc_ctx_log_to_file(ctx, "stderr"); } err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose); printf("Using card driver: %s\n", card->driver->name); if (do_create_pin_file) { if ((err = create_pin()) != 0) goto end; action_count--; } if (do_create_key_files) { if ((err = create_key_files()) != 0) goto end; action_count--; } if (do_generate_key) { if ((err = generate_key()) != 0) goto end; action_count--; } if (do_store_key) { if ((err = store_key()) != 0) goto end; action_count--; } if (do_list_keys) { if ((err = list_keys()) != 0) goto end; action_count--; } if (do_read_key) { if ((err = read_key()) != 0) goto end; action_count--; } if (pincode != NULL) { memset(pincode, 0, 8); free(pincode); } end: if (card) { sc_unlock(card); sc_disconnect_card(card); } if (ctx) sc_release_context(ctx); return err; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_344_8
crossvul-cpp_data_good_343_10
/* * util.c: utility functions used by OpenSC command line tools. * * Copyright (C) 2011 OpenSC Project developers * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #ifndef _WIN32 #include <termios.h> #else #include <conio.h> #endif #include <ctype.h> #include "util.h" #include "ui/notify.h" int is_string_valid_atr(const char *atr_str) { unsigned char atr[SC_MAX_ATR_SIZE]; size_t atr_len = sizeof(atr); if (sc_hex_to_bin(atr_str, atr, &atr_len)) return 0; if (atr_len < 2) return 0; if (atr[0] != 0x3B && atr[0] != 0x3F) return 0; return 1; } int util_connect_card_ex(sc_context_t *ctx, sc_card_t **cardp, const char *reader_id, int do_wait, int do_lock, int verbose) { struct sc_reader *reader = NULL, *found = NULL; struct sc_card *card = NULL; int r; sc_notify_init(); if (do_wait) { unsigned int event; if (sc_ctx_get_reader_count(ctx) == 0) { fprintf(stderr, "Waiting for a reader to be attached...\n"); r = sc_wait_for_event(ctx, SC_EVENT_READER_ATTACHED, &found, &event, -1, NULL); if (r < 0) { fprintf(stderr, "Error while waiting for a reader: %s\n", sc_strerror(r)); return 3; } r = sc_ctx_detect_readers(ctx); if (r < 0) { fprintf(stderr, "Error while refreshing readers: %s\n", sc_strerror(r)); return 3; } } fprintf(stderr, "Waiting for a card to be inserted...\n"); r = sc_wait_for_event(ctx, SC_EVENT_CARD_INSERTED, &found, &event, -1, NULL); if (r < 0) { fprintf(stderr, "Error while waiting for a card: %s\n", sc_strerror(r)); return 3; } reader = found; } else if (sc_ctx_get_reader_count(ctx) == 0) { fprintf(stderr, "No smart card readers found.\n"); return 1; } else { if (!reader_id) { unsigned int i; /* Automatically try to skip to a reader with a card if reader not specified */ for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) { reader = sc_ctx_get_reader(ctx, i); if (sc_detect_card_presence(reader) & SC_READER_CARD_PRESENT) { fprintf(stderr, "Using reader with a card: %s\n", reader->name); goto autofound; } } /* If no reader had a card, default to the first reader */ reader = sc_ctx_get_reader(ctx, 0); } else { /* If the reader identifier looks like an ATR, try to find the reader with that card */ if (is_string_valid_atr(reader_id)) { unsigned char atr_buf[SC_MAX_ATR_SIZE]; size_t atr_buf_len = sizeof(atr_buf); unsigned int i; sc_hex_to_bin(reader_id, atr_buf, &atr_buf_len); /* Loop readers, looking for a card with ATR */ for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) { struct sc_reader *rdr = sc_ctx_get_reader(ctx, i); if (!(sc_detect_card_presence(rdr) & SC_READER_CARD_PRESENT)) continue; else if (rdr->atr.len != atr_buf_len) continue; else if (memcmp(rdr->atr.value, atr_buf, rdr->atr.len)) continue; fprintf(stderr, "Matched ATR in reader: %s\n", rdr->name); reader = rdr; goto autofound; } } else { char *endptr = NULL; unsigned int num; errno = 0; num = strtol(reader_id, &endptr, 0); if (!errno && endptr && *endptr == '\0') reader = sc_ctx_get_reader(ctx, num); else reader = sc_ctx_get_reader_by_name(ctx, reader_id); } } autofound: if (!reader) { fprintf(stderr, "Reader \"%s\" not found (%d reader(s) detected)\n", reader_id, sc_ctx_get_reader_count(ctx)); return 1; } if (sc_detect_card_presence(reader) <= 0) { fprintf(stderr, "Card not present.\n"); return 3; } } if (verbose) printf("Connecting to card in reader %s...\n", reader->name); r = sc_connect_card(reader, &card); if (r < 0) { fprintf(stderr, "Failed to connect to card: %s\n", sc_strerror(r)); return 1; } if (verbose) printf("Using card driver %s.\n", card->driver->name); if (do_lock) { r = sc_lock(card); if (r < 0) { fprintf(stderr, "Failed to lock card: %s\n", sc_strerror(r)); sc_disconnect_card(card); return 1; } } *cardp = card; return 0; } int util_connect_card(sc_context_t *ctx, sc_card_t **cardp, const char *reader_id, int do_wait, int verbose) { return util_connect_card_ex(ctx, cardp, reader_id, do_wait, 1, verbose); } void util_print_binary(FILE *f, const u8 *buf, int count) { int i; for (i = 0; i < count; i++) { unsigned char c = buf[i]; const char *format; if (!isprint(c)) format = "\\x%02X"; else format = "%c"; fprintf(f, format, c); } (void) fflush(f); } void util_hex_dump(FILE *f, const u8 *in, int len, const char *sep) { int i; for (i = 0; i < len; i++) { if (sep != NULL && i) fprintf(f, "%s", sep); fprintf(f, "%02X", in[i]); } } void util_hex_dump_asc(FILE *f, const u8 *in, size_t count, int addr) { int lines = 0; while (count) { char ascbuf[17]; size_t i; if (addr >= 0) { fprintf(f, "%08X: ", addr); addr += 16; } for (i = 0; i < count && i < 16; i++) { fprintf(f, "%02X ", *in); if (isprint(*in)) ascbuf[i] = *in; else ascbuf[i] = '.'; in++; } count -= i; ascbuf[i] = 0; for (; i < 16 && lines; i++) fprintf(f, " "); fprintf(f, "%s\n", ascbuf); lines++; } } NORETURN void util_print_usage_and_die(const char *app_name, const struct option options[], const char *option_help[], const char *args) { int i; int header_shown = 0; if (args) printf("Usage: %s [OPTIONS] %s\n", app_name, args); else printf("Usage: %s [OPTIONS]\n", app_name); for (i = 0; options[i].name; i++) { char buf[40]; const char *arg_str; /* Skip "hidden" options */ if (option_help[i] == NULL) continue; if (!header_shown++) printf("Options:\n"); switch (options[i].has_arg) { case 1: arg_str = " <arg>"; break; case 2: arg_str = " [arg]"; break; default: arg_str = ""; break; } if (isascii(options[i].val) && isprint(options[i].val) && !isspace(options[i].val)) sprintf(buf, "-%c, --%s%s", options[i].val, options[i].name, arg_str); else sprintf(buf, " --%s%s", options[i].name, arg_str); /* print the line - wrap if necessary */ if (strlen(buf) > 28) { printf(" %s\n", buf); buf[0] = '\0'; } printf(" %-28s %s\n", buf, option_help[i]); } exit(2); } const char * util_acl_to_str(const sc_acl_entry_t *e) { static char line[80], buf[20]; unsigned int acl; if (e == NULL) return "N/A"; line[0] = 0; while (e != NULL) { acl = e->method; switch (acl) { case SC_AC_UNKNOWN: return "N/A"; case SC_AC_NEVER: return "NEVR"; case SC_AC_NONE: return "NONE"; case SC_AC_CHV: strcpy(buf, "CHV"); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "%d", e->key_ref); break; case SC_AC_TERM: strcpy(buf, "TERM"); break; case SC_AC_PRO: strcpy(buf, "PROT"); break; case SC_AC_AUT: strcpy(buf, "AUTH"); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 4, "%d", e->key_ref); break; case SC_AC_SEN: strcpy(buf, "Sec.Env. "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "#%d", e->key_ref); break; case SC_AC_SCB: strcpy(buf, "Sec.ControlByte "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "Ox%X", e->key_ref); break; case SC_AC_IDA: strcpy(buf, "PKCS#15 AuthID "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "#%d", e->key_ref); break; default: strcpy(buf, "????"); break; } strncat(line, buf, sizeof line); strncat(line, " ", sizeof line); e = e->next; } line[(sizeof line)-1] = '\0'; /* make sure it's NUL terminated */ line[strlen(line)-1] = 0; /* get rid of trailing space */ return line; } NORETURN void util_fatal(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\nAborting.\n"); va_end(ap); sc_notify_close(); exit(1); } void util_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } void util_warn(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "warning: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } int util_getpass (char **lineptr, size_t *len, FILE *stream) { #define MAX_PASS_SIZE 128 char *buf; size_t i; int ch = 0; #ifndef _WIN32 struct termios old, new; fflush(stdout); if (tcgetattr (fileno (stdout), &old) != 0) return -1; new = old; new.c_lflag &= ~ECHO; if (tcsetattr (fileno (stdout), TCSAFLUSH, &new) != 0) return -1; #endif buf = calloc(1, MAX_PASS_SIZE); if (!buf) return -1; for (i = 0; i < MAX_PASS_SIZE - 1; i++) { #ifndef _WIN32 ch = getchar(); #else ch = _getch(); #endif if (ch == 0 || ch == 3) break; if (ch == '\n' || ch == '\r') break; buf[i] = (char) ch; } #ifndef _WIN32 tcsetattr (fileno (stdout), TCSAFLUSH, &old); fputs("\n", stdout); #endif if (ch == 0 || ch == 3) { free(buf); return -1; } if (*lineptr && (!len || *len < i+1)) { free(*lineptr); *lineptr = NULL; } if (*lineptr) { memcpy(*lineptr,buf,i+1); memset(buf, 0, MAX_PASS_SIZE); free(buf); } else { *lineptr = buf; if (len) *len = MAX_PASS_SIZE; } return i; } size_t util_get_pin(const char *input, const char **pin) { size_t inputlen = strlen(input); size_t pinlen = 0; if(inputlen > 4 && strncasecmp(input, "env:", 4) == 0) { // Get a PIN from a environment variable *pin = getenv(input + 4); pinlen = *pin ? strlen(*pin) : 0; } else { //Just use the input *pin = input; pinlen = inputlen; } return pinlen; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_343_10
crossvul-cpp_data_bad_4946_2
#include "cache.h" #include "tag.h" #include "commit.h" #include "tree.h" #include "blob.h" #include "diff.h" #include "tree-walk.h" #include "revision.h" #include "list-objects.h" static void process_blob(struct rev_info *revs, struct blob *blob, show_object_fn show, struct strbuf *path, const char *name, void *cb_data) { struct object *obj = &blob->object; if (!revs->blob_objects) return; if (!obj) die("bad blob object"); if (obj->flags & (UNINTERESTING | SEEN)) return; obj->flags |= SEEN; show(obj, path, name, cb_data); } /* * Processing a gitlink entry currently does nothing, since * we do not recurse into the subproject. * * We *could* eventually add a flag that actually does that, * which would involve: * - is the subproject actually checked out? * - if so, see if the subproject has already been added * to the alternates list, and add it if not. * - process the commit (or tag) the gitlink points to * recursively. * * However, it's unclear whether there is really ever any * reason to see superprojects and subprojects as such a * "unified" object pool (potentially resulting in a totally * humongous pack - avoiding which was the whole point of * having gitlinks in the first place!). * * So for now, there is just a note that we *could* follow * the link, and how to do it. Whether it necessarily makes * any sense what-so-ever to ever do that is another issue. */ static void process_gitlink(struct rev_info *revs, const unsigned char *sha1, show_object_fn show, struct strbuf *path, const char *name, void *cb_data) { /* Nothing to do */ } static void process_tree(struct rev_info *revs, struct tree *tree, show_object_fn show, struct strbuf *base, const char *name, void *cb_data) { struct object *obj = &tree->object; struct tree_desc desc; struct name_entry entry; enum interesting match = revs->diffopt.pathspec.nr == 0 ? all_entries_interesting: entry_not_interesting; int baselen = base->len; if (!revs->tree_objects) return; if (!obj) die("bad tree object"); if (obj->flags & (UNINTERESTING | SEEN)) return; if (parse_tree_gently(tree, revs->ignore_missing_links) < 0) { if (revs->ignore_missing_links) return; die("bad tree object %s", oid_to_hex(&obj->oid)); } obj->flags |= SEEN; show(obj, base, name, cb_data); strbuf_addstr(base, name); if (base->len) strbuf_addch(base, '/'); init_tree_desc(&desc, tree->buffer, tree->size); while (tree_entry(&desc, &entry)) { if (match != all_entries_interesting) { match = tree_entry_interesting(&entry, base, 0, &revs->diffopt.pathspec); if (match == all_entries_not_interesting) break; if (match == entry_not_interesting) continue; } if (S_ISDIR(entry.mode)) process_tree(revs, lookup_tree(entry.sha1), show, base, entry.path, cb_data); else if (S_ISGITLINK(entry.mode)) process_gitlink(revs, entry.sha1, show, base, entry.path, cb_data); else process_blob(revs, lookup_blob(entry.sha1), show, base, entry.path, cb_data); } strbuf_setlen(base, baselen); free_tree_buffer(tree); } static void mark_edge_parents_uninteresting(struct commit *commit, struct rev_info *revs, show_edge_fn show_edge) { struct commit_list *parents; for (parents = commit->parents; parents; parents = parents->next) { struct commit *parent = parents->item; if (!(parent->object.flags & UNINTERESTING)) continue; mark_tree_uninteresting(parent->tree); if (revs->edge_hint && !(parent->object.flags & SHOWN)) { parent->object.flags |= SHOWN; show_edge(parent); } } } void mark_edges_uninteresting(struct rev_info *revs, show_edge_fn show_edge) { struct commit_list *list; int i; for (list = revs->commits; list; list = list->next) { struct commit *commit = list->item; if (commit->object.flags & UNINTERESTING) { mark_tree_uninteresting(commit->tree); if (revs->edge_hint_aggressive && !(commit->object.flags & SHOWN)) { commit->object.flags |= SHOWN; show_edge(commit); } continue; } mark_edge_parents_uninteresting(commit, revs, show_edge); } if (revs->edge_hint_aggressive) { for (i = 0; i < revs->cmdline.nr; i++) { struct object *obj = revs->cmdline.rev[i].item; struct commit *commit = (struct commit *)obj; if (obj->type != OBJ_COMMIT || !(obj->flags & UNINTERESTING)) continue; mark_tree_uninteresting(commit->tree); if (!(obj->flags & SHOWN)) { obj->flags |= SHOWN; show_edge(commit); } } } } static void add_pending_tree(struct rev_info *revs, struct tree *tree) { add_pending_object(revs, &tree->object, ""); } void traverse_commit_list(struct rev_info *revs, show_commit_fn show_commit, show_object_fn show_object, void *data) { int i; struct commit *commit; struct strbuf base; strbuf_init(&base, PATH_MAX); while ((commit = get_revision(revs)) != NULL) { /* * an uninteresting boundary commit may not have its tree * parsed yet, but we are not going to show them anyway */ if (commit->tree) add_pending_tree(revs, commit->tree); show_commit(commit, data); } for (i = 0; i < revs->pending.nr; i++) { struct object_array_entry *pending = revs->pending.objects + i; struct object *obj = pending->item; const char *name = pending->name; const char *path = pending->path; if (obj->flags & (UNINTERESTING | SEEN)) continue; if (obj->type == OBJ_TAG) { obj->flags |= SEEN; show_object(obj, NULL, name, data); continue; } if (!path) path = ""; if (obj->type == OBJ_TREE) { process_tree(revs, (struct tree *)obj, show_object, &base, path, data); continue; } if (obj->type == OBJ_BLOB) { process_blob(revs, (struct blob *)obj, show_object, NULL, path, data); continue; } die("unknown pending object %s (%s)", oid_to_hex(&obj->oid), name); } object_array_clear(&revs->pending); strbuf_release(&base); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4946_2
crossvul-cpp_data_good_1611_3
/* t1disasm * * This program `disassembles' Adobe Type-1 font programs in either PFB or PFA * format. It produces a human readable/editable pseudo-PostScript file by * performing eexec and charstring decryption as specified in the `Adobe Type 1 * Font Format' version 1.1 (the `black book'). There is a companion program, * t1asm, which `assembles' such a pseudo-PostScript file into either PFB or * PFA format. * * Copyright (c) 1992 by I. Lee Hetherington, all rights reserved. * Copyright (c) 1998-2013 Eddie Kohler * * 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, subject to the * conditions listed in the Click LICENSE file, which is available in full at * http://github.com/kohler/click/blob/master/LICENSE. The conditions * include: you must preserve this copyright notice, and you cannot mention * the copyright holders in advertising related to the Software without * their permission. The Software is provided WITHOUT ANY WARRANTY, EXPRESS * OR IMPLIED. This notice is a summary of the Click LICENSE file; the * license in that file is binding. * * New change log in `NEWS'. Old change log: * * Revision 1.4 92/07/10 10:55:08 ilh * Added support for additional PostScript after the closefile command * (ie., some fonts have {restore}if' after the cleartomark). Also, * removed hardwired charstring start command (-| or RD) in favor of * automatically determining it. * * Revision 1.3 92/06/23 10:57:53 ilh * MSDOS porting by Kai-Uwe Herbing (herbing@netmbx.netmbx.de) * incoporated. * * Revision 1.2 92/05/22 12:05:33 ilh * Fixed bug where we were counting on sprintf to return its first * argument---not true in ANSI C. This bug was detected by Piet * Tutelaers (rcpt@urc.tue.nl). Also, fixed (signed) integer overflow * error when testing high-order bit of integer for possible * sign-extension by making comparison between unsigned integers. * * Revision 1.1 92/05/22 12:04:07 ilh * initial version * * Ported to Microsoft C/C++ Compiler and MS-DOS operating system by * Kai-Uwe Herbing (herbing@netmbx.netmbx.de) on June 12, 1992. Code * specific to the MS-DOS version is encapsulated with #ifdef _MSDOS * ... #endif, where _MSDOS is an identifier, which is automatically * defined, if you compile with the Microsoft C/C++ Compiler. * */ /* Note: this is ANSI C. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #if defined(_MSDOS) || defined(_WIN32) # include <fcntl.h> # include <io.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h> #include <stdarg.h> #include <errno.h> #include <assert.h> #include <lcdf/clp.h> #include "t1lib.h" #include "t1asmhelp.h" #ifdef __cplusplus extern "C" { #endif typedef unsigned char byte; static FILE *ofp; static int unknown = 0; /* decryption stuff */ static uint16_t c1 = 52845, c2 = 22719; static uint16_t cr_default = 4330; static uint16_t er_default = 55665; static int error_count = 0; /* Subroutine to output strings. */ static void output(const char *string) { fprintf(ofp, "%s", string); } /* Subroutine to neatly format output of charstring tokens. If token = "\n", then a newline is output. If at start of line (start == 1), prefix token with tab, otherwise a space. */ static void output_token(const char *token) { static int start = 1; if (strcmp(token, "\n") == 0) { fprintf(ofp, "\n"); start = 1; } else { fprintf(ofp, "%s%s", start ? "\t" : " ", token); start = 0; } } /* Subroutine to decrypt and ASCII-ify tokens in charstring data. The charstring decryption machinery is fired up, skipping the first lenIV bytes, and the decrypted tokens are expanded into human-readable form. */ static void decrypt_charstring(unsigned char *line, int len) { int i; int32_t val; char buf[20]; /* decrypt charstring */ if (lenIV >= 0) { /* only decrypt if lenIV >= 0 -- negative lenIV means unencrypted charstring. Thanks to Tom Kacvinsky <tjk@ams.org> */ uint16_t cr = cr_default; byte plain; for (i = 0; i < len; i++) { byte cipher = line[i]; plain = (byte)(cipher ^ (cr >> 8)); cr = (uint16_t)((cipher + cr) * c1 + c2); line[i] = plain; } line += lenIV; len -= lenIV; } /* handle each charstring command */ for (i = 0; i < len; i++) { byte b = line[i]; if (b >= 32) { if (b >= 32 && b <= 246) val = b - 139; else if (b >= 247 && b <= 250) { i++; val = (b - 247)*256 + 108 + line[i]; } else if (b >= 251 && b <= 254) { i++; val = -(b - 251)*256 - 108 - line[i]; } else { val = (line[i+1] & 0xff) << 24; val |= (line[i+2] & 0xff) << 16; val |= (line[i+3] & 0xff) << 8; val |= (line[i+4] & 0xff) << 0; /* in case an int32 is larger than four bytes---sign extend */ #if INT_MAX > 0x7FFFFFFFUL if (val & 0x80000000) val |= ~0x7FFFFFFF; #endif i += 4; } sprintf(buf, "%d", val); output_token(buf); } else { switch (b) { case 0: output_token("error"); break; /* special */ case 1: output_token("hstem"); break; case 3: output_token("vstem"); break; case 4: output_token("vmoveto"); break; case 5: output_token("rlineto"); break; case 6: output_token("hlineto"); break; case 7: output_token("vlineto"); break; case 8: output_token("rrcurveto"); break; case 9: output_token("closepath"); break; /* Type 1 ONLY */ case 10: output_token("callsubr"); break; case 11: output_token("return"); break; case 13: output_token("hsbw"); break; /* Type 1 ONLY */ case 14: output_token("endchar"); break; case 16: output_token("blend"); break; /* Type 2 */ case 18: output_token("hstemhm"); break; /* Type 2 */ case 19: output_token("hintmask"); break; /* Type 2 */ case 20: output_token("cntrmask"); break; /* Type 2 */ case 21: output_token("rmoveto"); break; case 22: output_token("hmoveto"); break; case 23: output_token("vstemhm"); break; /* Type 2 */ case 24: output_token("rcurveline"); break; /* Type 2 */ case 25: output_token("rlinecurve"); break; /* Type 2 */ case 26: output_token("vvcurveto"); break; /* Type 2 */ case 27: output_token("hhcurveto"); break; /* Type 2 */ case 28: { /* Type 2 */ /* short integer */ val = (line[i+1] & 0xff) << 8; val |= (line[i+2] & 0xff); i += 2; if (val & 0x8000) val |= ~0x7FFF; sprintf(buf, "%d", val); output_token(buf); } case 29: output_token("callgsubr"); break; /* Type 2 */ case 30: output_token("vhcurveto"); break; case 31: output_token("hvcurveto"); break; case 12: i++; b = line[i]; switch (b) { case 0: output_token("dotsection"); break; /* Type 1 ONLY */ case 1: output_token("vstem3"); break; /* Type 1 ONLY */ case 2: output_token("hstem3"); break; /* Type 1 ONLY */ case 3: output_token("and"); break; /* Type 2 */ case 4: output_token("or"); break; /* Type 2 */ case 5: output_token("not"); break; /* Type 2 */ case 6: output_token("seac"); break; /* Type 1 ONLY */ case 7: output_token("sbw"); break; /* Type 1 ONLY */ case 8: output_token("store"); break; /* Type 2 */ case 9: output_token("abs"); break; /* Type 2 */ case 10: output_token("add"); break; /* Type 2 */ case 11: output_token("sub"); break; /* Type 2 */ case 12: output_token("div"); break; case 13: output_token("load"); break; /* Type 2 */ case 14: output_token("neg"); break; /* Type 2 */ case 15: output_token("eq"); break; /* Type 2 */ case 16: output_token("callothersubr"); break; /* Type 1 ONLY */ case 17: output_token("pop"); break; /* Type 1 ONLY */ case 18: output_token("drop"); break; /* Type 2 */ case 20: output_token("put"); break; /* Type 2 */ case 21: output_token("get"); break; /* Type 2 */ case 22: output_token("ifelse"); break; /* Type 2 */ case 23: output_token("random"); break; /* Type 2 */ case 24: output_token("mul"); break; /* Type 2 */ case 26: output_token("sqrt"); break; /* Type 2 */ case 27: output_token("dup"); break; /* Type 2 */ case 28: output_token("exch"); break; /* Type 2 */ case 29: output_token("index"); break; /* Type 2 */ case 30: output_token("roll"); break; /* Type 2 */ case 33: output_token("setcurrentpoint"); break;/* Type 1 ONLY */ case 34: output_token("hflex"); break; /* Type 2 */ case 35: output_token("flex"); break; /* Type 2 */ case 36: output_token("hflex1"); break; /* Type 2 */ case 37: output_token("flex1"); break; /* Type 2 */ default: sprintf(buf, "escape_%d", b); unknown++; output_token(buf); break; } break; default: sprintf(buf, "UNKNOWN_%d", b); unknown++; output_token(buf); break; } output_token("\n"); } } if (i > len) { output("\terror\n"); error("disassembly error: charstring too short"); } } /* Disassembly font_reader functions */ static int in_eexec = 0; static unsigned char *save = 0; static int save_len = 0; static int save_cap = 0; static void append_save(const unsigned char *line, int len) { if (line == save) { assert(len <= save_cap); save_len = len; return; } if (save_len + len >= save_cap) { unsigned char *new_save; if (!save_cap) save_cap = 1024; while (save_len + len >= save_cap) save_cap *= 2; new_save = (unsigned char *)malloc(save_cap); if (!new_save) fatal_error("out of memory"); memcpy(new_save, save, save_len); free(save); save = new_save; } memcpy(save + save_len, line, len); save_len += len; } /* 23.Feb.2004 - use 'memstr', not strstr, because the strings input to eexec_line aren't null terminated! Reported by Werner Lemberg. */ static const unsigned char * oog_memstr(const unsigned char *line, int line_len, const char *pattern, int pattern_len) { const unsigned char *try; const unsigned char *last = line + line_len - pattern_len + 1; while (line < last && (try = memchr(line, (unsigned char)*pattern, last - line))) { if (memcmp(try, pattern, pattern_len) == 0) return try; else line = try + 1; } return 0; } /* returns 1 if next \n should be deleted */ static int eexec_line(unsigned char *line, int line_len) { int cs_start_len = strlen(cs_start); int pos; int first_space; int digits; int cut_newline = 0; /* append this data to the end of `save' if necessary */ if (save_len) { append_save(line, line_len); line = save; line_len = save_len; save_len = 0; } if (!line_len) return 0; /* Look for charstring start */ /* skip first word */ for (pos = 0; pos < line_len && isspace(line[pos]); pos++) ; while (pos < line_len && !isspace(line[pos])) pos++; if (pos >= line_len) goto not_charstring; /* skip spaces */ first_space = pos; while (pos < line_len && isspace(line[pos])) pos++; if (pos >= line_len || !isdigit(line[pos])) goto not_charstring; /* skip number */ digits = pos; while (pos < line_len && isdigit(line[pos])) pos++; /* check for subr (another number) */ if (pos < line_len - 1 && isspace(line[pos]) && isdigit(line[pos+1])) { first_space = pos; digits = pos + 1; for (pos = digits; pos < line_len && isdigit(line[pos]); pos++) ; } /* check for charstring start */ if (pos + 2 + cs_start_len < line_len && pos > digits && line[pos] == ' ' && strncmp((const char *)(line + pos + 1), cs_start, cs_start_len) == 0 && line[pos + 1 + cs_start_len] == ' ') { /* check if charstring is long enough */ int cs_len = atoi((const char *)(line + digits)); if (pos + 2 + cs_start_len + cs_len < line_len) { /* long enough! */ if (line[line_len - 1] == '\r') { line[line_len - 1] = '\n'; cut_newline = 1; } fprintf(ofp, "%.*s {\n", first_space, line); decrypt_charstring(line + pos + 2 + cs_start_len, cs_len); pos += 2 + cs_start_len + cs_len; fprintf(ofp, "\t}%.*s", line_len - pos, line + pos); return cut_newline; } else { /* not long enough! */ append_save(line, line_len); return 0; } } /* otherwise, just output the line */ not_charstring: /* 6.Oct.2003 - Werner Lemberg reports a stupid Omega font that behaves badly: a charstring definition follows "/Charstrings ... begin", ON THE SAME LINE. */ { const char *CharStrings = (const char *) oog_memstr(line, line_len, "/CharStrings ", 13); int crap, n; char should_be_slash = 0; if (CharStrings && sscanf(CharStrings + 12, " %d dict dup begin %c%n", &crap, &should_be_slash, &n) >= 2 && should_be_slash == '/') { int len = (CharStrings + 12 + n - 1) - (char *) line; fprintf(ofp, "%.*s\n", len, line); return eexec_line((unsigned char *) (CharStrings + 12 + n - 1), line_len - len); } } if (line[line_len - 1] == '\r') { line[line_len - 1] = '\n'; cut_newline = 1; } set_lenIV((char *)line); set_cs_start((char *)line); fprintf(ofp, "%.*s", line_len, line); /* look for `currentfile closefile' to see if we should stop decrypting */ if (oog_memstr(line, line_len, "currentfile closefile", 21) != 0) in_eexec = -1; return cut_newline; } static int all_zeroes(const char *string) { if (*string != '0') return 0; while (*string == '0') string++; return *string == '\0' || *string == '\n'; } static void disasm_output_ascii(char *line, int len) { int was_in_eexec = in_eexec; (void) len; /* avoid warning */ in_eexec = 0; /* if we came from a binary section, we need to process that too */ if (was_in_eexec > 0) { unsigned char zero = 0; eexec_line(&zero, 0); } /* if we just came from the "ASCII part" of an eexec section, we need to process the saved lines */ if (was_in_eexec < 0) { int i = 0; int save_char = 0; /* note: save[] is unsigned char * */ while (i < save_len) { /* grab a line */ int start = i; while (i < save_len && save[i] != '\r' && save[i] != '\n') i++; if (i < save_len) { if (i < save_len - 1 && save[i] == '\r' && save[i+1] == '\n') save_char = -1; else save_char = save[i+1]; save[i] = '\n'; save[i+1] = 0; } else save[i] = 0; /* output it */ disasm_output_ascii((char *)(save + start), -1); /* repair damage */ if (i < save_len) { if (save_char >= 0) { save[i+1] = save_char; i++; } else i += 2; } } save_len = 0; } if (!all_zeroes(line)) output(line); } /* collect until '\n' or end of binary section */ static void disasm_output_binary(unsigned char *data, int len) { static int ignore_newline; static uint16_t er; byte plain; int i; /* in the ASCII portion of a binary section, just save this data */ if (in_eexec < 0) { append_save(data, len); return; } /* eexec initialization */ if (in_eexec == 0) { er = er_default; ignore_newline = 0; in_eexec = 0; } if (in_eexec < 4) { for (i = 0; i < len && in_eexec < 4; i++, in_eexec++) { byte cipher = data[i]; plain = (byte)(cipher ^ (er >> 8)); er = (uint16_t)((cipher + er) * c1 + c2); data[i] = plain; } data += i; len -= i; } /* now make lines: collect until '\n' or '\r' and pass them off to eexec_line. */ i = 0; while (in_eexec > 0) { int start = i; for (; i < len; i++) { byte cipher = data[i]; plain = (byte)(cipher ^ (er >> 8)); er = (uint16_t)((cipher + er) * c1 + c2); data[i] = plain; if (plain == '\r' || plain == '\n') break; } if (ignore_newline && start < i && data[start] == '\n') { ignore_newline = 0; continue; } if (i >= len) { if (start < len) append_save(data + start, i - start); break; } i++; ignore_newline = eexec_line(data + start, i - start); } /* if in_eexec < 0, we have some plaintext lines sitting around in a binary section of the PFB. save them for later */ if (in_eexec < 0 && i < len) append_save(data + i, len - i); } static void disasm_output_end(void) { /* take care of leftover saved data */ static char crap[1] = ""; disasm_output_ascii(crap, 0); } /***** * Command line **/ #define OUTPUT_OPT 301 #define VERSION_OPT 302 #define HELP_OPT 303 static Clp_Option options[] = { { "help", 0, HELP_OPT, 0, 0 }, { "output", 'o', OUTPUT_OPT, Clp_ValString, 0 }, { "version", 0, VERSION_OPT, 0, 0 }, }; static const char *program_name; void fatal_error(const char *message, ...) { va_list val; va_start(val, message); fprintf(stderr, "%s: ", program_name); vfprintf(stderr, message, val); fputc('\n', stderr); va_end(val); exit(1); } void error(const char *message, ...) { va_list val; va_start(val, message); fprintf(stderr, "%s: ", program_name); vfprintf(stderr, message, val); fputc('\n', stderr); error_count++; va_end(val); } static void short_usage(void) { fprintf(stderr, "Usage: %s [INPUT [OUTPUT]]\n\ Try `%s --help' for more information.\n", program_name, program_name); } static void usage(void) { printf("\ `T1disasm' translates a PostScript Type 1 font in PFB or PFA format into a\n\ human-readable, human-editable form. The result is written to the standard\n\ output unless an OUTPUT file is given.\n\ \n\ Usage: %s [OPTION]... [INPUT [OUTPUT]]\n\ \n\ Options:\n\ -o, --output=FILE Write output to FILE.\n\ -h, --help Print this message and exit.\n\ --version Print version number and warranty and exit.\n\ \n\ Report bugs to <ekohler@gmail.com>.\n", program_name); } #ifdef __cplusplus } #endif int main(int argc, char *argv[]) { struct font_reader fr; int c; FILE *ifp = 0; const char *ifp_filename = "<stdin>"; Clp_Parser *clp = Clp_NewParser(argc, (const char * const *)argv, sizeof(options) / sizeof(options[0]), options); program_name = Clp_ProgramName(clp); /* interpret command line arguments using CLP */ while (1) { int opt = Clp_Next(clp); switch (opt) { output_file: case OUTPUT_OPT: if (ofp) fatal_error("output file already specified"); if (strcmp(clp->vstr, "-") == 0) ofp = stdout; else { ofp = fopen(clp->vstr, "w"); if (!ofp) fatal_error("%s: %s", clp->vstr, strerror(errno)); } break; case HELP_OPT: usage(); exit(0); break; case VERSION_OPT: printf("t1disasm (LCDF t1utils) %s\n", VERSION); printf("Copyright (C) 1992-2010 I. Lee Hetherington, Eddie Kohler et al.\n\ This is free software; see the source for copying conditions.\n\ There is NO warranty, not even for merchantability or fitness for a\n\ particular purpose.\n"); exit(0); break; case Clp_NotOption: if (ifp && ofp) fatal_error("too many arguments"); else if (ifp) goto output_file; if (strcmp(clp->vstr, "-") == 0) ifp = stdin; else { ifp_filename = clp->vstr; ifp = fopen(clp->vstr, "rb"); if (!ifp) fatal_error("%s: %s", clp->vstr, strerror(errno)); } break; case Clp_Done: goto done; case Clp_BadOption: short_usage(); exit(1); break; } } done: if (!ifp) ifp = stdin; if (!ofp) ofp = stdout; #if defined(_MSDOS) || defined(_WIN32) /* As we might be processing a PFB (binary) input file, we must set its file mode to binary. */ _setmode(_fileno(ifp), _O_BINARY); #endif /* prepare font reader */ fr.output_ascii = disasm_output_ascii; fr.output_binary = disasm_output_binary; fr.output_end = disasm_output_end; /* peek at first byte to see if it is the PFB marker 0x80 */ c = getc(ifp); ungetc(c, ifp); /* do the file */ if (c == PFB_MARKER) process_pfb(ifp, ifp_filename, &fr); else if (c == '%') process_pfa(ifp, ifp_filename, &fr); else fatal_error("%s does not start with font marker (`%%' or 0x80)", ifp_filename); fclose(ifp); fclose(ofp); if (unknown) error((unknown > 1 ? "encountered %d unknown charstring commands" : "encountered %d unknown charstring command"), unknown); return (error_count ? 1 : 0); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1611_3
crossvul-cpp_data_good_2192_0
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2014 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: The typical suspects | | Pollita <pollita@php.net> | | Marcus Boerger <helly@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ /* {{{ includes */ #include "php.h" #include "php_network.h" #if HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef PHP_WIN32 # include "win32/inet.h" # include <winsock2.h> # include <windows.h> # include <Ws2tcpip.h> #else /* This holds good for NetWare too, both for Winsock and Berkeley sockets */ #include <netinet/in.h> #if HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #include <netdb.h> #ifdef _OSD_POSIX #undef STATUS #undef T_UNSPEC #endif #if HAVE_ARPA_NAMESER_H #ifdef DARWIN # define BIND_8_COMPAT 1 #endif #include <arpa/nameser.h> #endif #if HAVE_RESOLV_H #include <resolv.h> #endif #ifdef HAVE_DNS_H #include <dns.h> #endif #endif /* Borrowed from SYS/SOCKET.H */ #if defined(NETWARE) && defined(USE_WINSOCK) #define AF_INET 2 /* internetwork: UDP, TCP, etc. */ #endif #ifndef MAXHOSTNAMELEN #define MAXHOSTNAMELEN 255 #endif /* For the local hostname obtained via gethostname which is different from the dns-related MAXHOSTNAMELEN constant above */ #ifndef HOST_NAME_MAX #define HOST_NAME_MAX 255 #endif #include "php_dns.h" /* type compat */ #ifndef DNS_T_A #define DNS_T_A 1 #endif #ifndef DNS_T_NS #define DNS_T_NS 2 #endif #ifndef DNS_T_CNAME #define DNS_T_CNAME 5 #endif #ifndef DNS_T_SOA #define DNS_T_SOA 6 #endif #ifndef DNS_T_PTR #define DNS_T_PTR 12 #endif #ifndef DNS_T_HINFO #define DNS_T_HINFO 13 #endif #ifndef DNS_T_MINFO #define DNS_T_MINFO 14 #endif #ifndef DNS_T_MX #define DNS_T_MX 15 #endif #ifndef DNS_T_TXT #define DNS_T_TXT 16 #endif #ifndef DNS_T_AAAA #define DNS_T_AAAA 28 #endif #ifndef DNS_T_SRV #define DNS_T_SRV 33 #endif #ifndef DNS_T_NAPTR #define DNS_T_NAPTR 35 #endif #ifndef DNS_T_A6 #define DNS_T_A6 38 #endif #ifndef DNS_T_ANY #define DNS_T_ANY 255 #endif /* }}} */ static char *php_gethostbyaddr(char *ip); static char *php_gethostbyname(char *name); #ifdef HAVE_GETHOSTNAME /* {{{ proto string gethostname() Get the host name of the current machine */ PHP_FUNCTION(gethostname) { char buf[HOST_NAME_MAX]; if (zend_parse_parameters_none() == FAILURE) { return; } if (gethostname(buf, sizeof(buf) - 1)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to fetch host [%d]: %s", errno, strerror(errno)); RETURN_FALSE; } RETURN_STRING(buf, 1); } /* }}} */ #endif /* TODO: Reimplement the gethostby* functions using the new winxp+ API, in dns_win32.c, then we can have a dns.c, dns_unix.c and dns_win32.c instead of a messy dns.c full of #ifdef */ /* {{{ proto string gethostbyaddr(string ip_address) Get the Internet host name corresponding to a given IP address */ PHP_FUNCTION(gethostbyaddr) { char *addr; int addr_len; char *hostname; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &addr, &addr_len) == FAILURE) { return; } hostname = php_gethostbyaddr(addr); if (hostname == NULL) { #if HAVE_IPV6 && HAVE_INET_PTON php_error_docref(NULL TSRMLS_CC, E_WARNING, "Address is not a valid IPv4 or IPv6 address"); #else php_error_docref(NULL TSRMLS_CC, E_WARNING, "Address is not in a.b.c.d form"); #endif RETVAL_FALSE; } else { RETVAL_STRING(hostname, 0); } } /* }}} */ /* {{{ php_gethostbyaddr */ static char *php_gethostbyaddr(char *ip) { #if HAVE_IPV6 && HAVE_INET_PTON struct in6_addr addr6; #endif struct in_addr addr; struct hostent *hp; #if HAVE_IPV6 && HAVE_INET_PTON if (inet_pton(AF_INET6, ip, &addr6)) { hp = gethostbyaddr((char *) &addr6, sizeof(addr6), AF_INET6); } else if (inet_pton(AF_INET, ip, &addr)) { hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET); } else { return NULL; } #else addr.s_addr = inet_addr(ip); if (addr.s_addr == -1) { return NULL; } hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET); #endif if (!hp || hp->h_name == NULL || hp->h_name[0] == '\0') { return estrdup(ip); } return estrdup(hp->h_name); } /* }}} */ /* {{{ proto string gethostbyname(string hostname) Get the IP address corresponding to a given Internet host name */ PHP_FUNCTION(gethostbyname) { char *hostname; int hostname_len; char *addr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &hostname, &hostname_len) == FAILURE) { return; } addr = php_gethostbyname(hostname); RETVAL_STRING(addr, 0); } /* }}} */ /* {{{ proto array gethostbynamel(string hostname) Return a list of IP addresses that a given hostname resolves to. */ PHP_FUNCTION(gethostbynamel) { char *hostname; int hostname_len; struct hostent *hp; struct in_addr in; int i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &hostname, &hostname_len) == FAILURE) { return; } hp = gethostbyname(hostname); if (hp == NULL || hp->h_addr_list == NULL) { RETURN_FALSE; } array_init(return_value); for (i = 0 ; hp->h_addr_list[i] != 0 ; i++) { in = *(struct in_addr *) hp->h_addr_list[i]; add_next_index_string(return_value, inet_ntoa(in), 1); } } /* }}} */ /* {{{ php_gethostbyname */ static char *php_gethostbyname(char *name) { struct hostent *hp; struct in_addr in; hp = gethostbyname(name); if (!hp || !*(hp->h_addr_list)) { return estrdup(name); } memcpy(&in.s_addr, *(hp->h_addr_list), sizeof(in.s_addr)); return estrdup(inet_ntoa(in)); } /* }}} */ #if HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32) # define PHP_DNS_NUM_TYPES 12 /* Number of DNS Types Supported by PHP currently */ # define PHP_DNS_A 0x00000001 # define PHP_DNS_NS 0x00000002 # define PHP_DNS_CNAME 0x00000010 # define PHP_DNS_SOA 0x00000020 # define PHP_DNS_PTR 0x00000800 # define PHP_DNS_HINFO 0x00001000 # define PHP_DNS_MX 0x00004000 # define PHP_DNS_TXT 0x00008000 # define PHP_DNS_A6 0x01000000 # define PHP_DNS_SRV 0x02000000 # define PHP_DNS_NAPTR 0x04000000 # define PHP_DNS_AAAA 0x08000000 # define PHP_DNS_ANY 0x10000000 # define PHP_DNS_ALL (PHP_DNS_A|PHP_DNS_NS|PHP_DNS_CNAME|PHP_DNS_SOA|PHP_DNS_PTR|PHP_DNS_HINFO|PHP_DNS_MX|PHP_DNS_TXT|PHP_DNS_A6|PHP_DNS_SRV|PHP_DNS_NAPTR|PHP_DNS_AAAA) #endif /* HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32) */ /* Note: These functions are defined in ext/standard/dns_win32.c for Windows! */ #if !defined(PHP_WIN32) && (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) #ifndef HFIXEDSZ #define HFIXEDSZ 12 /* fixed data in header <arpa/nameser.h> */ #endif /* HFIXEDSZ */ #ifndef QFIXEDSZ #define QFIXEDSZ 4 /* fixed data in query <arpa/nameser.h> */ #endif /* QFIXEDSZ */ #undef MAXHOSTNAMELEN #define MAXHOSTNAMELEN 1024 #ifndef MAXRESOURCERECORDS #define MAXRESOURCERECORDS 64 #endif /* MAXRESOURCERECORDS */ typedef union { HEADER qb1; u_char qb2[65536]; } querybuf; /* just a hack to free resources allocated by glibc in __res_nsend() * See also: * res_thread_freeres() in glibc/resolv/res_init.c * __libc_res_nsend() in resolv/res_send.c * */ #if defined(__GLIBC__) && !defined(HAVE_DEPRECATED_DNS_FUNCS) #define php_dns_free_res(__res__) _php_dns_free_res(__res__) static void _php_dns_free_res(struct __res_state res) { /* {{{ */ int ns; for (ns = 0; ns < MAXNS; ns++) { if (res._u._ext.nsaddrs[ns] != NULL) { free (res._u._ext.nsaddrs[ns]); res._u._ext.nsaddrs[ns] = NULL; } } } /* }}} */ #else #define php_dns_free_res(__res__) #endif /* {{{ proto bool dns_check_record(string host [, string type]) Check DNS records corresponding to a given Internet host name or IP address */ PHP_FUNCTION(dns_check_record) { #ifndef MAXPACKET #define MAXPACKET 8192 /* max packet size used internally by BIND */ #endif u_char ans[MAXPACKET]; char *hostname, *rectype = NULL; int hostname_len, rectype_len = 0; int type = T_MX, i; #if defined(HAVE_DNS_SEARCH) struct sockaddr_storage from; uint32_t fromsize = sizeof(from); dns_handle_t handle; #elif defined(HAVE_RES_NSEARCH) struct __res_state state; struct __res_state *handle = &state; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &hostname, &hostname_len, &rectype, &rectype_len) == FAILURE) { return; } if (hostname_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Host cannot be empty"); RETURN_FALSE; } if (rectype) { if (!strcasecmp("A", rectype)) type = T_A; else if (!strcasecmp("NS", rectype)) type = DNS_T_NS; else if (!strcasecmp("MX", rectype)) type = DNS_T_MX; else if (!strcasecmp("PTR", rectype)) type = DNS_T_PTR; else if (!strcasecmp("ANY", rectype)) type = DNS_T_ANY; else if (!strcasecmp("SOA", rectype)) type = DNS_T_SOA; else if (!strcasecmp("TXT", rectype)) type = DNS_T_TXT; else if (!strcasecmp("CNAME", rectype)) type = DNS_T_CNAME; else if (!strcasecmp("AAAA", rectype)) type = DNS_T_AAAA; else if (!strcasecmp("SRV", rectype)) type = DNS_T_SRV; else if (!strcasecmp("NAPTR", rectype)) type = DNS_T_NAPTR; else if (!strcasecmp("A6", rectype)) type = DNS_T_A6; else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Type '%s' not supported", rectype); RETURN_FALSE; } } #if defined(HAVE_DNS_SEARCH) handle = dns_open(NULL); if (handle == NULL) { RETURN_FALSE; } #elif defined(HAVE_RES_NSEARCH) memset(&state, 0, sizeof(state)); if (res_ninit(handle)) { RETURN_FALSE; } #else res_init(); #endif RETVAL_TRUE; i = php_dns_search(handle, hostname, C_IN, type, ans, sizeof(ans)); if (i < 0) { RETVAL_FALSE; } php_dns_free_handle(handle); } /* }}} */ #if HAVE_FULL_DNS_FUNCS /* {{{ php_parserr */ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int store, int raw, zval **subarray) { u_short type, class, dlen; u_long ttl; long n, i; u_short s; u_char *tp, *p; char name[MAXHOSTNAMELEN]; int have_v6_break = 0, in_v6_break = 0; *subarray = NULL; n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, sizeof(name) - 2); if (n < 0) { return NULL; } cp += n; GETSHORT(type, cp); GETSHORT(class, cp); GETLONG(ttl, cp); GETSHORT(dlen, cp); if (type_to_fetch != T_ANY && type != type_to_fetch) { cp += dlen; return cp; } if (!store) { cp += dlen; return cp; } ALLOC_INIT_ZVAL(*subarray); array_init(*subarray); add_assoc_string(*subarray, "host", name, 1); add_assoc_string(*subarray, "class", "IN", 1); add_assoc_long(*subarray, "ttl", ttl); if (raw) { add_assoc_long(*subarray, "type", type); add_assoc_stringl(*subarray, "data", (char*) cp, (uint) dlen, 1); cp += dlen; return cp; } switch (type) { case DNS_T_A: add_assoc_string(*subarray, "type", "A", 1); snprintf(name, sizeof(name), "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]); add_assoc_string(*subarray, "ip", name, 1); cp += dlen; break; case DNS_T_MX: add_assoc_string(*subarray, "type", "MX", 1); GETSHORT(n, cp); add_assoc_long(*subarray, "pri", n); /* no break; */ case DNS_T_CNAME: if (type == DNS_T_CNAME) { add_assoc_string(*subarray, "type", "CNAME", 1); } /* no break; */ case DNS_T_NS: if (type == DNS_T_NS) { add_assoc_string(*subarray, "type", "NS", 1); } /* no break; */ case DNS_T_PTR: if (type == DNS_T_PTR) { add_assoc_string(*subarray, "type", "PTR", 1); } n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "target", name, 1); break; case DNS_T_HINFO: /* See RFC 1010 for values */ add_assoc_string(*subarray, "type", "HINFO", 1); n = *cp & 0xFF; cp++; add_assoc_stringl(*subarray, "cpu", (char*)cp, n, 1); cp += n; n = *cp & 0xFF; cp++; add_assoc_stringl(*subarray, "os", (char*)cp, n, 1); cp += n; break; case DNS_T_TXT: { int ll = 0; zval *entries = NULL; add_assoc_string(*subarray, "type", "TXT", 1); tp = emalloc(dlen + 1); MAKE_STD_ZVAL(entries); array_init(entries); while (ll < dlen) { n = cp[ll]; if ((ll + n) >= dlen) { // Invalid chunk length, truncate n = dlen - (ll + 1); } memcpy(tp + ll , cp + ll + 1, n); add_next_index_stringl(entries, cp + ll + 1, n, 1); ll = ll + n + 1; } tp[dlen] = '\0'; cp += dlen; add_assoc_stringl(*subarray, "txt", tp, (dlen>0)?dlen - 1:0, 0); add_assoc_zval(*subarray, "entries", entries); } break; case DNS_T_SOA: add_assoc_string(*subarray, "type", "SOA", 1); n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "mname", name, 1); n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "rname", name, 1); GETLONG(n, cp); add_assoc_long(*subarray, "serial", n); GETLONG(n, cp); add_assoc_long(*subarray, "refresh", n); GETLONG(n, cp); add_assoc_long(*subarray, "retry", n); GETLONG(n, cp); add_assoc_long(*subarray, "expire", n); GETLONG(n, cp); add_assoc_long(*subarray, "minimum-ttl", n); break; case DNS_T_AAAA: tp = (u_char*)name; for(i=0; i < 8; i++) { GETSHORT(s, cp); if (s != 0) { if (tp > (u_char *)name) { in_v6_break = 0; tp[0] = ':'; tp++; } tp += sprintf((char*)tp,"%x",s); } else { if (!have_v6_break) { have_v6_break = 1; in_v6_break = 1; tp[0] = ':'; tp++; } else if (!in_v6_break) { tp[0] = ':'; tp++; tp[0] = '0'; tp++; } } } if (have_v6_break && in_v6_break) { tp[0] = ':'; tp++; } tp[0] = '\0'; add_assoc_string(*subarray, "type", "AAAA", 1); add_assoc_string(*subarray, "ipv6", name, 1); break; case DNS_T_A6: p = cp; add_assoc_string(*subarray, "type", "A6", 1); n = ((int)cp[0]) & 0xFF; cp++; add_assoc_long(*subarray, "masklen", n); tp = (u_char*)name; if (n > 15) { have_v6_break = 1; in_v6_break = 1; tp[0] = ':'; tp++; } if (n % 16 > 8) { /* Partial short */ if (cp[0] != 0) { if (tp > (u_char *)name) { in_v6_break = 0; tp[0] = ':'; tp++; } sprintf((char*)tp, "%x", cp[0] & 0xFF); } else { if (!have_v6_break) { have_v6_break = 1; in_v6_break = 1; tp[0] = ':'; tp++; } else if (!in_v6_break) { tp[0] = ':'; tp++; tp[0] = '0'; tp++; } } cp++; } for (i = (n + 8) / 16; i < 8; i++) { GETSHORT(s, cp); if (s != 0) { if (tp > (u_char *)name) { in_v6_break = 0; tp[0] = ':'; tp++; } tp += sprintf((char*)tp,"%x",s); } else { if (!have_v6_break) { have_v6_break = 1; in_v6_break = 1; tp[0] = ':'; tp++; } else if (!in_v6_break) { tp[0] = ':'; tp++; tp[0] = '0'; tp++; } } } if (have_v6_break && in_v6_break) { tp[0] = ':'; tp++; } tp[0] = '\0'; add_assoc_string(*subarray, "ipv6", name, 1); if (cp < p + dlen) { n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "chain", name, 1); } break; case DNS_T_SRV: add_assoc_string(*subarray, "type", "SRV", 1); GETSHORT(n, cp); add_assoc_long(*subarray, "pri", n); GETSHORT(n, cp); add_assoc_long(*subarray, "weight", n); GETSHORT(n, cp); add_assoc_long(*subarray, "port", n); n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "target", name, 1); break; case DNS_T_NAPTR: add_assoc_string(*subarray, "type", "NAPTR", 1); GETSHORT(n, cp); add_assoc_long(*subarray, "order", n); GETSHORT(n, cp); add_assoc_long(*subarray, "pref", n); n = (cp[0] & 0xFF); add_assoc_stringl(*subarray, "flags", (char*)++cp, n, 1); cp += n; n = (cp[0] & 0xFF); add_assoc_stringl(*subarray, "services", (char*)++cp, n, 1); cp += n; n = (cp[0] & 0xFF); add_assoc_stringl(*subarray, "regex", (char*)++cp, n, 1); cp += n; n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "replacement", name, 1); break; default: zval_ptr_dtor(subarray); *subarray = NULL; cp += dlen; break; } return cp; } /* }}} */ /* {{{ proto array|false dns_get_record(string hostname [, int type[, array authns, array addtl]]) Get any Resource Record corresponding to a given Internet host name */ PHP_FUNCTION(dns_get_record) { char *hostname; int hostname_len; long type_param = PHP_DNS_ANY; zval *authns = NULL, *addtl = NULL; int type_to_fetch; #if defined(HAVE_DNS_SEARCH) struct sockaddr_storage from; uint32_t fromsize = sizeof(from); dns_handle_t handle; #elif defined(HAVE_RES_NSEARCH) struct __res_state state; struct __res_state *handle = &state; #endif HEADER *hp; querybuf answer; u_char *cp = NULL, *end = NULL; int n, qd, an, ns = 0, ar = 0; int type, first_query = 1, store_results = 1; zend_bool raw = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz!z!b", &hostname, &hostname_len, &type_param, &authns, &addtl, &raw) == FAILURE) { return; } if (authns) { zval_dtor(authns); array_init(authns); } if (addtl) { zval_dtor(addtl); array_init(addtl); } if (!raw) { if ((type_param & ~PHP_DNS_ALL) && (type_param != PHP_DNS_ANY)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Type '%ld' not supported", type_param); RETURN_FALSE; } } else { if ((type_param < 1) || (type_param > 0xFFFF)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Numeric DNS record type must be between 1 and 65535, '%ld' given", type_param); RETURN_FALSE; } } /* Initialize the return array */ array_init(return_value); /* - We emulate an or'ed type mask by querying type by type. (Steps 0 - NUMTYPES-1 ) * If additional info is wanted we check again with DNS_T_ANY (step NUMTYPES / NUMTYPES+1 ) * store_results is used to skip storing the results retrieved in step * NUMTYPES+1 when results were already fetched. * - In case of PHP_DNS_ANY we use the directly fetch DNS_T_ANY. (step NUMTYPES+1 ) * - In case of raw mode, we query only the requestd type instead of looping type by type * before going with the additional info stuff. */ if (raw) { type = -1; } else if (type_param == PHP_DNS_ANY) { type = PHP_DNS_NUM_TYPES + 1; } else { type = 0; } for ( ; type < (addtl ? (PHP_DNS_NUM_TYPES + 2) : PHP_DNS_NUM_TYPES) || first_query; type++ ) { first_query = 0; switch (type) { case -1: /* raw */ type_to_fetch = type_param; /* skip over the rest and go directly to additional records */ type = PHP_DNS_NUM_TYPES - 1; break; case 0: type_to_fetch = type_param&PHP_DNS_A ? DNS_T_A : 0; break; case 1: type_to_fetch = type_param&PHP_DNS_NS ? DNS_T_NS : 0; break; case 2: type_to_fetch = type_param&PHP_DNS_CNAME ? DNS_T_CNAME : 0; break; case 3: type_to_fetch = type_param&PHP_DNS_SOA ? DNS_T_SOA : 0; break; case 4: type_to_fetch = type_param&PHP_DNS_PTR ? DNS_T_PTR : 0; break; case 5: type_to_fetch = type_param&PHP_DNS_HINFO ? DNS_T_HINFO : 0; break; case 6: type_to_fetch = type_param&PHP_DNS_MX ? DNS_T_MX : 0; break; case 7: type_to_fetch = type_param&PHP_DNS_TXT ? DNS_T_TXT : 0; break; case 8: type_to_fetch = type_param&PHP_DNS_AAAA ? DNS_T_AAAA : 0; break; case 9: type_to_fetch = type_param&PHP_DNS_SRV ? DNS_T_SRV : 0; break; case 10: type_to_fetch = type_param&PHP_DNS_NAPTR ? DNS_T_NAPTR : 0; break; case 11: type_to_fetch = type_param&PHP_DNS_A6 ? DNS_T_A6 : 0; break; case PHP_DNS_NUM_TYPES: store_results = 0; continue; default: case (PHP_DNS_NUM_TYPES + 1): type_to_fetch = DNS_T_ANY; break; } if (type_to_fetch) { #if defined(HAVE_DNS_SEARCH) handle = dns_open(NULL); if (handle == NULL) { zval_dtor(return_value); RETURN_FALSE; } #elif defined(HAVE_RES_NSEARCH) memset(&state, 0, sizeof(state)); if (res_ninit(handle)) { zval_dtor(return_value); RETURN_FALSE; } #else res_init(); #endif n = php_dns_search(handle, hostname, C_IN, type_to_fetch, answer.qb2, sizeof answer); if (n < 0) { php_dns_free_handle(handle); continue; } cp = answer.qb2 + HFIXEDSZ; end = answer.qb2 + n; hp = (HEADER *)&answer; qd = ntohs(hp->qdcount); an = ntohs(hp->ancount); ns = ntohs(hp->nscount); ar = ntohs(hp->arcount); /* Skip QD entries, they're only used by dn_expand later on */ while (qd-- > 0) { n = dn_skipname(cp, end); if (n < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to parse DNS data received"); zval_dtor(return_value); php_dns_free_handle(handle); RETURN_FALSE; } cp += n + QFIXEDSZ; } /* YAY! Our real answers! */ while (an-- && cp && cp < end) { zval *retval; cp = php_parserr(cp, &answer, type_to_fetch, store_results, raw, &retval); if (retval != NULL && store_results) { add_next_index_zval(return_value, retval); } } if (authns || addtl) { /* List of Authoritative Name Servers * Process when only requesting addtl so that we can skip through the section */ while (ns-- > 0 && cp && cp < end) { zval *retval = NULL; cp = php_parserr(cp, &answer, DNS_T_ANY, authns != NULL, raw, &retval); if (retval != NULL) { add_next_index_zval(authns, retval); } } } if (addtl) { /* Additional records associated with authoritative name servers */ while (ar-- > 0 && cp && cp < end) { zval *retval = NULL; cp = php_parserr(cp, &answer, DNS_T_ANY, 1, raw, &retval); if (retval != NULL) { add_next_index_zval(addtl, retval); } } } php_dns_free_handle(handle); } } } /* }}} */ /* {{{ proto bool dns_get_mx(string hostname, array mxhosts [, array weight]) Get MX records corresponding to a given Internet host name */ PHP_FUNCTION(dns_get_mx) { char *hostname; int hostname_len; zval *mx_list, *weight_list = NULL; int count, qdc; u_short type, weight; u_char ans[MAXPACKET]; char buf[MAXHOSTNAMELEN]; HEADER *hp; u_char *cp, *end; int i; #if defined(HAVE_DNS_SEARCH) struct sockaddr_storage from; uint32_t fromsize = sizeof(from); dns_handle_t handle; #elif defined(HAVE_RES_NSEARCH) struct __res_state state; struct __res_state *handle = &state; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|z", &hostname, &hostname_len, &mx_list, &weight_list) == FAILURE) { return; } zval_dtor(mx_list); array_init(mx_list); if (weight_list) { zval_dtor(weight_list); array_init(weight_list); } #if defined(HAVE_DNS_SEARCH) handle = dns_open(NULL); if (handle == NULL) { RETURN_FALSE; } #elif defined(HAVE_RES_NSEARCH) memset(&state, 0, sizeof(state)); if (res_ninit(handle)) { RETURN_FALSE; } #else res_init(); #endif i = php_dns_search(handle, hostname, C_IN, DNS_T_MX, (u_char *)&ans, sizeof(ans)); if (i < 0) { RETURN_FALSE; } if (i > (int)sizeof(ans)) { i = sizeof(ans); } hp = (HEADER *)&ans; cp = (u_char *)&ans + HFIXEDSZ; end = (u_char *)&ans +i; for (qdc = ntohs((unsigned short)hp->qdcount); qdc--; cp += i + QFIXEDSZ) { if ((i = dn_skipname(cp, end)) < 0 ) { php_dns_free_handle(handle); RETURN_FALSE; } } count = ntohs((unsigned short)hp->ancount); while (--count >= 0 && cp < end) { if ((i = dn_skipname(cp, end)) < 0 ) { php_dns_free_handle(handle); RETURN_FALSE; } cp += i; GETSHORT(type, cp); cp += INT16SZ + INT32SZ; GETSHORT(i, cp); if (type != DNS_T_MX) { cp += i; continue; } GETSHORT(weight, cp); if ((i = dn_expand(ans, end, cp, buf, sizeof(buf)-1)) < 0) { php_dns_free_handle(handle); RETURN_FALSE; } cp += i; add_next_index_string(mx_list, buf, 1); if (weight_list) { add_next_index_long(weight_list, weight); } } php_dns_free_handle(handle); RETURN_TRUE; } /* }}} */ #endif /* HAVE_FULL_DNS_FUNCS */ #endif /* !defined(PHP_WIN32) && (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) */ #if HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32) PHP_MINIT_FUNCTION(dns) { REGISTER_LONG_CONSTANT("DNS_A", PHP_DNS_A, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_NS", PHP_DNS_NS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_CNAME", PHP_DNS_CNAME, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_SOA", PHP_DNS_SOA, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_PTR", PHP_DNS_PTR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_HINFO", PHP_DNS_HINFO, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_MX", PHP_DNS_MX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_TXT", PHP_DNS_TXT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_SRV", PHP_DNS_SRV, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_NAPTR", PHP_DNS_NAPTR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_AAAA", PHP_DNS_AAAA, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_A6", PHP_DNS_A6, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_ANY", PHP_DNS_ANY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_ALL", PHP_DNS_ALL, CONST_CS | CONST_PERSISTENT); return SUCCESS; } #endif /* HAVE_FULL_DNS_FUNCS */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-119/c/good_2192_0
crossvul-cpp_data_bad_1050_3
/* Copyright (C) 2002-2012 by George Williams */ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <fontforge-config.h> #if !defined(_NO_FFSCRIPT) || !defined(_NO_PYTHON) #include "cvundoes.h" #include "fontforgeui.h" #include "gfile.h" #include "gkeysym.h" #include "gresource.h" #include "scriptfuncs.h" #include "scripting.h" #include "ustring.h" #include "utype.h" struct sd_data { int done; FontView *fv; SplineChar *sc; int layer; GWindow gw; int oldh; }; #define SD_Width 250 #define SD_Height 270 #define CID_Script 1001 #define CID_Box 1002 #define CID_OK 1003 #define CID_Call 1004 #define CID_Cancel 1005 #define CID_Python 1006 #define CID_FF 1007 static int SD_Call(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { char *fn; unichar_t *insert; fn = gwwv_open_filename(_("Call Script"), NULL, "*",NULL); if ( fn==NULL ) return(true); insert = malloc((strlen(fn)+10)*sizeof(unichar_t)); *insert = '"'; utf82u_strcpy(insert+1,fn); uc_strcat(insert,"\"()"); GTextFieldReplace(GWidgetGetControl(GGadgetGetWindow(g),CID_Script),insert); free(insert); free(fn); } return( true ); } #if !defined(_NO_FFSCRIPT) static void ExecNative(GGadget *g, GEvent *e) { struct sd_data *sd = GDrawGetUserData(GGadgetGetWindow(g)); Context c; Val args[1]; jmp_buf env; memset( &c,0,sizeof(c)); memset( args,0,sizeof(args)); running_script = true; c.a.argc = 1; c.a.vals = args; c.filename = args[0].u.sval = "ScriptDlg"; args[0].type = v_str; c.return_val.type = v_void; c.err_env = &env; c.curfv = (FontViewBase *) sd->fv; if ( setjmp(env)!=0 ) { running_script = false; return; /* Error return */ } c.script = GFileTmpfile(); if ( c.script==NULL ) ScriptError(&c, "Can't create temporary file"); else { const unichar_t *ret = _GGadgetGetTitle(GWidgetGetControl(sd->gw,CID_Script)); while ( *ret ) { /* There's a bug here. Filenames need to be converted to the local charset !!!! */ putc(*ret,c.script); ++ret; } rewind(c.script); ff_VerboseCheck(); c.lineno = 1; while ( !c.returned && !c.broken && ff_NextToken(&c)!=tt_eof ) { ff_backuptok(&c); ff_statement(&c); } fclose(c.script); sd->done = true; } running_script = false; } #endif #if !defined(_NO_PYTHON) static void ExecPython(GGadget *g, GEvent *e) { struct sd_data *sd = GDrawGetUserData(GGadgetGetWindow(g)); char *str; running_script = true; str = GGadgetGetTitle8(GWidgetGetControl(sd->gw,CID_Script)); PyFF_ScriptString((FontViewBase *) sd->fv,sd->sc,sd->layer,str); free(str); running_script = false; } #endif #if !defined(_NO_FFSCRIPT) && !defined(_NO_PYTHON) static void _SD_LangChanged(struct sd_data *sd) { GGadgetSetEnabled(GWidgetGetControl(sd->gw,CID_Call), !GGadgetIsChecked(GWidgetGetControl(sd->gw,CID_Python))); } static int SD_LangChanged(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_radiochanged ) { struct sd_data *sd = GDrawGetUserData(GGadgetGetWindow(g)); _SD_LangChanged(sd); } return( true ); } #endif static int SD_OK(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct sd_data *sd = GDrawGetUserData(GGadgetGetWindow(g)); #if !defined(_NO_FFSCRIPT) && !defined(_NO_PYTHON) if ( GGadgetIsChecked(GWidgetGetControl(GGadgetGetWindow(g),CID_Python)) ) ExecPython(g,e); else ExecNative(g,e); #elif !defined(_NO_PYTHON) ExecPython(g,e); #elif !defined(_NO_FFSCRIPT) ExecNative(g,e); #endif sd->done = true; } return( true ); } static void SD_DoCancel(struct sd_data *sd) { sd->done = true; } static int SD_Cancel(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { SD_DoCancel( GDrawGetUserData(GGadgetGetWindow(g))); } return( true ); } static int sd_e_h(GWindow gw, GEvent *event) { struct sd_data *sd = GDrawGetUserData(gw); if ( sd==NULL ) return( true ); if ( event->type==et_close ) { SD_DoCancel( sd ); } else if ( event->type==et_char ) { if ( event->u.chr.keysym == GK_F1 || event->u.chr.keysym == GK_Help ) { help("scripting.html"); return( true ); } return( false ); } else if ( event->type == et_map ) /* Above palettes */ GDrawRaise(gw); else if ( event->type == et_resize ) GDrawRequestExpose(gw,NULL,false); return( true ); } void ScriptDlg(FontView *fv,CharView *cv) { GRect pos; static GWindow gw; GWindowAttrs wattrs; GGadgetCreateData gcd[12], boxes[5], *barray[4][8], *hvarray[4][2]; #if !defined(_NO_FFSCRIPT) && !defined(_NO_PYTHON) GGadgetCreateData *rarray[4]; #endif GTextInfo label[12]; struct sd_data sd; FontView *list; int i,l; memset(&sd,0,sizeof(sd)); sd.fv = fv; sd.sc = cv==NULL ? NULL : cv->b.sc; sd.layer = cv==NULL ? ly_fore : CVLayer((CharViewBase *) cv); sd.oldh = pos.height = GDrawPointsToPixels(NULL,SD_Height); if ( gw==NULL ) { memset(&wattrs,0,sizeof(wattrs)); wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_restrict|wam_isdlg; wattrs.event_masks = ~(1<<et_charup); wattrs.restrict_input_to_me = 1; wattrs.undercursor = 1; wattrs.cursor = ct_pointer; wattrs.utf8_window_title = _("Execute Script"); wattrs.is_dlg = true; pos.x = pos.y = 0; pos.width = GDrawPointsToPixels(NULL,GGadgetScale(SD_Width)); gw = GDrawCreateTopWindow(NULL,&pos,sd_e_h,&sd,&wattrs); memset(&boxes,0,sizeof(boxes)); memset(&gcd,0,sizeof(gcd)); memset(&label,0,sizeof(label)); i = l = 0; gcd[i].gd.pos.x = 10; gcd[i].gd.pos.y = 10; gcd[i].gd.pos.width = SD_Width-20; gcd[i].gd.pos.height = SD_Height-54; gcd[i].gd.flags = gg_visible | gg_enabled | gg_textarea_wrap; gcd[i].gd.cid = CID_Script; gcd[i++].creator = GTextAreaCreate; hvarray[l][0] = &gcd[i-1]; hvarray[l++][1] = NULL; #if !defined(_NO_FFSCRIPT) && !defined(_NO_PYTHON) gcd[i-1].gd.pos.height -= 24; gcd[i].gd.pos.x = 10; gcd[i].gd.pos.y = gcd[i-1].gd.pos.y+gcd[i-1].gd.pos.height+1; gcd[i].gd.flags = gg_visible | gg_enabled | gg_cb_on; gcd[i].gd.cid = CID_Python; label[i].text = (unichar_t *) _("_Python"); label[i].text_is_1byte = true; label[i].text_in_resource = true; gcd[i].gd.label = &label[i]; gcd[i].gd.handle_controlevent = SD_LangChanged; gcd[i++].creator = GRadioCreate; rarray[0] = &gcd[i-1]; gcd[i].gd.pos.x = 70; gcd[i].gd.pos.y = gcd[i-1].gd.pos.y; gcd[i].gd.flags = gg_visible | gg_enabled; /* disabled if cv!=NULL later */ gcd[i].gd.cid = CID_FF; label[i].text = (unichar_t *) _("_FF"); label[i].text_is_1byte = true; label[i].text_in_resource = true; gcd[i].gd.label = &label[i]; gcd[i].gd.handle_controlevent = SD_LangChanged; gcd[i++].creator = GRadioCreate; rarray[1] = &gcd[i-1]; rarray[2] = GCD_Glue; rarray[3] = NULL; boxes[2].gd.flags = gg_enabled | gg_visible; boxes[2].gd.u.boxelements = rarray; boxes[2].creator = GHBoxCreate; hvarray[l][0] = &boxes[2]; hvarray[l++][1] = NULL; #endif barray[0][0] = barray[1][0] = barray[0][6] = barray[1][6] = GCD_Glue; barray[0][2] = barray[1][2] = barray[0][4] = barray[1][4] = GCD_Glue; barray[0][1] = barray[0][5] = GCD_RowSpan; barray[0][7] = barray[1][7] = barray[2][0] = NULL; gcd[i].gd.pos.x = 25-3; gcd[i].gd.pos.y = SD_Height-32-3; gcd[i].gd.flags = gg_visible | gg_enabled | gg_but_default; label[i].text = (unichar_t *) _("_OK"); label[i].text_is_1byte = true; label[i].text_in_resource = true; gcd[i].gd.mnemonic = 'O'; gcd[i].gd.label = &label[i]; gcd[i].gd.handle_controlevent = SD_OK; gcd[i].gd.cid = CID_OK; gcd[i++].creator = GButtonCreate; barray[1][1] = &gcd[i-1]; gcd[i].gd.pos.x = -25; gcd[i].gd.pos.y = SD_Height-32; gcd[i].gd.flags = gg_visible | gg_enabled | gg_but_cancel; label[i].text = (unichar_t *) _("_Cancel"); label[i].text_is_1byte = true; label[i].text_in_resource = true; gcd[i].gd.label = &label[i]; gcd[i].gd.mnemonic = 'C'; gcd[i].gd.handle_controlevent = SD_Cancel; gcd[i].gd.cid = CID_Cancel; gcd[i++].creator = GButtonCreate; barray[1][5] = &gcd[i-1]; gcd[i].gd.pos.x = (SD_Width-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor))/2; gcd[i].gd.pos.y = SD_Height-40; gcd[i].gd.flags = gg_visible | gg_enabled; label[i].text = (unichar_t *) _("C_all..."); label[i].text_is_1byte = true; label[i].text_in_resource = true; gcd[i].gd.label = &label[i]; gcd[i].gd.mnemonic = 'a'; gcd[i].gd.handle_controlevent = SD_Call; gcd[i].gd.cid = CID_Call; gcd[i++].creator = GButtonCreate; barray[0][3] = &gcd[i-1]; #if !defined(_NO_FFSCRIPT) gcd[i].gd.pos.width = gcd[i].gd.pos.height = 5; gcd[i].gd.flags = gg_visible | gg_enabled; gcd[i++].creator = GSpacerCreate; barray[1][3] = &gcd[i-1]; #else barray[1][3] = GCD_RowSpan; #endif barray[3][0] = NULL; boxes[3].gd.flags = gg_enabled | gg_visible; boxes[3].gd.u.boxelements = barray[0]; boxes[3].creator = GHVBoxCreate; hvarray[l][0] = &boxes[3]; hvarray[l++][1] = NULL; hvarray[l][0] = NULL; boxes[0].gd.pos.x = boxes[0].gd.pos.y = 2; boxes[0].gd.flags = gg_enabled | gg_visible; boxes[0].gd.u.boxelements = hvarray[0]; boxes[0].creator = GHVGroupCreate; GGadgetsCreate(gw,boxes); if ( boxes[2].ret!=NULL ) GHVBoxSetExpandableCol(boxes[2].ret,gb_expandglue); GHVBoxSetExpandableCol(boxes[3].ret,gb_expandgluesame); GHVBoxSetExpandableRow(boxes[0].ret,0); GHVBoxFitWindow(boxes[0].ret); } #if !defined(_NO_FFSCRIPT) && !defined(_NO_PYTHON) GGadgetSetEnabled(GWidgetGetControl(gw,CID_FF),cv==NULL); #endif sd.gw = gw; GDrawSetUserData(gw,&sd); GWidgetIndicateFocusGadget(GWidgetGetControl(gw,CID_Script)); #if !defined(_NO_FFSCRIPT) && !defined(_NO_PYTHON) _SD_LangChanged(&sd); #endif GDrawSetVisible(gw,true); while ( !sd.done ) GDrawProcessOneEvent(NULL); GDrawSetVisible(gw,false); /* Selection may be out of date, force a refresh */ for ( list = fv_list; list!=NULL; list=(FontView *) list->b.next ) GDrawRequestExpose(list->v,NULL,false); GDrawSync(NULL); GDrawProcessPendingEvents(NULL); GDrawSetUserData(gw,NULL); } #endif /* No scripting */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_1050_3
crossvul-cpp_data_bad_2553_0
/* libhttpd.c - HTTP protocol library ** ** Copyright � 1995,1998,1999,2000,2001 by Jef Poskanzer <jef@mail.acme.com>. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE ** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT ** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY ** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF ** SUCH DAMAGE. */ #include <config.h> //system headers #include <sys/types.h> #include <sys/param.h> #include <sys/stat.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #ifdef HAVE_MEMORY_H #include <memory.h> #endif /* HAVE_MEMORY_H */ #include <pwd.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <syslog.h> #include <unistd.h> #include <stdarg.h> #ifdef HAVE_OSRELDATE_H #include <osreldate.h> #endif /* HAVE_OSRELDATE_H */ #ifdef HAVE_DIRENT_H # include <dirent.h> # define NAMLEN(dirent) strlen((dirent)->d_name) #else # define dirent direct # define NAMLEN(dirent) (dirent)->d_namlen # ifdef HAVE_SYS_NDIR_H # include <sys/ndir.h> # endif # ifdef HAVE_SYS_DIR_H # include <sys/dir.h> # endif # ifdef HAVE_NDIR_H # include <ndir.h> # endif #endif extern char* crypt( const char* key, const char* setting ); //local headers #include <libhttpd.h> #include <match.h> #include <mmc.h> #include <tdate_parse.h> #include <thttpd.h> #include <timers.h> #include <version.h> #ifdef SHOW_SERVER_VERSION #define EXPOSED_SERVER_SOFTWARE SERVER_SOFTWARE #else /* SHOW_SERVER_VERSION */ #define EXPOSED_SERVER_SOFTWARE "sthttpd" #endif /* SHOW_SERVER_VERSION */ #ifndef STDIN_FILENO #define STDIN_FILENO 0 #endif #ifndef STDOUT_FILENO #define STDOUT_FILENO 1 #endif #ifndef STDERR_FILENO #define STDERR_FILENO 2 #endif #ifndef SHUT_WR #define SHUT_WR 1 #endif #ifdef __CYGWIN__ #define timezone _timezone #endif #ifndef MAX #define MAX(a,b) ((a) > (b) ? (a) : (b)) #endif #ifndef MIN #define MIN(a,b) ((a) < (b) ? (a) : (b)) #endif /* Forwards. */ static void check_options( void ); static void free_httpd_server( httpd_server* hs ); static int initialize_listen_socket( httpd_sockaddr* saP ); static void add_response( httpd_conn* hc, char* str ); static void send_mime( httpd_conn* hc, int status, char* title, char* encodings, char* extraheads, char* type, off_t length, time_t mod ); static void send_response( httpd_conn* hc, int status, char* title, char* extraheads, char* form, char* arg ); static void send_response_tail( httpd_conn* hc ); static void defang( char* str, char* dfstr, int dfsize ); #ifdef ERR_DIR static int send_err_file( httpd_conn* hc, int status, char* title, char* extraheads, char* filename ); #endif /* ERR_DIR */ #ifdef AUTH_FILE static void send_authenticate( httpd_conn* hc, char* realm ); static int b64_decode( const char* str, unsigned char* space, int size ); static int auth_check( httpd_conn* hc, char* dirname ); static int auth_check2( httpd_conn* hc, char* dirname ); #endif /* AUTH_FILE */ static void send_dirredirect( httpd_conn* hc ); static int hexit( char c ); static void strdecode( char* to, char* from ); #ifdef GENERATE_INDEXES static void strencode( char* to, int tosize, char* from ); #endif /* GENERATE_INDEXES */ #ifdef TILDE_MAP_1 static int tilde_map_1( httpd_conn* hc ); #endif /* TILDE_MAP_1 */ #ifdef TILDE_MAP_2 static int tilde_map_2( httpd_conn* hc ); #endif /* TILDE_MAP_2 */ static int vhost_map( httpd_conn* hc ); static char* expand_symlinks( char* path, char** restP, int no_symlink_check, int tildemapped ); static char* bufgets( httpd_conn* hc ); static void de_dotdot( char* file ); static void init_mime( void ); static void figure_mime( httpd_conn* hc ); #ifdef CGI_TIMELIMIT static void cgi_kill2( ClientData client_data, struct timeval* nowP ); static void cgi_kill( ClientData client_data, struct timeval* nowP ); #endif /* CGI_TIMELIMIT */ #ifdef GENERATE_INDEXES static int ls( httpd_conn* hc ); #endif /* GENERATE_INDEXES */ static char* build_env( char* fmt, char* arg ); #ifdef SERVER_NAME_LIST static char* hostname_map( char* hostname ); #endif /* SERVER_NAME_LIST */ static char** make_envp( httpd_conn* hc ); static char** make_argp( httpd_conn* hc ); static void cgi_interpose_input( httpd_conn* hc, int wfd ); static void post_post_garbage_hack( httpd_conn* hc ); static void cgi_interpose_output( httpd_conn* hc, int rfd ); static void cgi_child( httpd_conn* hc ); static int cgi( httpd_conn* hc ); static int really_start_request( httpd_conn* hc, struct timeval* nowP ); static void make_log_entry( httpd_conn* hc, struct timeval* nowP ); static int check_referer( httpd_conn* hc ); static int really_check_referer( httpd_conn* hc ); static int sockaddr_check( httpd_sockaddr* saP ); static size_t sockaddr_len( httpd_sockaddr* saP ); static int my_snprintf( char* str, size_t size, const char* format, ... ); #ifndef HAVE_ATOLL static long long atoll( const char* str ); #endif /* HAVE_ATOLL */ /* This global keeps track of whether we are in the main process or a ** sub-process. The reason is that httpd_write_response() can get called ** in either context; when it is called from the main process it must use ** non-blocking I/O to avoid stalling the server, but when it is called ** from a sub-process it wants to use blocking I/O so that the whole ** response definitely gets written. So, it checks this variable. A bit ** of a hack but it seems to do the right thing. */ static int sub_process = 0; static void check_options( void ) { #if defined(TILDE_MAP_1) && defined(TILDE_MAP_2) syslog( LOG_CRIT, "both TILDE_MAP_1 and TILDE_MAP_2 are defined" ); exit( 1 ); #endif /* both */ } static void free_httpd_server( httpd_server* hs ) { free(hs->binding_hostname); free(hs->cwd); free(hs->cgi_pattern); free(hs->charset); free(hs->p3p); free(hs->url_pattern); free(hs->local_pattern); free(hs); } httpd_server* httpd_initialize( char* hostname, httpd_sockaddr* sa4P, httpd_sockaddr* sa6P, unsigned short port, char* cgi_pattern, int cgi_limit, char* charset, char* p3p, int max_age, char* cwd, int no_log, FILE* logfp, int no_symlink_check, int vhost, int global_passwd, char* url_pattern, char* local_pattern, int no_empty_referers ) { httpd_server* hs; static char ghnbuf[256]; char* cp; check_options(); hs = NEW( httpd_server, 1 ); if ( hs == (httpd_server*) 0 ) { syslog( LOG_CRIT, "out of memory allocating an httpd_server" ); return (httpd_server*) 0; } if ( hostname != (char*) 0 ) { hs->binding_hostname = strdup( hostname ); if ( hs->binding_hostname == (char*) 0 ) { syslog( LOG_CRIT, "out of memory copying hostname" ); return (httpd_server*) 0; } hs->server_hostname = hs->binding_hostname; } else { hs->binding_hostname = (char*) 0; hs->server_hostname = (char*) 0; if ( gethostname( ghnbuf, sizeof(ghnbuf) ) < 0 ) ghnbuf[0] = '\0'; #ifdef SERVER_NAME_LIST if ( ghnbuf[0] != '\0' ) hs->server_hostname = hostname_map( ghnbuf ); #endif /* SERVER_NAME_LIST */ if ( hs->server_hostname == (char*) 0 ) { #ifdef SERVER_NAME hs->server_hostname = SERVER_NAME; #else /* SERVER_NAME */ if ( ghnbuf[0] != '\0' ) hs->server_hostname = ghnbuf; #endif /* SERVER_NAME */ } } hs->port = port; if ( cgi_pattern == (char*) 0 ) hs->cgi_pattern = (char*) 0; else { /* Nuke any leading slashes. */ if ( cgi_pattern[0] == '/' ) ++cgi_pattern; hs->cgi_pattern = strdup( cgi_pattern ); if ( hs->cgi_pattern == (char*) 0 ) { syslog( LOG_CRIT, "out of memory copying cgi_pattern" ); return (httpd_server*) 0; } /* Nuke any leading slashes in the cgi pattern. */ while ( ( cp = strstr( hs->cgi_pattern, "|/" ) ) != (char*) 0 ) /* -2 for the offset, +1 for the '\0' */ (void) memmove( cp + 1, cp + 2, strlen( cp ) - 1 ); } hs->cgi_limit = cgi_limit; hs->cgi_count = 0; hs->charset = strdup( charset ); hs->p3p = strdup( p3p ); hs->max_age = max_age; hs->cwd = strdup( cwd ); if ( hs->cwd == (char*) 0 ) { syslog( LOG_CRIT, "out of memory copying cwd" ); return (httpd_server*) 0; } if ( url_pattern == (char*) 0 ) hs->url_pattern = (char*) 0; else { hs->url_pattern = strdup( url_pattern ); if ( hs->url_pattern == (char*) 0 ) { syslog( LOG_CRIT, "out of memory copying url_pattern" ); return (httpd_server*) 0; } } if ( local_pattern == (char*) 0 ) hs->local_pattern = (char*) 0; else { hs->local_pattern = strdup( local_pattern ); if ( hs->local_pattern == (char*) 0 ) { syslog( LOG_CRIT, "out of memory copying local_pattern" ); return (httpd_server*) 0; } } hs->no_log = no_log; hs->logfp = (FILE*) 0; httpd_set_logfp( hs, logfp ); hs->no_symlink_check = no_symlink_check; hs->vhost = vhost; hs->global_passwd = global_passwd; hs->no_empty_referers = no_empty_referers; /* Initialize listen sockets. Try v6 first because of a Linux peculiarity; ** like some other systems, it has magical v6 sockets that also listen for ** v4, but in Linux if you bind a v4 socket first then the v6 bind fails. */ if ( sa6P == (httpd_sockaddr*) 0 ) hs->listen6_fd = -1; else hs->listen6_fd = initialize_listen_socket( sa6P ); if ( sa4P == (httpd_sockaddr*) 0 ) hs->listen4_fd = -1; else hs->listen4_fd = initialize_listen_socket( sa4P ); /* If we didn't get any valid sockets, fail. */ if ( hs->listen4_fd == -1 && hs->listen6_fd == -1 ) { free_httpd_server( hs ); return (httpd_server*) 0; } init_mime(); /* Done initializing. */ if ( hs->binding_hostname == (char*) 0 ) syslog( LOG_NOTICE, "%.80s starting on port %d", SERVER_SOFTWARE, (int) hs->port ); else syslog( LOG_NOTICE, "%.80s starting on %.80s, port %d", SERVER_SOFTWARE, httpd_ntoa( hs->listen4_fd != -1 ? sa4P : sa6P ), (int) hs->port ); return hs; } static int initialize_listen_socket( httpd_sockaddr* saP ) { int listen_fd; int on, flags; /* Check sockaddr. */ if ( ! sockaddr_check( saP ) ) { syslog( LOG_CRIT, "unknown sockaddr family on listen socket" ); return -1; } /* Create socket. */ listen_fd = socket( saP->sa.sa_family, SOCK_STREAM, 0 ); if ( listen_fd < 0 ) { syslog( LOG_CRIT, "socket %.80s - %m", httpd_ntoa( saP ) ); return -1; } (void) fcntl( listen_fd, F_SETFD, 1 ); /* Allow reuse of local addresses. */ on = 1; if ( setsockopt( listen_fd, SOL_SOCKET, SO_REUSEADDR, (char*) &on, sizeof(on) ) < 0 ) syslog( LOG_CRIT, "setsockopt SO_REUSEADDR - %m" ); /* Bind to it. */ if ( bind( listen_fd, &saP->sa, sockaddr_len( saP ) ) < 0 ) { syslog( LOG_CRIT, "bind %.80s - %m", httpd_ntoa( saP ) ); (void) close( listen_fd ); return -1; } /* Set the listen file descriptor to no-delay / non-blocking mode. */ flags = fcntl( listen_fd, F_GETFL, 0 ); if ( flags == -1 ) { syslog( LOG_CRIT, "fcntl F_GETFL - %m" ); (void) close( listen_fd ); return -1; } if ( fcntl( listen_fd, F_SETFL, flags | O_NDELAY ) < 0 ) { syslog( LOG_CRIT, "fcntl O_NDELAY - %m" ); (void) close( listen_fd ); return -1; } /* Start a listen going. */ if ( listen( listen_fd, LISTEN_BACKLOG ) < 0 ) { syslog( LOG_CRIT, "listen - %m" ); (void) close( listen_fd ); return -1; } /* Use accept filtering, if available. */ #ifdef SO_ACCEPTFILTER { #if ( __FreeBSD_version >= 411000 ) #define ACCEPT_FILTER_NAME "httpready" #else #define ACCEPT_FILTER_NAME "dataready" #endif struct accept_filter_arg af; (void) bzero( &af, sizeof(af) ); (void) strcpy( af.af_name, ACCEPT_FILTER_NAME ); (void) setsockopt( listen_fd, SOL_SOCKET, SO_ACCEPTFILTER, (char*) &af, sizeof(af) ); } #endif /* SO_ACCEPTFILTER */ return listen_fd; } void httpd_set_logfp( httpd_server* hs, FILE* logfp ) { if ( hs->logfp != (FILE*) 0 ) (void) fclose( hs->logfp ); hs->logfp = logfp; } void httpd_terminate( httpd_server* hs ) { httpd_unlisten( hs ); if ( hs->logfp != (FILE*) 0 ) (void) fclose( hs->logfp ); free_httpd_server( hs ); } void httpd_unlisten( httpd_server* hs ) { if ( hs->listen4_fd != -1 ) { (void) close( hs->listen4_fd ); hs->listen4_fd = -1; } if ( hs->listen6_fd != -1 ) { (void) close( hs->listen6_fd ); hs->listen6_fd = -1; } } /* Conditional macro to allow two alternate forms for use in the built-in ** error pages. If EXPLICIT_ERROR_PAGES is defined, the second and more ** explicit error form is used; otherwise, the first and more generic ** form is used. */ #ifdef EXPLICIT_ERROR_PAGES #define ERROR_FORM(a,b) b #else /* EXPLICIT_ERROR_PAGES */ #define ERROR_FORM(a,b) a #endif /* EXPLICIT_ERROR_PAGES */ static char* ok200title = "OK"; static char* ok206title = "Partial Content"; static char* err302title = "Found"; static char* err302form = "The actual URL is '%.80s'.\n"; static char* err304title = "Not Modified"; char* httpd_err400title = "Bad Request"; char* httpd_err400form = "Your request has bad syntax or is inherently impossible to satisfy.\n"; #ifdef AUTH_FILE static char* err401title = "Unauthorized"; static char* err401form = "Authorization required for the URL '%.80s'.\n"; #endif /* AUTH_FILE */ static char* err403title = "Forbidden"; #ifndef EXPLICIT_ERROR_PAGES static char* err403form = "You do not have permission to get URL '%.80s' from this server.\n"; #endif /* !EXPLICIT_ERROR_PAGES */ static char* err404title = "Not Found"; static char* err404form = "The requested URL '%.80s' was not found on this server.\n"; char* httpd_err408title = "Request Timeout"; char* httpd_err408form = "No request appeared within a reasonable time period.\n"; static char* err500title = "Internal Error"; static char* err500form = "There was an unusual problem serving the requested URL '%.80s'.\n"; static char* err501title = "Not Implemented"; static char* err501form = "The requested method '%.80s' is not implemented by this server.\n"; char* httpd_err503title = "Service Temporarily Overloaded"; char* httpd_err503form = "The requested URL '%.80s' is temporarily overloaded. Please try again later.\n"; /* Append a string to the buffer waiting to be sent as response. */ static void add_response( httpd_conn* hc, char* str ) { size_t len; len = strlen( str ); httpd_realloc_str( &hc->response, &hc->maxresponse, hc->responselen + len ); (void) memmove( &(hc->response[hc->responselen]), str, len ); hc->responselen += len; } /* Send the buffered response. */ void httpd_write_response( httpd_conn* hc ) { /* If we are in a sub-process, turn off no-delay mode. */ if ( sub_process ) httpd_clear_ndelay( hc->conn_fd ); /* Send the response, if necessary. */ if ( hc->responselen > 0 ) { (void) httpd_write_fully( hc->conn_fd, hc->response, hc->responselen ); hc->responselen = 0; } } /* Set no-delay / non-blocking mode on a socket. */ void httpd_set_ndelay( int fd ) { int flags, newflags; flags = fcntl( fd, F_GETFL, 0 ); if ( flags != -1 ) { newflags = flags | (int) O_NDELAY; if ( newflags != flags ) (void) fcntl( fd, F_SETFL, newflags ); } } /* Clear no-delay / non-blocking mode on a socket. */ void httpd_clear_ndelay( int fd ) { int flags, newflags; flags = fcntl( fd, F_GETFL, 0 ); if ( flags != -1 ) { newflags = flags & ~ (int) O_NDELAY; if ( newflags != flags ) (void) fcntl( fd, F_SETFL, newflags ); } } static void send_mime( httpd_conn* hc, int status, char* title, char* encodings, char* extraheads, char* type, off_t length, time_t mod ) { time_t now, expires; const char* rfc1123fmt = "%a, %d %b %Y %H:%M:%S GMT"; char nowbuf[100]; char modbuf[100]; char expbuf[100]; char fixed_type[500]; char buf[1000]; int partial_content; int s100; hc->status = status; hc->bytes_to_send = length; if ( hc->mime_flag ) { if ( status == 200 && hc->got_range && ( hc->last_byte_index >= hc->first_byte_index ) && ( ( hc->last_byte_index != length - 1 ) || ( hc->first_byte_index != 0 ) ) && ( hc->range_if == (time_t) -1 || hc->range_if == hc->sb.st_mtime ) ) { partial_content = 1; hc->status = status = 206; title = ok206title; } else { partial_content = 0; hc->got_range = 0; } now = time( (time_t*) 0 ); if ( mod == (time_t) 0 ) mod = now; (void) strftime( nowbuf, sizeof(nowbuf), rfc1123fmt, gmtime( &now ) ); (void) strftime( modbuf, sizeof(modbuf), rfc1123fmt, gmtime( &mod ) ); (void) my_snprintf( fixed_type, sizeof(fixed_type), type, hc->hs->charset ); (void) my_snprintf( buf, sizeof(buf), "%.20s %d %s\015\012Server: %s\015\012Content-Type: %s\015\012Date: %s\015\012Last-Modified: %s\015\012Accept-Ranges: bytes\015\012Connection: close\015\012", hc->protocol, status, title, EXPOSED_SERVER_SOFTWARE, fixed_type, nowbuf, modbuf ); add_response( hc, buf ); s100 = status / 100; if ( s100 != 2 && s100 != 3 ) { (void) my_snprintf( buf, sizeof(buf), "Cache-Control: no-cache,no-store\015\012" ); add_response( hc, buf ); } if ( encodings[0] != '\0' ) { (void) my_snprintf( buf, sizeof(buf), "Content-Encoding: %s\015\012", encodings ); add_response( hc, buf ); } if ( partial_content ) { (void) my_snprintf( buf, sizeof(buf), "Content-Range: bytes %lld-%lld/%lld\015\012Content-Length: %lld\015\012", (int64_t) hc->first_byte_index, (int64_t) hc->last_byte_index, (int64_t) length, (int64_t) ( hc->last_byte_index - hc->first_byte_index + 1 ) ); add_response( hc, buf ); } else if ( length >= 0 ) { (void) my_snprintf( buf, sizeof(buf), "Content-Length: %lld\015\012", (int64_t) length ); add_response( hc, buf ); } if ( hc->hs->p3p[0] != '\0' ) { (void) my_snprintf( buf, sizeof(buf), "P3P: %s\015\012", hc->hs->p3p ); add_response( hc, buf ); } if ( hc->hs->max_age >= 0 ) { expires = now + hc->hs->max_age; (void) strftime( expbuf, sizeof(expbuf), rfc1123fmt, gmtime( &expires ) ); (void) my_snprintf( buf, sizeof(buf), "Cache-Control: max-age=%d\015\012Expires: %s\015\012", hc->hs->max_age, expbuf ); add_response( hc, buf ); } if ( extraheads[0] != '\0' ) add_response( hc, extraheads ); add_response( hc, "\015\012" ); } } static int str_alloc_count = 0; static size_t str_alloc_size = 0; void httpd_realloc_str( char** strP, size_t* maxsizeP, size_t size ) { if ( *maxsizeP == 0 ) { *maxsizeP = MAX( 200, size + 100 ); *strP = NEW( char, *maxsizeP + 1 ); ++str_alloc_count; str_alloc_size += *maxsizeP; } else if ( size > *maxsizeP ) { str_alloc_size -= *maxsizeP; *maxsizeP = MAX( *maxsizeP * 2, size * 5 / 4 ); *strP = RENEW( *strP, char, *maxsizeP + 1 ); str_alloc_size += *maxsizeP; } else return; if ( *strP == (char*) 0 ) { syslog( LOG_ERR, "out of memory reallocating a string to %zu bytes", *maxsizeP ); exit( 1 ); } } static void send_response( httpd_conn* hc, int status, char* title, char* extraheads, char* form, char* arg ) { char defanged_arg[1000], buf[2000]; send_mime( hc, status, title, "", extraheads, "text/html; charset=%s", (off_t) -1, (time_t) 0 ); (void) my_snprintf( buf, sizeof(buf), "\ <HTML>\n\ <HEAD><TITLE>%d %s</TITLE></HEAD>\n\ <BODY BGCOLOR=\"#cc9999\" TEXT=\"#000000\" LINK=\"#2020ff\" VLINK=\"#4040cc\">\n\ <H2>%d %s</H2>\n", status, title, status, title ); add_response( hc, buf ); defang( arg, defanged_arg, sizeof(defanged_arg) ); (void) my_snprintf( buf, sizeof(buf), form, defanged_arg ); add_response( hc, buf ); if ( match( "**MSIE**", hc->useragent ) ) { int n; add_response( hc, "<!--\n" ); for ( n = 0; n < 6; ++n ) add_response( hc, "Padding so that MSIE deigns to show this error instead of its own canned one.\n"); add_response( hc, "-->\n" ); } send_response_tail( hc ); } static void send_response_tail( httpd_conn* hc ) { char buf[1000]; (void) my_snprintf( buf, sizeof(buf), "\ <HR>\n\ <ADDRESS><A HREF=\"%s\">%s</A></ADDRESS>\n\ </BODY>\n\ </HTML>\n", SERVER_ADDRESS, EXPOSED_SERVER_SOFTWARE ); add_response( hc, buf ); } static void defang( char* str, char* dfstr, int dfsize ) { char* cp1; char* cp2; for ( cp1 = str, cp2 = dfstr; *cp1 != '\0' && cp2 - dfstr < dfsize - 5; ++cp1, ++cp2 ) { switch ( *cp1 ) { case '<': *cp2++ = '&'; *cp2++ = 'l'; *cp2++ = 't'; *cp2 = ';'; break; case '>': *cp2++ = '&'; *cp2++ = 'g'; *cp2++ = 't'; *cp2 = ';'; break; default: *cp2 = *cp1; break; } } *cp2 = '\0'; } void httpd_send_err( httpd_conn* hc, int status, char* title, char* extraheads, char* form, char* arg ) { #ifdef ERR_DIR char filename[1000]; /* Try virtual host error page. */ if ( hc->hs->vhost && hc->hostdir[0] != '\0' ) { (void) my_snprintf( filename, sizeof(filename), "%s/%s/err%d.html", hc->hostdir, ERR_DIR, status ); if ( send_err_file( hc, status, title, extraheads, filename ) ) return; } /* Try server-wide error page. */ (void) my_snprintf( filename, sizeof(filename), "%s/err%d.html", ERR_DIR, status ); if ( send_err_file( hc, status, title, extraheads, filename ) ) return; /* Fall back on built-in error page. */ send_response( hc, status, title, extraheads, form, arg ); #else /* ERR_DIR */ send_response( hc, status, title, extraheads, form, arg ); #endif /* ERR_DIR */ } #ifdef ERR_DIR static int send_err_file( httpd_conn* hc, int status, char* title, char* extraheads, char* filename ) { FILE* fp; char buf[1000]; size_t r; fp = fopen( filename, "r" ); if ( fp == (FILE*) 0 ) return 0; send_mime( hc, status, title, "", extraheads, "text/html; charset=%s", (off_t) -1, (time_t) 0 ); for (;;) { r = fread( buf, 1, sizeof(buf) - 1, fp ); if ( r == 0 ) break; buf[r] = '\0'; add_response( hc, buf ); } (void) fclose( fp ); #ifdef ERR_APPEND_SERVER_INFO send_response_tail( hc ); #endif /* ERR_APPEND_SERVER_INFO */ return 1; } #endif /* ERR_DIR */ #ifdef AUTH_FILE static void send_authenticate( httpd_conn* hc, char* realm ) { static char* header; static size_t maxheader = 0; static char headstr[] = "WWW-Authenticate: Basic realm=\""; httpd_realloc_str( &header, &maxheader, sizeof(headstr) + strlen( realm ) + 3 ); (void) my_snprintf( header, maxheader, "%s%s\"\015\012", headstr, realm ); httpd_send_err( hc, 401, err401title, header, err401form, hc->encodedurl ); /* If the request was a POST then there might still be data to be read, ** so we need to do a lingering close. */ if ( hc->method == METHOD_POST ) hc->should_linger = 1; } /* Base-64 decoding. This represents binary data as printable ASCII ** characters. Three 8-bit binary bytes are turned into four 6-bit ** values, like so: ** ** [11111111] [22222222] [33333333] ** ** [111111] [112222] [222233] [333333] ** ** Then the 6-bit values are represented using the characters "A-Za-z0-9+/". */ static int b64_decode_table[256] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 00-0F */ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 10-1F */ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, /* 20-2F */ 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, /* 30-3F */ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* 40-4F */ 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, /* 50-5F */ -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, /* 60-6F */ 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, /* 70-7F */ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 80-8F */ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 90-9F */ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* A0-AF */ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* B0-BF */ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* C0-CF */ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* D0-DF */ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* E0-EF */ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 /* F0-FF */ }; /* Do base-64 decoding on a string. Ignore any non-base64 bytes. ** Return the actual number of bytes generated. The decoded size will ** be at most 3/4 the size of the encoded, and may be smaller if there ** are padding characters (blanks, newlines). */ static int b64_decode( const char* str, unsigned char* space, int size ) { const char* cp; int space_idx, phase; int d, prev_d = 0; unsigned char c; space_idx = 0; phase = 0; for ( cp = str; *cp != '\0'; ++cp ) { d = b64_decode_table[(int) *cp]; if ( d != -1 ) { switch ( phase ) { case 0: ++phase; break; case 1: c = ( ( prev_d << 2 ) | ( ( d & 0x30 ) >> 4 ) ); if ( space_idx < size ) space[space_idx++] = c; ++phase; break; case 2: c = ( ( ( prev_d & 0xf ) << 4 ) | ( ( d & 0x3c ) >> 2 ) ); if ( space_idx < size ) space[space_idx++] = c; ++phase; break; case 3: c = ( ( ( prev_d & 0x03 ) << 6 ) | d ); if ( space_idx < size ) space[space_idx++] = c; phase = 0; break; } prev_d = d; } } return space_idx; } /* Returns -1 == unauthorized, 0 == no auth file, 1 = authorized. */ static int auth_check( httpd_conn* hc, char* dirname ) { if ( hc->hs->global_passwd ) { char* topdir; if ( hc->hs->vhost && hc->hostdir[0] != '\0' ) topdir = hc->hostdir; else topdir = "."; switch ( auth_check2( hc, topdir ) ) { case -1: return -1; case 1: return 1; } } return auth_check2( hc, dirname ); } /* Returns -1 == unauthorized, 0 == no auth file, 1 = authorized. */ static int auth_check2( httpd_conn* hc, char* dirname ) { static char* authpath; static size_t maxauthpath = 0; struct stat sb; char authinfo[500]; char* authpass; char* colon; int l; FILE* fp; char line[500]; char* cryp; static char* prevauthpath; static size_t maxprevauthpath = 0; static time_t prevmtime; static char* prevuser; static size_t maxprevuser = 0; static char* prevcryp; static size_t maxprevcryp = 0; char *crypt_result; /* Construct auth filename. */ httpd_realloc_str( &authpath, &maxauthpath, strlen( dirname ) + 1 + sizeof(AUTH_FILE) ); (void) my_snprintf( authpath, maxauthpath, "%s/%s", dirname, AUTH_FILE ); /* Does this directory have an auth file? */ if ( stat( authpath, &sb ) < 0 ) /* Nope, let the request go through. */ return 0; /* Does this request contain basic authorization info? */ if ( hc->authorization[0] == '\0' || strncmp( hc->authorization, "Basic ", 6 ) != 0 ) { /* Nope, return a 401 Unauthorized. */ send_authenticate( hc, dirname ); return -1; } /* Decode it. */ l = b64_decode( &(hc->authorization[6]), (unsigned char*) authinfo, sizeof(authinfo) - 1 ); authinfo[l] = '\0'; /* Split into user and password. */ authpass = strchr( authinfo, ':' ); if ( authpass == (char*) 0 ) { /* No colon? Bogus auth info. */ send_authenticate( hc, dirname ); return -1; } *authpass++ = '\0'; /* If there are more fields, cut them off. */ colon = strchr( authpass, ':' ); if ( colon != (char*) 0 ) *colon = '\0'; /* See if we have a cached entry and can use it. */ if ( maxprevauthpath != 0 && strcmp( authpath, prevauthpath ) == 0 && sb.st_mtime == prevmtime && strcmp( authinfo, prevuser ) == 0 ) { /* Yes. Check against the cached encrypted password. */ crypt_result = crypt( authpass, prevcryp ); if ( ! crypt_result ) return -1; if ( strcmp( crypt_result, prevcryp ) == 0 ) { /* Ok! */ httpd_realloc_str( &hc->remoteuser, &hc->maxremoteuser, strlen( authinfo ) ); (void) strcpy( hc->remoteuser, authinfo ); return 1; } else { /* No. */ send_authenticate( hc, dirname ); return -1; } } /* Open the password file. */ fp = fopen( authpath, "r" ); if ( fp == (FILE*) 0 ) { /* The file exists but we can't open it? Disallow access. */ syslog( LOG_ERR, "%.80s auth file %.80s could not be opened - %m", httpd_ntoa( &hc->client_addr ), authpath ); httpd_send_err( hc, 403, err403title, "", ERROR_FORM( err403form, "The requested URL '%.80s' is protected by an authentication file, but the authentication file cannot be opened.\n" ), hc->encodedurl ); return -1; } /* Read it. */ while ( fgets( line, sizeof(line), fp ) != (char*) 0 ) { /* Nuke newline. */ l = strlen( line ); if ( line[l - 1] == '\n' ) line[l - 1] = '\0'; /* Split into user and encrypted password. */ cryp = strchr( line, ':' ); if ( cryp == (char*) 0 ) continue; *cryp++ = '\0'; /* Is this the right user? */ if ( strcmp( line, authinfo ) == 0 ) { /* Yes. */ (void) fclose( fp ); /* So is the password right? */ crypt_result = crypt( authpass, cryp ); if ( ! crypt_result ) return -1; if ( strcmp( crypt_result, cryp ) == 0 ) { /* Ok! */ httpd_realloc_str( &hc->remoteuser, &hc->maxremoteuser, strlen( line ) ); (void) strcpy( hc->remoteuser, line ); /* And cache this user's info for next time. */ httpd_realloc_str( &prevauthpath, &maxprevauthpath, strlen( authpath ) ); (void) strcpy( prevauthpath, authpath ); prevmtime = sb.st_mtime; httpd_realloc_str( &prevuser, &maxprevuser, strlen( authinfo ) ); (void) strcpy( prevuser, authinfo ); httpd_realloc_str( &prevcryp, &maxprevcryp, strlen( cryp ) ); (void) strcpy( prevcryp, cryp ); return 1; } else { /* No. */ send_authenticate( hc, dirname ); return -1; } } } /* Didn't find that user. Access denied. */ (void) fclose( fp ); send_authenticate( hc, dirname ); return -1; } #endif /* AUTH_FILE */ static void send_dirredirect( httpd_conn* hc ) { static char* location; static char* header; static size_t maxlocation = 0, maxheader = 0; static char headstr[] = "Location: "; if ( hc->query[0] != '\0') { char* cp = strchr( hc->encodedurl, '?' ); if ( cp != (char*) 0 ) /* should always find it */ *cp = '\0'; httpd_realloc_str( &location, &maxlocation, strlen( hc->encodedurl ) + 2 + strlen( hc->query ) ); (void) my_snprintf( location, maxlocation, "%s/?%s", hc->encodedurl, hc->query ); } else { httpd_realloc_str( &location, &maxlocation, strlen( hc->encodedurl ) + 1 ); (void) my_snprintf( location, maxlocation, "%s/", hc->encodedurl ); } httpd_realloc_str( &header, &maxheader, sizeof(headstr) + strlen( location ) ); (void) my_snprintf( header, maxheader, "%s%s\015\012", headstr, location ); send_response( hc, 302, err302title, header, err302form, location ); } char* httpd_method_str( int method ) { switch ( method ) { case METHOD_GET: return "GET"; case METHOD_HEAD: return "HEAD"; case METHOD_POST: return "POST"; default: return "UNKNOWN"; } } static int hexit( char c ) { if ( c >= '0' && c <= '9' ) return c - '0'; if ( c >= 'a' && c <= 'f' ) return c - 'a' + 10; if ( c >= 'A' && c <= 'F' ) return c - 'A' + 10; return 0; /* shouldn't happen, we're guarded by isxdigit() */ } /* Copies and decodes a string. It's ok for from and to to be the ** same string. */ static void strdecode( char* to, char* from ) { for ( ; *from != '\0'; ++to, ++from ) { if ( from[0] == '%' && isxdigit( from[1] ) && isxdigit( from[2] ) ) { *to = hexit( from[1] ) * 16 + hexit( from[2] ); from += 2; } else *to = *from; } *to = '\0'; } #ifdef GENERATE_INDEXES /* Copies and encodes a string. */ static void strencode( char* to, int tosize, char* from ) { int tolen; for ( tolen = 0; *from != '\0' && tolen + 4 < tosize; ++from ) { if ( isalnum(*from) || strchr( "/_.-~", *from ) != (char*) 0 ) { *to = *from; ++to; ++tolen; } else { (void) sprintf( to, "%%%02x", (int) *from & 0xff ); to += 3; tolen += 3; } } *to = '\0'; } #endif /* GENERATE_INDEXES */ #ifdef TILDE_MAP_1 /* Map a ~username/whatever URL into <prefix>/username. */ static int tilde_map_1( httpd_conn* hc ) { static char* temp; static size_t maxtemp = 0; int len; static char* prefix = TILDE_MAP_1; len = strlen( hc->expnfilename ) - 1; httpd_realloc_str( &temp, &maxtemp, len ); (void) strcpy( temp, &hc->expnfilename[1] ); httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, strlen( prefix ) + 1 + len ); (void) strcpy( hc->expnfilename, prefix ); if ( prefix[0] != '\0' ) (void) strcat( hc->expnfilename, "/" ); (void) strcat( hc->expnfilename, temp ); return 1; } #endif /* TILDE_MAP_1 */ #ifdef TILDE_MAP_2 /* Map a ~username/whatever URL into <user's homedir>/<postfix>. */ static int tilde_map_2( httpd_conn* hc ) { static char* temp; static size_t maxtemp = 0; static char* postfix = TILDE_MAP_2; char* cp; struct passwd* pw; char* alt; char* rest; /* Get the username. */ httpd_realloc_str( &temp, &maxtemp, strlen( hc->expnfilename ) - 1 ); (void) strcpy( temp, &hc->expnfilename[1] ); cp = strchr( temp, '/' ); if ( cp != (char*) 0 ) *cp++ = '\0'; else cp = ""; /* Get the passwd entry. */ pw = getpwnam( temp ); if ( pw == (struct passwd*) 0 ) return 0; /* Set up altdir. */ httpd_realloc_str( &hc->altdir, &hc->maxaltdir, strlen( pw->pw_dir ) + 1 + strlen( postfix ) ); (void) strcpy( hc->altdir, pw->pw_dir ); if ( postfix[0] != '\0' ) { (void) strcat( hc->altdir, "/" ); (void) strcat( hc->altdir, postfix ); } alt = expand_symlinks( hc->altdir, &rest, 0, 1 ); if ( rest[0] != '\0' ) return 0; httpd_realloc_str( &hc->altdir, &hc->maxaltdir, strlen( alt ) ); (void) strcpy( hc->altdir, alt ); /* And the filename becomes altdir plus the post-~ part of the original. */ httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, strlen( hc->altdir ) + 1 + strlen( cp ) ); (void) my_snprintf( hc->expnfilename, hc->maxexpnfilename, "%s/%s", hc->altdir, cp ); /* For this type of tilde mapping, we want to defeat vhost mapping. */ hc->tildemapped = 1; return 1; } #endif /* TILDE_MAP_2 */ /* Virtual host mapping. */ static int vhost_map( httpd_conn* hc ) { httpd_sockaddr sa; socklen_t sz; static char* tempfilename; static size_t maxtempfilename = 0; char* cp1; int len; #ifdef VHOST_DIRLEVELS int i; char* cp2; #endif /* VHOST_DIRLEVELS */ /* Figure out the virtual hostname. */ if ( hc->reqhost[0] != '\0' ) hc->hostname = hc->reqhost; else if ( hc->hdrhost[0] != '\0' ) hc->hostname = hc->hdrhost; else { sz = sizeof(sa); if ( getsockname( hc->conn_fd, &sa.sa, &sz ) < 0 ) { syslog( LOG_ERR, "getsockname - %m" ); return 0; } hc->hostname = httpd_ntoa( &sa ); } /* Pound it to lower case. */ for ( cp1 = hc->hostname; *cp1 != '\0'; ++cp1 ) if ( isupper( *cp1 ) ) *cp1 = tolower( *cp1 ); if ( hc->tildemapped ) return 1; /* Figure out the host directory. */ #ifdef VHOST_DIRLEVELS httpd_realloc_str( &hc->hostdir, &hc->maxhostdir, strlen( hc->hostname ) + 2 * VHOST_DIRLEVELS ); if ( strncmp( hc->hostname, "www.", 4 ) == 0 ) cp1 = &hc->hostname[4]; else cp1 = hc->hostname; for ( cp2 = hc->hostdir, i = 0; i < VHOST_DIRLEVELS; ++i ) { /* Skip dots in the hostname. If we don't, then we get vhost ** directories in higher level of filestructure if dot gets ** involved into path construction. It's `while' used here instead ** of `if' for it's possible to have a hostname formed with two ** dots at the end of it. */ while ( *cp1 == '.' ) ++cp1; /* Copy a character from the hostname, or '_' if we ran out. */ if ( *cp1 != '\0' ) *cp2++ = *cp1++; else *cp2++ = '_'; /* Copy a slash. */ *cp2++ = '/'; } (void) strcpy( cp2, hc->hostname ); #else /* VHOST_DIRLEVELS */ httpd_realloc_str( &hc->hostdir, &hc->maxhostdir, strlen( hc->hostname ) ); (void) strcpy( hc->hostdir, hc->hostname ); #endif /* VHOST_DIRLEVELS */ /* Prepend hostdir to the filename. */ len = strlen( hc->expnfilename ); httpd_realloc_str( &tempfilename, &maxtempfilename, len ); (void) strcpy( tempfilename, hc->expnfilename ); httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, strlen( hc->hostdir ) + 1 + len ); (void) strcpy( hc->expnfilename, hc->hostdir ); (void) strcat( hc->expnfilename, "/" ); (void) strcat( hc->expnfilename, tempfilename ); return 1; } /* Expands all symlinks in the given filename, eliding ..'s and leading /'s. ** Returns the expanded path (pointer to static string), or (char*) 0 on ** errors. Also returns, in the string pointed to by restP, any trailing ** parts of the path that don't exist. ** ** This is a fairly nice little routine. It handles any size filenames ** without excessive mallocs. */ static char* expand_symlinks( char* path, char** restP, int no_symlink_check, int tildemapped ) { static char* checked; static char* rest; char link[5000]; static size_t maxchecked = 0, maxrest = 0; size_t checkedlen, restlen, linklen, prevcheckedlen, prevrestlen; int nlinks, i; char* r; char* cp1; char* cp2; if ( no_symlink_check ) { /* If we are chrooted, we can actually skip the symlink-expansion, ** since it's impossible to get out of the tree. However, we still ** need to do the pathinfo check, and the existing symlink expansion ** code is a pretty reasonable way to do this. So, what we do is ** a single stat() of the whole filename - if it exists, then we ** return it as is with nothing in restP. If it doesn't exist, we ** fall through to the existing code. ** ** One side-effect of this is that users can't symlink to central ** approved CGIs any more. The workaround is to use the central ** URL for the CGI instead of a local symlinked one. */ struct stat sb; if ( stat( path, &sb ) != -1 ) { checkedlen = strlen( path ); httpd_realloc_str( &checked, &maxchecked, checkedlen ); (void) strcpy( checked, path ); /* Trim trailing slashes. */ while ( checkedlen && checked[checkedlen - 1] == '/' ) { checked[checkedlen - 1] = '\0'; --checkedlen; } httpd_realloc_str( &rest, &maxrest, 0 ); rest[0] = '\0'; *restP = rest; return checked; } } /* Start out with nothing in checked and the whole filename in rest. */ httpd_realloc_str( &checked, &maxchecked, 1 ); checked[0] = '\0'; checkedlen = 0; restlen = strlen( path ); httpd_realloc_str( &rest, &maxrest, restlen ); (void) strcpy( rest, path ); if ( restlen && rest[restlen - 1] == '/' ) rest[--restlen] = '\0'; /* trim trailing slash */ if ( ! tildemapped ) /* Remove any leading slashes. */ while ( rest[0] == '/' ) { /*One more for '\0', one less for the eaten first*/ (void) memmove( rest, &(rest[1]), strlen(rest) ); --restlen; } r = rest; nlinks = 0; /* While there are still components to check... */ while ( restlen > 0 ) { /* Save current checkedlen in case we get a symlink. Save current ** restlen in case we get a non-existant component. */ prevcheckedlen = checkedlen; prevrestlen = restlen; /* Grab one component from r and transfer it to checked. */ cp1 = strchr( r, '/' ); if ( cp1 != (char*) 0 ) { i = cp1 - r; if ( i == 0 ) { /* Special case for absolute paths. */ httpd_realloc_str( &checked, &maxchecked, checkedlen + 1 ); (void) strncpy( &checked[checkedlen], r, 1 ); checkedlen += 1; } else if ( strncmp( r, "..", MAX( i, 2 ) ) == 0 ) { /* Ignore ..'s that go above the start of the path. */ if ( checkedlen != 0 ) { cp2 = strrchr( checked, '/' ); if ( cp2 == (char*) 0 ) checkedlen = 0; else if ( cp2 == checked ) checkedlen = 1; else checkedlen = cp2 - checked; } } else { httpd_realloc_str( &checked, &maxchecked, checkedlen + 1 + i ); if ( checkedlen > 0 && checked[checkedlen-1] != '/' ) checked[checkedlen++] = '/'; (void) strncpy( &checked[checkedlen], r, i ); checkedlen += i; } checked[checkedlen] = '\0'; r += i + 1; restlen -= i + 1; } else { /* No slashes remaining, r is all one component. */ if ( strcmp( r, ".." ) == 0 ) { /* Ignore ..'s that go above the start of the path. */ if ( checkedlen != 0 ) { cp2 = strrchr( checked, '/' ); if ( cp2 == (char*) 0 ) checkedlen = 0; else if ( cp2 == checked ) checkedlen = 1; else checkedlen = cp2 - checked; checked[checkedlen] = '\0'; } } else { httpd_realloc_str( &checked, &maxchecked, checkedlen + 1 + restlen ); if ( checkedlen > 0 && checked[checkedlen-1] != '/' ) checked[checkedlen++] = '/'; (void) strcpy( &checked[checkedlen], r ); checkedlen += restlen; } r += restlen; restlen = 0; } /* Try reading the current filename as a symlink */ if ( checked[0] == '\0' ) continue; linklen = readlink( checked, link, sizeof(link) - 1 ); if ( linklen == -1 ) { if ( errno == EINVAL ) continue; /* not a symlink */ if ( errno == EACCES || errno == ENOENT || errno == ENOTDIR ) { /* That last component was bogus. Restore and return. */ *restP = r - ( prevrestlen - restlen ); if ( prevcheckedlen == 0 ) (void) strcpy( checked, "." ); else checked[prevcheckedlen] = '\0'; return checked; } syslog( LOG_ERR, "readlink %.80s - %m", checked ); return (char*) 0; } ++nlinks; if ( nlinks > MAX_LINKS ) { syslog( LOG_ERR, "too many symlinks in %.80s", path ); return (char*) 0; } link[linklen] = '\0'; if ( link[linklen - 1] == '/' ) link[--linklen] = '\0'; /* trim trailing slash */ /* Insert the link contents in front of the rest of the filename. */ if ( restlen != 0 ) { (void) strcpy( rest, r ); httpd_realloc_str( &rest, &maxrest, restlen + linklen + 1 ); for ( i = restlen; i >= 0; --i ) rest[i + linklen + 1] = rest[i]; (void) strcpy( rest, link ); rest[linklen] = '/'; restlen += linklen + 1; r = rest; } else { /* There's nothing left in the filename, so the link contents ** becomes the rest. */ httpd_realloc_str( &rest, &maxrest, linklen ); (void) strcpy( rest, link ); restlen = linklen; r = rest; } if ( rest[0] == '/' ) { /* There must have been an absolute symlink - zero out checked. */ checked[0] = '\0'; checkedlen = 0; } else { /* Re-check this component. */ checkedlen = prevcheckedlen; checked[checkedlen] = '\0'; } } /* Ok. */ *restP = r; if ( checked[0] == '\0' ) (void) strcpy( checked, "." ); return checked; } int httpd_get_conn( httpd_server* hs, int listen_fd, httpd_conn* hc ) { httpd_sockaddr sa; socklen_t sz; if ( ! hc->initialized ) { hc->read_size = 0; httpd_realloc_str( &hc->read_buf, &hc->read_size, 500 ); hc->maxdecodedurl = hc->maxorigfilename = hc->maxexpnfilename = hc->maxencodings = hc->maxpathinfo = hc->maxquery = hc->maxaccept = hc->maxaccepte = hc->maxreqhost = hc->maxhostdir = hc->maxremoteuser = hc->maxresponse = 0; #ifdef TILDE_MAP_2 hc->maxaltdir = 0; #endif /* TILDE_MAP_2 */ httpd_realloc_str( &hc->decodedurl, &hc->maxdecodedurl, 1 ); httpd_realloc_str( &hc->origfilename, &hc->maxorigfilename, 1 ); httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, 0 ); httpd_realloc_str( &hc->encodings, &hc->maxencodings, 0 ); httpd_realloc_str( &hc->pathinfo, &hc->maxpathinfo, 0 ); httpd_realloc_str( &hc->query, &hc->maxquery, 0 ); httpd_realloc_str( &hc->accept, &hc->maxaccept, 0 ); httpd_realloc_str( &hc->accepte, &hc->maxaccepte, 0 ); httpd_realloc_str( &hc->reqhost, &hc->maxreqhost, 0 ); httpd_realloc_str( &hc->hostdir, &hc->maxhostdir, 0 ); httpd_realloc_str( &hc->remoteuser, &hc->maxremoteuser, 0 ); httpd_realloc_str( &hc->response, &hc->maxresponse, 0 ); #ifdef TILDE_MAP_2 httpd_realloc_str( &hc->altdir, &hc->maxaltdir, 0 ); #endif /* TILDE_MAP_2 */ hc->initialized = 1; } /* Accept the new connection. */ sz = sizeof(sa); hc->conn_fd = accept( listen_fd, &sa.sa, &sz ); if ( hc->conn_fd < 0 ) { if ( errno == EWOULDBLOCK ) return GC_NO_MORE; syslog( LOG_ERR, "accept - %m" ); return GC_FAIL; } if ( ! sockaddr_check( &sa ) ) { syslog( LOG_ERR, "unknown sockaddr family" ); close( hc->conn_fd ); hc->conn_fd = -1; return GC_FAIL; } (void) fcntl( hc->conn_fd, F_SETFD, 1 ); hc->hs = hs; (void) memset( &hc->client_addr, 0, sizeof(hc->client_addr) ); (void) memmove( &hc->client_addr, &sa, sockaddr_len( &sa ) ); hc->read_idx = 0; hc->checked_idx = 0; hc->checked_state = CHST_FIRSTWORD; hc->method = METHOD_UNKNOWN; hc->status = 0; hc->bytes_to_send = 0; hc->bytes_sent = 0; hc->encodedurl = ""; hc->decodedurl[0] = '\0'; hc->protocol = "UNKNOWN"; hc->origfilename[0] = '\0'; hc->expnfilename[0] = '\0'; hc->encodings[0] = '\0'; hc->pathinfo[0] = '\0'; hc->query[0] = '\0'; hc->referer = ""; hc->useragent = ""; hc->accept[0] = '\0'; hc->accepte[0] = '\0'; hc->acceptl = ""; hc->cookie = ""; hc->contenttype = ""; hc->reqhost[0] = '\0'; hc->hdrhost = ""; hc->hostdir[0] = '\0'; hc->authorization = ""; hc->remoteuser[0] = '\0'; hc->response[0] = '\0'; #ifdef TILDE_MAP_2 hc->altdir[0] = '\0'; #endif /* TILDE_MAP_2 */ hc->responselen = 0; hc->if_modified_since = (time_t) -1; hc->range_if = (time_t) -1; hc->contentlength = -1; hc->type = ""; hc->hostname = (char*) 0; hc->mime_flag = 1; hc->one_one = 0; hc->got_range = 0; hc->tildemapped = 0; hc->first_byte_index = 0; hc->last_byte_index = -1; hc->keep_alive = 0; hc->should_linger = 0; hc->file_address = (char*) 0; return GC_OK; } /* Checks hc->read_buf to see whether a complete request has been read so far; ** either the first line has two words (an HTTP/0.9 request), or the first ** line has three words and there's a blank line present. ** ** hc->read_idx is how much has been read in; hc->checked_idx is how much we ** have checked so far; and hc->checked_state is the current state of the ** finite state machine. */ int httpd_got_request( httpd_conn* hc ) { char c; for ( ; hc->checked_idx < hc->read_idx; ++hc->checked_idx ) { c = hc->read_buf[hc->checked_idx]; switch ( hc->checked_state ) { case CHST_FIRSTWORD: switch ( c ) { case ' ': case '\t': hc->checked_state = CHST_FIRSTWS; break; case '\012': case '\015': hc->checked_state = CHST_BOGUS; return GR_BAD_REQUEST; } break; case CHST_FIRSTWS: switch ( c ) { case ' ': case '\t': break; case '\012': case '\015': hc->checked_state = CHST_BOGUS; return GR_BAD_REQUEST; default: hc->checked_state = CHST_SECONDWORD; break; } break; case CHST_SECONDWORD: switch ( c ) { case ' ': case '\t': hc->checked_state = CHST_SECONDWS; break; case '\012': case '\015': /* The first line has only two words - an HTTP/0.9 request. */ return GR_GOT_REQUEST; } break; case CHST_SECONDWS: switch ( c ) { case ' ': case '\t': break; case '\012': case '\015': hc->checked_state = CHST_BOGUS; return GR_BAD_REQUEST; default: hc->checked_state = CHST_THIRDWORD; break; } break; case CHST_THIRDWORD: switch ( c ) { case ' ': case '\t': hc->checked_state = CHST_THIRDWS; break; case '\012': hc->checked_state = CHST_LF; break; case '\015': hc->checked_state = CHST_CR; break; } break; case CHST_THIRDWS: switch ( c ) { case ' ': case '\t': break; case '\012': hc->checked_state = CHST_LF; break; case '\015': hc->checked_state = CHST_CR; break; default: hc->checked_state = CHST_BOGUS; return GR_BAD_REQUEST; } break; case CHST_LINE: switch ( c ) { case '\012': hc->checked_state = CHST_LF; break; case '\015': hc->checked_state = CHST_CR; break; } break; case CHST_LF: switch ( c ) { case '\012': /* Two newlines in a row - a blank line - end of request. */ return GR_GOT_REQUEST; case '\015': hc->checked_state = CHST_CR; break; default: hc->checked_state = CHST_LINE; break; } break; case CHST_CR: switch ( c ) { case '\012': hc->checked_state = CHST_CRLF; break; case '\015': /* Two returns in a row - end of request. */ return GR_GOT_REQUEST; default: hc->checked_state = CHST_LINE; break; } break; case CHST_CRLF: switch ( c ) { case '\012': /* Two newlines in a row - end of request. */ return GR_GOT_REQUEST; case '\015': hc->checked_state = CHST_CRLFCR; break; default: hc->checked_state = CHST_LINE; break; } break; case CHST_CRLFCR: switch ( c ) { case '\012': case '\015': /* Two CRLFs or two CRs in a row - end of request. */ return GR_GOT_REQUEST; default: hc->checked_state = CHST_LINE; break; } break; case CHST_BOGUS: return GR_BAD_REQUEST; } } return GR_NO_REQUEST; } int httpd_parse_request( httpd_conn* hc ) { char* buf; char* method_str; char* url; char* protocol; char* reqhost; char* eol; char* cp; char* pi; hc->checked_idx = 0; /* reset */ method_str = bufgets( hc ); url = strpbrk( method_str, " \t\012\015" ); if ( url == (char*) 0 ) { httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" ); return -1; } *url++ = '\0'; url += strspn( url, " \t\012\015" ); protocol = strpbrk( url, " \t\012\015" ); if ( protocol == (char*) 0 ) { protocol = "HTTP/0.9"; hc->mime_flag = 0; } else { *protocol++ = '\0'; protocol += strspn( protocol, " \t\012\015" ); if ( *protocol != '\0' ) { eol = strpbrk( protocol, " \t\012\015" ); if ( eol != (char*) 0 ) *eol = '\0'; if ( strcasecmp( protocol, "HTTP/1.0" ) != 0 ) hc->one_one = 1; } } hc->protocol = protocol; /* Check for HTTP/1.1 absolute URL. */ if ( strncasecmp( url, "http://", 7 ) == 0 ) { if ( ! hc->one_one ) { httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" ); return -1; } reqhost = url + 7; url = strchr( reqhost, '/' ); if ( url == (char*) 0 ) { httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" ); return -1; } *url = '\0'; if ( strchr( reqhost, '/' ) != (char*) 0 || reqhost[0] == '.' ) { httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" ); return -1; } httpd_realloc_str( &hc->reqhost, &hc->maxreqhost, strlen( reqhost ) ); (void) strcpy( hc->reqhost, reqhost ); *url = '/'; } if ( *url != '/' ) { httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" ); return -1; } if ( strcasecmp( method_str, httpd_method_str( METHOD_GET ) ) == 0 ) hc->method = METHOD_GET; else if ( strcasecmp( method_str, httpd_method_str( METHOD_HEAD ) ) == 0 ) hc->method = METHOD_HEAD; else if ( strcasecmp( method_str, httpd_method_str( METHOD_POST ) ) == 0 ) hc->method = METHOD_POST; else { httpd_send_err( hc, 501, err501title, "", err501form, method_str ); return -1; } hc->encodedurl = url; httpd_realloc_str( &hc->decodedurl, &hc->maxdecodedurl, strlen( hc->encodedurl ) ); strdecode( hc->decodedurl, hc->encodedurl ); httpd_realloc_str( &hc->origfilename, &hc->maxorigfilename, strlen( hc->decodedurl ) ); (void) strcpy( hc->origfilename, &hc->decodedurl[1] ); /* Special case for top-level URL. */ if ( hc->origfilename[0] == '\0' ) (void) strcpy( hc->origfilename, "." ); /* Extract query string from encoded URL. */ cp = strchr( hc->encodedurl, '?' ); if ( cp != (char*) 0 ) { ++cp; httpd_realloc_str( &hc->query, &hc->maxquery, strlen( cp ) ); (void) strcpy( hc->query, cp ); /* Remove query from (decoded) origfilename. */ cp = strchr( hc->origfilename, '?' ); if ( cp != (char*) 0 ) *cp = '\0'; } de_dotdot( hc->origfilename ); if ( hc->origfilename[0] == '/' || ( hc->origfilename[0] == '.' && hc->origfilename[1] == '.' && ( hc->origfilename[2] == '\0' || hc->origfilename[2] == '/' ) ) ) { httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" ); return -1; } if ( hc->mime_flag ) { /* Read the MIME headers. */ while ( ( buf = bufgets( hc ) ) != (char*) 0 ) { if ( buf[0] == '\0' ) break; if ( strncasecmp( buf, "Referer:", 8 ) == 0 ) { cp = &buf[8]; cp += strspn( cp, " \t" ); hc->referer = cp; } else if ( strncasecmp( buf, "User-Agent:", 11 ) == 0 ) { cp = &buf[11]; cp += strspn( cp, " \t" ); hc->useragent = cp; } else if ( strncasecmp( buf, "Host:", 5 ) == 0 ) { cp = &buf[5]; cp += strspn( cp, " \t" ); hc->hdrhost = cp; cp = strchr( hc->hdrhost, ':' ); if ( cp != (char*) 0 ) *cp = '\0'; if ( strchr( hc->hdrhost, '/' ) != (char*) 0 || hc->hdrhost[0] == '.' ) { httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" ); return -1; } } else if ( strncasecmp( buf, "Accept:", 7 ) == 0 ) { cp = &buf[7]; cp += strspn( cp, " \t" ); if ( hc->accept[0] != '\0' ) { if ( strlen( hc->accept ) > 5000 ) { syslog( LOG_ERR, "%.80s way too much Accept: data", httpd_ntoa( &hc->client_addr ) ); continue; } httpd_realloc_str( &hc->accept, &hc->maxaccept, strlen( hc->accept ) + 2 + strlen( cp ) ); (void) strcat( hc->accept, ", " ); } else httpd_realloc_str( &hc->accept, &hc->maxaccept, strlen( cp ) ); (void) strcat( hc->accept, cp ); } else if ( strncasecmp( buf, "Accept-Encoding:", 16 ) == 0 ) { cp = &buf[16]; cp += strspn( cp, " \t" ); if ( hc->accepte[0] != '\0' ) { if ( strlen( hc->accepte ) > 5000 ) { syslog( LOG_ERR, "%.80s way too much Accept-Encoding: data", httpd_ntoa( &hc->client_addr ) ); continue; } httpd_realloc_str( &hc->accepte, &hc->maxaccepte, strlen( hc->accepte ) + 2 + strlen( cp ) ); (void) strcat( hc->accepte, ", " ); } else httpd_realloc_str( &hc->accepte, &hc->maxaccepte, strlen( cp ) ); (void) strcpy( hc->accepte, cp ); } else if ( strncasecmp( buf, "Accept-Language:", 16 ) == 0 ) { cp = &buf[16]; cp += strspn( cp, " \t" ); hc->acceptl = cp; } else if ( strncasecmp( buf, "If-Modified-Since:", 18 ) == 0 ) { cp = &buf[18]; hc->if_modified_since = tdate_parse( cp ); if ( hc->if_modified_since == (time_t) -1 ) syslog( LOG_DEBUG, "unparsable time: %.80s", cp ); } else if ( strncasecmp( buf, "Cookie:", 7 ) == 0 ) { cp = &buf[7]; cp += strspn( cp, " \t" ); hc->cookie = cp; } else if ( strncasecmp( buf, "Range:", 6 ) == 0 ) { /* Only support %d- and %d-%d, not %d-%d,%d-%d or -%d. */ if ( strchr( buf, ',' ) == (char*) 0 ) { char* cp_dash; cp = strpbrk( buf, "=" ); if ( cp != (char*) 0 ) { cp_dash = strchr( cp + 1, '-' ); if ( cp_dash != (char*) 0 && cp_dash != cp + 1 ) { *cp_dash = '\0'; hc->got_range = 1; hc->first_byte_index = atoll( cp + 1 ); if ( hc->first_byte_index < 0 ) hc->first_byte_index = 0; if ( isdigit( (int) cp_dash[1] ) ) { hc->last_byte_index = atoll( cp_dash + 1 ); if ( hc->last_byte_index < 0 ) hc->last_byte_index = -1; } } } } } else if ( strncasecmp( buf, "Range-If:", 9 ) == 0 || strncasecmp( buf, "If-Range:", 9 ) == 0 ) { cp = &buf[9]; hc->range_if = tdate_parse( cp ); if ( hc->range_if == (time_t) -1 ) syslog( LOG_DEBUG, "unparsable time: %.80s", cp ); } else if ( strncasecmp( buf, "Content-Type:", 13 ) == 0 ) { cp = &buf[13]; cp += strspn( cp, " \t" ); hc->contenttype = cp; } else if ( strncasecmp( buf, "Content-Length:", 15 ) == 0 ) { cp = &buf[15]; hc->contentlength = atol( cp ); } else if ( strncasecmp( buf, "Authorization:", 14 ) == 0 ) { cp = &buf[14]; cp += strspn( cp, " \t" ); hc->authorization = cp; } else if ( strncasecmp( buf, "Connection:", 11 ) == 0 ) { cp = &buf[11]; cp += strspn( cp, " \t" ); if ( strcasecmp( cp, "keep-alive" ) == 0 ) hc->keep_alive = 1; } else if ( strncasecmp( buf, "X-Forwarded-For:", 16 ) == 0 ) { // Use real IP if available cp = &buf[16]; cp += strspn( cp, " \t" ); inet_aton( cp, &(hc->client_addr.sa_in.sin_addr) ); } #ifdef LOG_UNKNOWN_HEADERS else if ( strncasecmp( buf, "Accept-Charset:", 15 ) == 0 || strncasecmp( buf, "Accept-Language:", 16 ) == 0 || strncasecmp( buf, "Agent:", 6 ) == 0 || strncasecmp( buf, "Cache-Control:", 14 ) == 0 || strncasecmp( buf, "Cache-Info:", 11 ) == 0 || strncasecmp( buf, "Charge-To:", 10 ) == 0 || strncasecmp( buf, "Client-IP:", 10 ) == 0 || strncasecmp( buf, "Date:", 5 ) == 0 || strncasecmp( buf, "Extension:", 10 ) == 0 || strncasecmp( buf, "Forwarded:", 10 ) == 0 || strncasecmp( buf, "From:", 5 ) == 0 || strncasecmp( buf, "HTTP-Version:", 13 ) == 0 || strncasecmp( buf, "Max-Forwards:", 13 ) == 0 || strncasecmp( buf, "Message-Id:", 11 ) == 0 || strncasecmp( buf, "MIME-Version:", 13 ) == 0 || strncasecmp( buf, "Negotiate:", 10 ) == 0 || strncasecmp( buf, "Pragma:", 7 ) == 0 || strncasecmp( buf, "Proxy-Agent:", 12 ) == 0 || strncasecmp( buf, "Proxy-Connection:", 17 ) == 0 || strncasecmp( buf, "Security-Scheme:", 16 ) == 0 || strncasecmp( buf, "Session-Id:", 11 ) == 0 || strncasecmp( buf, "UA-Color:", 9 ) == 0 || strncasecmp( buf, "UA-CPU:", 7 ) == 0 || strncasecmp( buf, "UA-Disp:", 8 ) == 0 || strncasecmp( buf, "UA-OS:", 6 ) == 0 || strncasecmp( buf, "UA-Pixels:", 10 ) == 0 || strncasecmp( buf, "User:", 5 ) == 0 || strncasecmp( buf, "Via:", 4 ) == 0 || strncasecmp( buf, "X-", 2 ) == 0 ) ; /* ignore */ else syslog( LOG_DEBUG, "unknown request header: %.80s", buf ); #endif /* LOG_UNKNOWN_HEADERS */ } } if ( hc->one_one ) { /* Check that HTTP/1.1 requests specify a host, as required. */ if ( hc->reqhost[0] == '\0' && hc->hdrhost[0] == '\0' ) { httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" ); return -1; } /* If the client wants to do keep-alives, it might also be doing ** pipelining. There's no way for us to tell. Since we don't ** implement keep-alives yet, if we close such a connection there ** might be unread pipelined requests waiting. So, we have to ** do a lingering close. */ if ( hc->keep_alive ) hc->should_linger = 1; } /* Ok, the request has been parsed. Now we resolve stuff that ** may require the entire request. */ /* Copy original filename to expanded filename. */ httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, strlen( hc->origfilename ) ); (void) strcpy( hc->expnfilename, hc->origfilename ); /* Tilde mapping. */ if ( hc->expnfilename[0] == '~' ) { #ifdef TILDE_MAP_1 if ( ! tilde_map_1( hc ) ) { httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl ); return -1; } #endif /* TILDE_MAP_1 */ #ifdef TILDE_MAP_2 if ( ! tilde_map_2( hc ) ) { httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl ); return -1; } #endif /* TILDE_MAP_2 */ } /* Virtual host mapping. */ if ( hc->hs->vhost ) if ( ! vhost_map( hc ) ) { httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); return -1; } /* Expand all symbolic links in the filename. This also gives us ** any trailing non-existing components, for pathinfo. */ cp = expand_symlinks( hc->expnfilename, &pi, hc->hs->no_symlink_check, hc->tildemapped ); if ( cp == (char*) 0 ) { httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); return -1; } httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, strlen( cp ) ); (void) strcpy( hc->expnfilename, cp ); httpd_realloc_str( &hc->pathinfo, &hc->maxpathinfo, strlen( pi ) ); (void) strcpy( hc->pathinfo, pi ); /* Remove pathinfo stuff from the original filename too. */ if ( hc->pathinfo[0] != '\0' ) { int i; i = strlen( hc->origfilename ) - strlen( hc->pathinfo ); if ( strcmp( &hc->origfilename[i], hc->pathinfo ) == 0 ) { if ( i == 0 ) hc->origfilename[0] = '\0'; else hc->origfilename[i - 1] = '\0'; } } /* If the expanded filename is an absolute path, check that it's still ** within the current directory or the alternate directory. */ if ( hc->expnfilename[0] == '/' ) { if ( strncmp( hc->expnfilename, hc->hs->cwd, strlen( hc->hs->cwd ) ) == 0 ) { /* Elide the current directory. */ (void) memmove( hc->expnfilename, &hc->expnfilename[strlen( hc->hs->cwd )], strlen(hc->expnfilename) - strlen( hc->hs->cwd ) + 1 ); } #ifdef TILDE_MAP_2 else if ( hc->altdir[0] != '\0' && ( strncmp( hc->expnfilename, hc->altdir, strlen( hc->altdir ) ) == 0 && ( hc->expnfilename[strlen( hc->altdir )] == '\0' || hc->expnfilename[strlen( hc->altdir )] == '/' ) ) ) {} #endif /* TILDE_MAP_2 */ else { syslog( LOG_NOTICE, "%.80s URL \"%.80s\" goes outside the web tree", httpd_ntoa( &hc->client_addr ), hc->encodedurl ); httpd_send_err( hc, 403, err403title, "", ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file outside the permitted web server directory tree.\n" ), hc->encodedurl ); return -1; } } return 0; } static char* bufgets( httpd_conn* hc ) { int i; char c; for ( i = hc->checked_idx; hc->checked_idx < hc->read_idx; ++hc->checked_idx ) { c = hc->read_buf[hc->checked_idx]; if ( c == '\012' || c == '\015' ) { hc->read_buf[hc->checked_idx] = '\0'; ++hc->checked_idx; if ( c == '\015' && hc->checked_idx < hc->read_idx && hc->read_buf[hc->checked_idx] == '\012' ) { hc->read_buf[hc->checked_idx] = '\0'; ++hc->checked_idx; } return &(hc->read_buf[i]); } } return (char*) 0; } static void de_dotdot( char* file ) { char* cp; char* cp2; int l; /* Collapse any multiple / sequences. */ while ( ( cp = strstr( file, "//") ) != (char*) 0 ) { for ( cp2 = cp + 2; *cp2 == '/'; ++cp2 ) continue; (void) strcpy( cp + 1, cp2 ); } /* Remove leading ./ and any /./ sequences. */ while ( strncmp( file, "./", 2 ) == 0 ) (void) memmove( file, file + 2, strlen( file ) - 1 ); while ( ( cp = strstr( file, "/./") ) != (char*) 0 ) (void) memmove( cp, cp + 2, strlen( file ) - 1 ); /* Alternate between removing leading ../ and removing xxx/../ */ for (;;) { while ( strncmp( file, "../", 3 ) == 0 ) (void) memmove( file, file + 3, strlen( file ) - 2 ); cp = strstr( file, "/../" ); if ( cp == (char*) 0 ) break; for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 ) continue; (void) strcpy( cp2 + 1, cp + 4 ); } /* Also elide any xxx/.. at the end. */ while ( ( l = strlen( file ) ) > 3 && strcmp( ( cp = file + l - 3 ), "/.." ) == 0 ) { for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 ) continue; if ( cp2 < file ) break; *cp2 = '\0'; } } void httpd_close_conn( httpd_conn* hc, struct timeval* nowP ) { make_log_entry( hc, nowP ); if ( hc->file_address != (char*) 0 ) { mmc_unmap( hc->file_address, &(hc->sb), nowP ); hc->file_address = (char*) 0; } if ( hc->conn_fd >= 0 ) { (void) close( hc->conn_fd ); hc->conn_fd = -1; } } void httpd_destroy_conn( httpd_conn* hc ) { if (hc->initialized) { free(hc->read_buf); free(hc->decodedurl); free(hc->origfilename); free(hc->expnfilename); free(hc->encodings); free(hc->pathinfo); free(hc->query); free(hc->accept); free(hc->accepte); free(hc->reqhost); free(hc->hostdir); free(hc->remoteuser); free(hc->response); #ifdef TILDE_MAP_2 free(hc->altdir); #endif /* TILDE_MAP_2 */ hc->initialized = 0; } } struct mime_entry { char* ext; size_t ext_len; char* val; size_t val_len; }; static struct mime_entry enc_tab[] = { #include "mime_encodings.h" }; static const int n_enc_tab = sizeof(enc_tab) / sizeof(*enc_tab); static struct mime_entry typ_tab[] = { #include "mime_types.h" }; static const int n_typ_tab = sizeof(typ_tab) / sizeof(*typ_tab); /* qsort comparison routine - declared old-style on purpose, for portability. */ static int ext_compare( a, b ) struct mime_entry* a; struct mime_entry* b; { return strcmp( a->ext, b->ext ); } static void init_mime( void ) { int i; /* Sort the tables so we can do binary search. */ qsort( enc_tab, n_enc_tab, sizeof(*enc_tab), ext_compare ); qsort( typ_tab, n_typ_tab, sizeof(*typ_tab), ext_compare ); /* Fill in the lengths. */ for ( i = 0; i < n_enc_tab; ++i ) { enc_tab[i].ext_len = strlen( enc_tab[i].ext ); enc_tab[i].val_len = strlen( enc_tab[i].val ); } for ( i = 0; i < n_typ_tab; ++i ) { typ_tab[i].ext_len = strlen( typ_tab[i].ext ); typ_tab[i].val_len = strlen( typ_tab[i].val ); } } /* Figure out MIME encodings and type based on the filename. Multiple ** encodings are separated by commas, and are listed in the order in ** which they were applied to the file. */ static void figure_mime( httpd_conn* hc ) { char* prev_dot; char* dot; char* ext; int me_indexes[100], n_me_indexes; size_t ext_len, encodings_len; int i, top, bot, mid; int r; char* default_type = "application/octet-stream"; /* Peel off encoding extensions until there aren't any more. */ n_me_indexes = 0; hc->type = default_type; for ( prev_dot = &hc->expnfilename[strlen(hc->expnfilename)]; ; prev_dot = dot ) { for ( dot = prev_dot - 1; dot >= hc->expnfilename && *dot != '.'; --dot ) ; if ( dot < hc->expnfilename ) { /* No dot found. No more extensions. */ goto done; } ext = dot + 1; ext_len = prev_dot - ext; /* Search the encodings table. Linear search is fine here, there ** are only a few entries. */ for ( i = 0; i < n_enc_tab; ++i ) { if ( ext_len == enc_tab[i].ext_len && strncasecmp( ext, enc_tab[i].ext, ext_len ) == 0 ) { if ( n_me_indexes < sizeof(me_indexes)/sizeof(*me_indexes) ) { me_indexes[n_me_indexes] = i; ++n_me_indexes; } break; } } /* Binary search for a matching type extension. */ top = n_typ_tab - 1; bot = 0; while ( top >= bot ) { mid = ( top + bot ) / 2; r = strncasecmp( ext, typ_tab[mid].ext, ext_len ); if ( r < 0 ) top = mid - 1; else if ( r > 0 ) bot = mid + 1; else if ( ext_len < typ_tab[mid].ext_len ) top = mid - 1; else if ( ext_len > typ_tab[mid].ext_len ) bot = mid + 1; else { hc->type = typ_tab[mid].val; goto done; } } } done: /* The last thing we do is actually generate the mime-encoding header. */ hc->encodings[0] = '\0'; encodings_len = 0; for ( i = n_me_indexes - 1; i >= 0; --i ) { httpd_realloc_str( &hc->encodings, &hc->maxencodings, encodings_len + enc_tab[me_indexes[i]].val_len + 1 ); if ( hc->encodings[0] != '\0' ) { (void) strcpy( &hc->encodings[encodings_len], "," ); ++encodings_len; } (void) strcpy( &hc->encodings[encodings_len], enc_tab[me_indexes[i]].val ); encodings_len += enc_tab[me_indexes[i]].val_len; } } #ifdef CGI_TIMELIMIT static void cgi_kill2( ClientData client_data, struct timeval* nowP ) { pid_t pid; pid = (pid_t) client_data.i; if ( kill( pid, SIGKILL ) == 0 ) syslog( LOG_ERR, "hard-killed CGI process %d", pid ); } static void cgi_kill( ClientData client_data, struct timeval* nowP ) { pid_t pid; pid = (pid_t) client_data.i; if ( kill( pid, SIGINT ) == 0 ) { syslog( LOG_ERR, "killed CGI process %d", pid ); /* In case this isn't enough, schedule an uncatchable kill. */ if ( tmr_create( nowP, cgi_kill2, client_data, 5 * 1000L, 0 ) == (Timer*) 0 ) { syslog( LOG_CRIT, "tmr_create(cgi_kill2) failed" ); exit( 1 ); } } } #endif /* CGI_TIMELIMIT */ #ifdef GENERATE_INDEXES /* qsort comparison routine - declared old-style on purpose, for portability. */ static int name_compare( a, b ) char** a; char** b; { return strcmp( *a, *b ); } static int ls( httpd_conn* hc ) { DIR* dirp; struct dirent* de; int namlen; static int maxnames = 0; int nnames; static char* names; static char** nameptrs; static char* name; static size_t maxname = 0; static char* rname; static size_t maxrname = 0; static char* encrname; static size_t maxencrname = 0; FILE* fp; int i, r; struct stat sb; struct stat lsb; char modestr[20]; char* linkprefix; char link[MAXPATHLEN+1]; int linklen; char* fileclass; time_t now; char* timestr; ClientData client_data; dirp = opendir( hc->expnfilename ); if ( dirp == (DIR*) 0 ) { syslog( LOG_ERR, "opendir %.80s - %m", hc->expnfilename ); httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl ); return -1; } if ( hc->method == METHOD_HEAD ) { closedir( dirp ); send_mime( hc, 200, ok200title, "", "", "text/html; charset=%s", (off_t) -1, hc->sb.st_mtime ); } else if ( hc->method == METHOD_GET ) { if ( hc->hs->cgi_limit != 0 && hc->hs->cgi_count >= hc->hs->cgi_limit ) { closedir( dirp ); httpd_send_err( hc, 503, httpd_err503title, "", httpd_err503form, hc->encodedurl ); return -1; } ++hc->hs->cgi_count; r = fork( ); if ( r < 0 ) { syslog( LOG_ERR, "fork - %m" ); closedir( dirp ); httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); return -1; } if ( r == 0 ) { /* Child process. */ sub_process = 1; httpd_unlisten( hc->hs ); send_mime( hc, 200, ok200title, "", "", "text/html; charset=%s", (off_t) -1, hc->sb.st_mtime ); httpd_write_response( hc ); #ifdef CGI_NICE /* Set priority. */ (void) nice( CGI_NICE ); #endif /* CGI_NICE */ /* Open a stdio stream so that we can use fprintf, which is more ** efficient than a bunch of separate write()s. We don't have ** to worry about double closes or file descriptor leaks cause ** we're in a subprocess. */ fp = fdopen( hc->conn_fd, "w" ); if ( fp == (FILE*) 0 ) { syslog( LOG_ERR, "fdopen - %m" ); httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); httpd_write_response( hc ); closedir( dirp ); exit( 1 ); } (void) fprintf( fp, "\ <HTML>\n\ <HEAD><TITLE>Index of %.80s</TITLE></HEAD>\n\ <BODY BGCOLOR=\"#99cc99\" TEXT=\"#000000\" LINK=\"#2020ff\" VLINK=\"#4040cc\">\n\ <H2>Index of %.80s</H2>\n\ <PRE>\n\ mode links bytes last-changed name\n\ <HR>", hc->encodedurl, hc->encodedurl ); /* Read in names. */ nnames = 0; while ( ( de = readdir( dirp ) ) != 0 ) /* dirent or direct */ { if ( nnames >= maxnames ) { if ( maxnames == 0 ) { maxnames = 100; names = NEW( char, maxnames * ( MAXPATHLEN + 1 ) ); nameptrs = NEW( char*, maxnames ); } else { maxnames *= 2; names = RENEW( names, char, maxnames * ( MAXPATHLEN + 1 ) ); nameptrs = RENEW( nameptrs, char*, maxnames ); } if ( names == (char*) 0 || nameptrs == (char**) 0 ) { syslog( LOG_ERR, "out of memory reallocating directory names" ); exit( 1 ); } for ( i = 0; i < maxnames; ++i ) nameptrs[i] = &names[i * ( MAXPATHLEN + 1 )]; } namlen = NAMLEN(de); (void) strncpy( nameptrs[nnames], de->d_name, namlen ); nameptrs[nnames][namlen] = '\0'; ++nnames; } closedir( dirp ); /* Sort the names. */ qsort( nameptrs, nnames, sizeof(*nameptrs), name_compare ); /* Generate output. */ for ( i = 0; i < nnames; ++i ) { httpd_realloc_str( &name, &maxname, strlen( hc->expnfilename ) + 1 + strlen( nameptrs[i] ) ); httpd_realloc_str( &rname, &maxrname, strlen( hc->origfilename ) + 1 + strlen( nameptrs[i] ) ); if ( hc->expnfilename[0] == '\0' || strcmp( hc->expnfilename, "." ) == 0 ) { (void) strcpy( name, nameptrs[i] ); (void) strcpy( rname, nameptrs[i] ); } else { (void) my_snprintf( name, maxname, "%s/%s", hc->expnfilename, nameptrs[i] ); if ( strcmp( hc->origfilename, "." ) == 0 ) (void) my_snprintf( rname, maxrname, "%s", nameptrs[i] ); else (void) my_snprintf( rname, maxrname, "%s%s", hc->origfilename, nameptrs[i] ); } httpd_realloc_str( &encrname, &maxencrname, 3 * strlen( rname ) + 1 ); strencode( encrname, maxencrname, rname ); if ( stat( name, &sb ) < 0 || lstat( name, &lsb ) < 0 ) continue; linkprefix = ""; link[0] = '\0'; /* Break down mode word. First the file type. */ switch ( lsb.st_mode & S_IFMT ) { case S_IFIFO: modestr[0] = 'p'; break; case S_IFCHR: modestr[0] = 'c'; break; case S_IFDIR: modestr[0] = 'd'; break; case S_IFBLK: modestr[0] = 'b'; break; case S_IFREG: modestr[0] = '-'; break; case S_IFSOCK: modestr[0] = 's'; break; case S_IFLNK: modestr[0] = 'l'; linklen = readlink( name, link, sizeof(link) - 1 ); if ( linklen != -1 ) { link[linklen] = '\0'; linkprefix = " -&gt; "; } break; default: modestr[0] = '?'; break; } /* Now the world permissions. Owner and group permissions ** are not of interest to web clients. */ modestr[1] = ( lsb.st_mode & S_IROTH ) ? 'r' : '-'; modestr[2] = ( lsb.st_mode & S_IWOTH ) ? 'w' : '-'; modestr[3] = ( lsb.st_mode & S_IXOTH ) ? 'x' : '-'; modestr[4] = '\0'; /* We also leave out the owner and group name, they are ** also not of interest to web clients. Plus if we're ** running under chroot(), they would require a copy ** of /etc/passwd and /etc/group, which we want to avoid. */ /* Get time string. */ now = time( (time_t*) 0 ); timestr = ctime( &lsb.st_mtime ); timestr[ 0] = timestr[ 4]; timestr[ 1] = timestr[ 5]; timestr[ 2] = timestr[ 6]; timestr[ 3] = ' '; timestr[ 4] = timestr[ 8]; timestr[ 5] = timestr[ 9]; timestr[ 6] = ' '; if ( now - lsb.st_mtime > 60*60*24*182 ) /* 1/2 year */ { timestr[ 7] = ' '; timestr[ 8] = timestr[20]; timestr[ 9] = timestr[21]; timestr[10] = timestr[22]; timestr[11] = timestr[23]; } else { timestr[ 7] = timestr[11]; timestr[ 8] = timestr[12]; timestr[ 9] = ':'; timestr[10] = timestr[14]; timestr[11] = timestr[15]; } timestr[12] = '\0'; /* The ls -F file class. */ switch ( sb.st_mode & S_IFMT ) { case S_IFDIR: fileclass = "/"; break; case S_IFSOCK: fileclass = "="; break; case S_IFLNK: fileclass = "@"; break; default: fileclass = ( sb.st_mode & S_IXOTH ) ? "*" : ""; break; } /* And print. */ (void) fprintf( fp, "%s %3ld %10lld %s <A HREF=\"/%.500s%s\">%.80s</A>%s%s%s\n", modestr, (long) lsb.st_nlink, (int64_t) lsb.st_size, timestr, encrname, S_ISDIR(sb.st_mode) ? "/" : "", nameptrs[i], linkprefix, link, fileclass ); } (void) fprintf( fp, "</PRE></BODY>\n</HTML>\n" ); (void) fclose( fp ); exit( 0 ); } /* Parent process. */ closedir( dirp ); syslog( LOG_INFO, "spawned indexing process %d for directory '%.200s'", r, hc->expnfilename ); #ifdef CGI_TIMELIMIT /* Schedule a kill for the child process, in case it runs too long */ client_data.i = r; if ( tmr_create( (struct timeval*) 0, cgi_kill, client_data, CGI_TIMELIMIT * 1000L, 0 ) == (Timer*) 0 ) { syslog( LOG_CRIT, "tmr_create(cgi_kill ls) failed" ); exit( 1 ); } #endif /* CGI_TIMELIMIT */ hc->status = 200; hc->bytes_sent = CGI_BYTECOUNT; hc->should_linger = 0; } else { closedir( dirp ); httpd_send_err( hc, 501, err501title, "", err501form, httpd_method_str( hc->method ) ); return -1; } return 0; } #endif /* GENERATE_INDEXES */ static char* build_env( char* fmt, char* arg ) { char* cp; size_t size; static char* buf; static size_t maxbuf = 0; size = strlen( fmt ) + strlen( arg ); if ( size > maxbuf ) httpd_realloc_str( &buf, &maxbuf, size ); (void) my_snprintf( buf, maxbuf, fmt, arg ); cp = strdup( buf ); if ( cp == (char*) 0 ) { syslog( LOG_ERR, "out of memory copying environment variable" ); exit( 1 ); } return cp; } #ifdef SERVER_NAME_LIST static char* hostname_map( char* hostname ) { int len, n; static char* list[] = { SERVER_NAME_LIST }; len = strlen( hostname ); for ( n = sizeof(list) / sizeof(*list) - 1; n >= 0; --n ) if ( strncasecmp( hostname, list[n], len ) == 0 ) if ( list[n][len] == '/' ) /* check in case of a substring match */ return &list[n][len + 1]; return (char*) 0; } #endif /* SERVER_NAME_LIST */ /* Set up environment variables. Be real careful here to avoid ** letting malicious clients overrun a buffer. We don't have ** to worry about freeing stuff since we're a sub-process. */ static char** make_envp( httpd_conn* hc ) { static char* envp[50]; int envn; char* cp; char buf[256]; envn = 0; envp[envn++] = build_env( "PATH=%s", CGI_PATH ); #ifdef CGI_LD_LIBRARY_PATH envp[envn++] = build_env( "LD_LIBRARY_PATH=%s", CGI_LD_LIBRARY_PATH ); #endif /* CGI_LD_LIBRARY_PATH */ envp[envn++] = build_env( "SERVER_SOFTWARE=%s", SERVER_SOFTWARE ); /* If vhosting, use that server-name here. */ if ( hc->hs->vhost && hc->hostname != (char*) 0 ) cp = hc->hostname; else cp = hc->hs->server_hostname; if ( cp != (char*) 0 ) envp[envn++] = build_env( "SERVER_NAME=%s", cp ); envp[envn++] = "GATEWAY_INTERFACE=CGI/1.1"; envp[envn++] = build_env("SERVER_PROTOCOL=%s", hc->protocol); (void) my_snprintf( buf, sizeof(buf), "%d", (int) hc->hs->port ); envp[envn++] = build_env( "SERVER_PORT=%s", buf ); envp[envn++] = build_env( "REQUEST_METHOD=%s", httpd_method_str( hc->method ) ); if ( hc->pathinfo[0] != '\0' ) { char* cp2; size_t l; envp[envn++] = build_env( "PATH_INFO=/%s", hc->pathinfo ); l = strlen( hc->hs->cwd ) + strlen( hc->pathinfo ) + 1; cp2 = NEW( char, l ); if ( cp2 != (char*) 0 ) { (void) my_snprintf( cp2, l, "%s%s", hc->hs->cwd, hc->pathinfo ); envp[envn++] = build_env( "PATH_TRANSLATED=%s", cp2 ); } } envp[envn++] = build_env( "SCRIPT_NAME=/%s", strcmp( hc->origfilename, "." ) == 0 ? "" : hc->origfilename ); if ( hc->query[0] != '\0') envp[envn++] = build_env( "QUERY_STRING=%s", hc->query ); envp[envn++] = build_env( "REMOTE_ADDR=%s", httpd_ntoa( &hc->client_addr ) ); if ( hc->referer[0] != '\0' ) envp[envn++] = build_env( "HTTP_REFERER=%s", hc->referer ); if ( hc->useragent[0] != '\0' ) envp[envn++] = build_env( "HTTP_USER_AGENT=%s", hc->useragent ); if ( hc->accept[0] != '\0' ) envp[envn++] = build_env( "HTTP_ACCEPT=%s", hc->accept ); if ( hc->accepte[0] != '\0' ) envp[envn++] = build_env( "HTTP_ACCEPT_ENCODING=%s", hc->accepte ); if ( hc->acceptl[0] != '\0' ) envp[envn++] = build_env( "HTTP_ACCEPT_LANGUAGE=%s", hc->acceptl ); if ( hc->cookie[0] != '\0' ) envp[envn++] = build_env( "HTTP_COOKIE=%s", hc->cookie ); if ( hc->contenttype[0] != '\0' ) envp[envn++] = build_env( "CONTENT_TYPE=%s", hc->contenttype ); if ( hc->hdrhost[0] != '\0' ) envp[envn++] = build_env( "HTTP_HOST=%s", hc->hdrhost ); if ( hc->contentlength != -1 ) { (void) my_snprintf( buf, sizeof(buf), "%lu", (unsigned long) hc->contentlength ); envp[envn++] = build_env( "CONTENT_LENGTH=%s", buf ); } if ( hc->remoteuser[0] != '\0' ) envp[envn++] = build_env( "REMOTE_USER=%s", hc->remoteuser ); if ( hc->authorization[0] != '\0' ) envp[envn++] = build_env( "AUTH_TYPE=%s", "Basic" ); /* We only support Basic auth at the moment. */ if ( getenv( "TZ" ) != (char*) 0 ) envp[envn++] = build_env( "TZ=%s", getenv( "TZ" ) ); envp[envn++] = build_env( "CGI_PATTERN=%s", hc->hs->cgi_pattern ); envp[envn] = (char*) 0; return envp; } /* Set up argument vector. Again, we don't have to worry about freeing stuff ** since we're a sub-process. This gets done after make_envp() because we ** scribble on hc->query. */ static char** make_argp( httpd_conn* hc ) { char** argp; int argn; char* cp1; char* cp2; /* By allocating an arg slot for every character in the query, plus ** one for the filename and one for the NULL, we are guaranteed to ** have enough. We could actually use strlen/2. */ argp = NEW( char*, strlen( hc->query ) + 2 ); if ( argp == (char**) 0 ) return (char**) 0; argp[0] = strrchr( hc->expnfilename, '/' ); if ( argp[0] != (char*) 0 ) ++argp[0]; else argp[0] = hc->expnfilename; argn = 1; /* According to the CGI spec at http://hoohoo.ncsa.uiuc.edu/cgi/cl.html, ** "The server should search the query information for a non-encoded = ** character to determine if the command line is to be used, if it finds ** one, the command line is not to be used." */ if ( strchr( hc->query, '=' ) == (char*) 0 ) { for ( cp1 = cp2 = hc->query; *cp2 != '\0'; ++cp2 ) { if ( *cp2 == '+' ) { *cp2 = '\0'; strdecode( cp1, cp1 ); argp[argn++] = cp1; cp1 = cp2 + 1; } } if ( cp2 != cp1 ) { strdecode( cp1, cp1 ); argp[argn++] = cp1; } } argp[argn] = (char*) 0; return argp; } /* This routine is used only for POST requests. It reads the data ** from the request and sends it to the child process. The only reason ** we need to do it this way instead of just letting the child read ** directly is that we have already read part of the data into our ** buffer. */ static void cgi_interpose_input( httpd_conn* hc, int wfd ) { size_t c; ssize_t r; char buf[1024]; c = hc->read_idx - hc->checked_idx; if ( c > 0 ) { if ( httpd_write_fully( wfd, &(hc->read_buf[hc->checked_idx]), c ) != c ) return; } while ( c < hc->contentlength ) { r = read( hc->conn_fd, buf, MIN( sizeof(buf), hc->contentlength - c ) ); if ( r < 0 && ( errno == EINTR || errno == EAGAIN ) ) { sleep( 1 ); continue; } if ( r <= 0 ) return; if ( httpd_write_fully( wfd, buf, r ) != r ) return; c += r; } post_post_garbage_hack( hc ); } /* Special hack to deal with broken browsers that send a LF or CRLF ** after POST data, causing TCP resets - we just read and discard up ** to 2 bytes. Unfortunately this doesn't fix the problem for CGIs ** which avoid the interposer process due to their POST data being ** short. Creating an interposer process for all POST CGIs is ** unacceptably expensive. The eventual fix will come when interposing ** gets integrated into the main loop as a tasklet instead of a process. */ static void post_post_garbage_hack( httpd_conn* hc ) { char buf[2]; /* If we are in a sub-process, turn on no-delay mode in case we ** previously cleared it. */ if ( sub_process ) httpd_set_ndelay( hc->conn_fd ); /* And read up to 2 bytes. */ (void) read( hc->conn_fd, buf, sizeof(buf) ); } /* This routine is used for parsed-header CGIs. The idea here is that the ** CGI can return special headers such as "Status:" and "Location:" which ** change the return status of the response. Since the return status has to ** be the very first line written out, we have to accumulate all the headers ** and check for the special ones before writing the status. Then we write ** out the saved headers and proceed to echo the rest of the response. */ static void cgi_interpose_output( httpd_conn* hc, int rfd ) { int r; char buf[1024]; size_t headers_size, headers_len; char* headers; char* br; int status; char* title; char* cp; /* Make sure the connection is in blocking mode. It should already ** be blocking, but we might as well be sure. */ httpd_clear_ndelay( hc->conn_fd ); /* Slurp in all headers. */ headers_size = 0; httpd_realloc_str( &headers, &headers_size, 500 ); headers_len = 0; for (;;) { r = read( rfd, buf, sizeof(buf) ); if ( r < 0 && ( errno == EINTR || errno == EAGAIN ) ) { sleep( 1 ); continue; } if ( r <= 0 ) { br = &(headers[headers_len]); break; } httpd_realloc_str( &headers, &headers_size, headers_len + r ); (void) memmove( &(headers[headers_len]), buf, r ); headers_len += r; headers[headers_len] = '\0'; if ( ( br = strstr( headers, "\015\012\015\012" ) ) != (char*) 0 || ( br = strstr( headers, "\012\012" ) ) != (char*) 0 ) break; } /* If there were no headers, bail. */ if ( headers[0] == '\0' ) return; /* Figure out the status. Look for a Status: or Location: header; ** else if there's an HTTP header line, get it from there; else ** default to 200. */ status = 200; if ( strncmp( headers, "HTTP/", 5 ) == 0 ) { cp = headers; cp += strcspn( cp, " \t" ); status = atoi( cp ); } if ( ( cp = strstr( headers, "Status:" ) ) != (char*) 0 && cp < br && ( cp == headers || *(cp-1) == '\012' ) ) { cp += 7; cp += strspn( cp, " \t" ); status = atoi( cp ); } else if ( ( cp = strstr( headers, "Location:" ) ) != (char*) 0 && cp < br && ( cp == headers || *(cp-1) == '\012' ) ) status = 302; /* Write the status line. */ switch ( status ) { case 200: title = ok200title; break; case 302: title = err302title; break; case 304: title = err304title; break; case 400: title = httpd_err400title; break; #ifdef AUTH_FILE case 401: title = err401title; break; #endif /* AUTH_FILE */ case 403: title = err403title; break; case 404: title = err404title; break; case 408: title = httpd_err408title; break; case 500: title = err500title; break; case 501: title = err501title; break; case 503: title = httpd_err503title; break; default: title = "Something"; break; } (void) my_snprintf( buf, sizeof(buf), "HTTP/1.0 %d %s\015\012", status, title ); (void) httpd_write_fully( hc->conn_fd, buf, strlen( buf ) ); /* Write the saved headers. */ (void) httpd_write_fully( hc->conn_fd, headers, headers_len ); /* Echo the rest of the output. */ for (;;) { r = read( rfd, buf, sizeof(buf) ); if ( r < 0 && ( errno == EINTR || errno == EAGAIN ) ) { sleep( 1 ); continue; } if ( r <= 0 ) break; if ( httpd_write_fully( hc->conn_fd, buf, r ) != r ) break; } shutdown( hc->conn_fd, SHUT_WR ); } /* CGI child process. */ static void cgi_child( httpd_conn* hc ) { int r; char** argp; char** envp; char* binary; char* directory; /* Unset close-on-exec flag for this socket. This actually shouldn't ** be necessary, according to POSIX a dup()'d file descriptor does ** *not* inherit the close-on-exec flag, its flag is always clear. ** However, Linux messes this up and does copy the flag to the ** dup()'d descriptor, so we have to clear it. This could be ** ifdeffed for Linux only. */ (void) fcntl( hc->conn_fd, F_SETFD, 0 ); /* Close the syslog descriptor so that the CGI program can't ** mess with it. All other open descriptors should be either ** the listen socket(s), sockets from accept(), or the file-logging ** fd, and all of those are set to close-on-exec, so we don't ** have to close anything else. */ closelog(); /* If the socket happens to be using one of the stdin/stdout/stderr ** descriptors, move it to another descriptor so that the dup2 calls ** below don't screw things up. We arbitrarily pick fd 3 - if there ** was already something on it, we clobber it, but that doesn't matter ** since at this point the only fd of interest is the connection. ** All others will be closed on exec. */ if ( hc->conn_fd == STDIN_FILENO || hc->conn_fd == STDOUT_FILENO || hc->conn_fd == STDERR_FILENO ) { int newfd = dup2( hc->conn_fd, STDERR_FILENO + 1 ); if ( newfd >= 0 ) hc->conn_fd = newfd; /* If the dup2 fails, shrug. We'll just take our chances. ** Shouldn't happen though. */ } /* Make the environment vector. */ envp = make_envp( hc ); /* Make the argument vector. */ argp = make_argp( hc ); /* Set up stdin. For POSTs we may have to set up a pipe from an ** interposer process, depending on if we've read some of the data ** into our buffer. */ if ( hc->method == METHOD_POST && hc->read_idx > hc->checked_idx ) { int p[2]; if ( pipe( p ) < 0 ) { syslog( LOG_ERR, "pipe - %m" ); httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); httpd_write_response( hc ); exit( 1 ); } r = fork( ); if ( r < 0 ) { syslog( LOG_ERR, "fork - %m" ); httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); httpd_write_response( hc ); exit( 1 ); } if ( r == 0 ) { /* Interposer process. */ sub_process = 1; (void) close( p[0] ); cgi_interpose_input( hc, p[1] ); exit( 0 ); } /* Need to schedule a kill for process r; but in the main process! */ (void) close( p[1] ); if ( p[0] != STDIN_FILENO ) { (void) dup2( p[0], STDIN_FILENO ); (void) close( p[0] ); } } else { /* Otherwise, the request socket is stdin. */ if ( hc->conn_fd != STDIN_FILENO ) (void) dup2( hc->conn_fd, STDIN_FILENO ); } /* Set up stdout/stderr. If we're doing CGI header parsing, ** we need an output interposer too. */ if ( strncmp( argp[0], "nph-", 4 ) != 0 && hc->mime_flag ) { int p[2]; if ( pipe( p ) < 0 ) { syslog( LOG_ERR, "pipe - %m" ); httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); httpd_write_response( hc ); exit( 1 ); } r = fork( ); if ( r < 0 ) { syslog( LOG_ERR, "fork - %m" ); httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); httpd_write_response( hc ); exit( 1 ); } if ( r == 0 ) { /* Interposer process. */ sub_process = 1; (void) close( p[1] ); cgi_interpose_output( hc, p[0] ); exit( 0 ); } /* Need to schedule a kill for process r; but in the main process! */ (void) close( p[0] ); if ( p[1] != STDOUT_FILENO ) (void) dup2( p[1], STDOUT_FILENO ); if ( p[1] != STDERR_FILENO ) (void) dup2( p[1], STDERR_FILENO ); if ( p[1] != STDOUT_FILENO && p[1] != STDERR_FILENO ) (void) close( p[1] ); } else { /* Otherwise, the request socket is stdout/stderr. */ if ( hc->conn_fd != STDOUT_FILENO ) (void) dup2( hc->conn_fd, STDOUT_FILENO ); if ( hc->conn_fd != STDERR_FILENO ) (void) dup2( hc->conn_fd, STDERR_FILENO ); } /* At this point we would like to set close-on-exec again for hc->conn_fd ** (see previous comments on Linux's broken behavior re: close-on-exec ** and dup.) Unfortunately there seems to be another Linux problem, or ** perhaps a different aspect of the same problem - if we do this ** close-on-exec in Linux, the socket stays open but stderr gets ** closed - the last fd duped from the socket. What a mess. So we'll ** just leave the socket as is, which under other OSs means an extra ** file descriptor gets passed to the child process. Since the child ** probably already has that file open via stdin stdout and/or stderr, ** this is not a problem. */ /* (void) fcntl( hc->conn_fd, F_SETFD, 1 ); */ #ifdef CGI_NICE /* Set priority. */ (void) nice( CGI_NICE ); #endif /* CGI_NICE */ /* Split the program into directory and binary, so we can chdir() ** to the program's own directory. This isn't in the CGI 1.1 ** spec, but it's what other HTTP servers do. */ directory = strdup( hc->expnfilename ); if ( directory == (char*) 0 ) binary = hc->expnfilename; /* ignore errors */ else { binary = strrchr( directory, '/' ); if ( binary == (char*) 0 ) binary = hc->expnfilename; else { *binary++ = '\0'; (void) chdir( directory ); /* ignore errors */ } } /* Default behavior for SIGPIPE. */ #ifdef HAVE_SIGSET (void) sigset( SIGPIPE, SIG_DFL ); #else /* HAVE_SIGSET */ (void) signal( SIGPIPE, SIG_DFL ); #endif /* HAVE_SIGSET */ /* Run the program. */ (void) execve( binary, argp, envp ); /* Something went wrong. */ syslog( LOG_ERR, "execve %.80s - %m", hc->expnfilename ); httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); httpd_write_response( hc ); exit( 1 ); } static int cgi( httpd_conn* hc ) { int r; ClientData client_data; if ( hc->method == METHOD_GET || hc->method == METHOD_POST ) { if ( hc->hs->cgi_limit != 0 && hc->hs->cgi_count >= hc->hs->cgi_limit ) { httpd_send_err( hc, 503, httpd_err503title, "", httpd_err503form, hc->encodedurl ); return -1; } ++hc->hs->cgi_count; httpd_clear_ndelay( hc->conn_fd ); r = fork( ); if ( r < 0 ) { syslog( LOG_ERR, "fork - %m" ); httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); return -1; } if ( r == 0 ) { /* Child process. */ sub_process = 1; httpd_unlisten( hc->hs ); cgi_child( hc ); } /* Parent process. */ syslog( LOG_INFO, "spawned CGI process %d for file '%.200s'", r, hc->expnfilename ); #ifdef CGI_TIMELIMIT /* Schedule a kill for the child process, in case it runs too long */ client_data.i = r; if ( tmr_create( (struct timeval*) 0, cgi_kill, client_data, CGI_TIMELIMIT * 1000L, 0 ) == (Timer*) 0 ) { syslog( LOG_CRIT, "tmr_create(cgi_kill child) failed" ); exit( 1 ); } #endif /* CGI_TIMELIMIT */ hc->status = 200; hc->bytes_sent = CGI_BYTECOUNT; hc->should_linger = 0; } else { httpd_send_err( hc, 501, err501title, "", err501form, httpd_method_str( hc->method ) ); return -1; } return 0; } static int really_start_request( httpd_conn* hc, struct timeval* nowP ) { static char* indexname; static size_t maxindexname = 0; static const char* index_names[] = { INDEX_NAMES }; int i; #ifdef AUTH_FILE static char* dirname; static size_t maxdirname = 0; #endif /* AUTH_FILE */ size_t expnlen, indxlen; char* cp; char* pi; expnlen = strlen( hc->expnfilename ); if ( hc->method != METHOD_GET && hc->method != METHOD_HEAD && hc->method != METHOD_POST ) { httpd_send_err( hc, 501, err501title, "", err501form, httpd_method_str( hc->method ) ); return -1; } /* Stat the file. */ if ( stat( hc->expnfilename, &hc->sb ) < 0 ) { httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); return -1; } /* Is it world-readable or world-executable? We check explicitly instead ** of just trying to open it, so that no one ever gets surprised by ** a file that's not set world-readable and yet somehow is ** readable by the HTTP server and therefore the *whole* world. */ if ( ! ( hc->sb.st_mode & ( S_IROTH | S_IXOTH ) ) ) { syslog( LOG_INFO, "%.80s URL \"%.80s\" resolves to a non world-readable file", httpd_ntoa( &hc->client_addr ), hc->encodedurl ); httpd_send_err( hc, 403, err403title, "", ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file that is not world-readable.\n" ), hc->encodedurl ); return -1; } /* Is it a directory? */ if ( S_ISDIR(hc->sb.st_mode) ) { /* If there's pathinfo, it's just a non-existent file. */ if ( hc->pathinfo[0] != '\0' ) { httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl ); return -1; } /* Special handling for directory URLs that don't end in a slash. ** We send back an explicit redirect with the slash, because ** otherwise many clients can't build relative URLs properly. */ if ( strcmp( hc->origfilename, "" ) != 0 && strcmp( hc->origfilename, "." ) != 0 && hc->origfilename[strlen( hc->origfilename ) - 1] != '/' ) { send_dirredirect( hc ); return -1; } /* Check for an index file. */ for ( i = 0; i < sizeof(index_names) / sizeof(char*); ++i ) { httpd_realloc_str( &indexname, &maxindexname, expnlen + 1 + strlen( index_names[i] ) ); (void) strcpy( indexname, hc->expnfilename ); indxlen = strlen( indexname ); if ( indxlen == 0 || indexname[indxlen - 1] != '/' ) (void) strcat( indexname, "/" ); if ( strcmp( indexname, "./" ) == 0 ) indexname[0] = '\0'; (void) strcat( indexname, index_names[i] ); if ( stat( indexname, &hc->sb ) >= 0 ) goto got_one; } /* Nope, no index file, so it's an actual directory request. */ #ifdef GENERATE_INDEXES /* Directories must be readable for indexing. */ if ( ! ( hc->sb.st_mode & S_IROTH ) ) { syslog( LOG_INFO, "%.80s URL \"%.80s\" tried to index a directory with indexing disabled", httpd_ntoa( &hc->client_addr ), hc->encodedurl ); httpd_send_err( hc, 403, err403title, "", ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a directory that has indexing disabled.\n" ), hc->encodedurl ); return -1; } #ifdef AUTH_FILE /* Check authorization for this directory. */ if ( auth_check( hc, hc->expnfilename ) == -1 ) return -1; #endif /* AUTH_FILE */ /* Referer check. */ if ( ! check_referer( hc ) ) return -1; /* Ok, generate an index. */ return ls( hc ); #else /* GENERATE_INDEXES */ syslog( LOG_INFO, "%.80s URL \"%.80s\" tried to index a directory", httpd_ntoa( &hc->client_addr ), hc->encodedurl ); httpd_send_err( hc, 403, err403title, "", ERROR_FORM( err403form, "The requested URL '%.80s' is a directory, and directory indexing is disabled on this server.\n" ), hc->encodedurl ); return -1; #endif /* GENERATE_INDEXES */ got_one: ; /* Got an index file. Expand symlinks again. More pathinfo means ** something went wrong. */ cp = expand_symlinks( indexname, &pi, hc->hs->no_symlink_check, hc->tildemapped ); if ( cp == (char*) 0 || pi[0] != '\0' ) { httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); return -1; } expnlen = strlen( cp ); httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, expnlen ); (void) strcpy( hc->expnfilename, cp ); /* Now, is the index version world-readable or world-executable? */ if ( ! ( hc->sb.st_mode & ( S_IROTH | S_IXOTH ) ) ) { syslog( LOG_INFO, "%.80s URL \"%.80s\" resolves to a non-world-readable index file", httpd_ntoa( &hc->client_addr ), hc->encodedurl ); httpd_send_err( hc, 403, err403title, "", ERROR_FORM( err403form, "The requested URL '%.80s' resolves to an index file that is not world-readable.\n" ), hc->encodedurl ); return -1; } } #ifdef AUTH_FILE /* Check authorization for this directory. */ httpd_realloc_str( &dirname, &maxdirname, expnlen ); (void) strcpy( dirname, hc->expnfilename ); cp = strrchr( dirname, '/' ); if ( cp == (char*) 0 ) (void) strcpy( dirname, "." ); else *cp = '\0'; if ( auth_check( hc, dirname ) == -1 ) return -1; /* Check if the filename is the AUTH_FILE itself - that's verboten. */ if ( expnlen == sizeof(AUTH_FILE) - 1 ) { if ( strcmp( hc->expnfilename, AUTH_FILE ) == 0 ) { syslog( LOG_NOTICE, "%.80s URL \"%.80s\" tried to retrieve an auth file", httpd_ntoa( &hc->client_addr ), hc->encodedurl ); httpd_send_err( hc, 403, err403title, "", ERROR_FORM( err403form, "The requested URL '%.80s' is an authorization file, retrieving it is not permitted.\n" ), hc->encodedurl ); return -1; } } else if ( expnlen >= sizeof(AUTH_FILE) && strcmp( &(hc->expnfilename[expnlen - sizeof(AUTH_FILE) + 1]), AUTH_FILE ) == 0 && hc->expnfilename[expnlen - sizeof(AUTH_FILE)] == '/' ) { syslog( LOG_NOTICE, "%.80s URL \"%.80s\" tried to retrieve an auth file", httpd_ntoa( &hc->client_addr ), hc->encodedurl ); httpd_send_err( hc, 403, err403title, "", ERROR_FORM( err403form, "The requested URL '%.80s' is an authorization file, retrieving it is not permitted.\n" ), hc->encodedurl ); return -1; } #endif /* AUTH_FILE */ /* Referer check. */ if ( ! check_referer( hc ) ) return -1; /* Is it world-executable and in the CGI area? */ if ( hc->hs->cgi_pattern != (char*) 0 && ( hc->sb.st_mode & S_IXOTH ) && match( hc->hs->cgi_pattern, hc->expnfilename ) ) return cgi( hc ); /* It's not CGI. If it's executable or there's pathinfo, someone's ** trying to either serve or run a non-CGI file as CGI. Either case ** is prohibited. */ if ( hc->sb.st_mode & S_IXOTH ) { syslog( LOG_NOTICE, "%.80s URL \"%.80s\" is executable but isn't CGI", httpd_ntoa( &hc->client_addr ), hc->encodedurl ); httpd_send_err( hc, 403, err403title, "", ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file which is marked executable but is not a CGI file; retrieving it is forbidden.\n" ), hc->encodedurl ); return -1; } if ( hc->pathinfo[0] != '\0' ) { syslog( LOG_INFO, "%.80s URL \"%.80s\" has pathinfo but isn't CGI", httpd_ntoa( &hc->client_addr ), hc->encodedurl ); httpd_send_err( hc, 403, err403title, "", ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file plus CGI-style pathinfo, but the file is not a valid CGI file.\n" ), hc->encodedurl ); return -1; } /* Fill in last_byte_index, if necessary. */ if ( hc->got_range && ( hc->last_byte_index == -1 || hc->last_byte_index >= hc->sb.st_size ) ) hc->last_byte_index = hc->sb.st_size - 1; figure_mime( hc ); if ( hc->method == METHOD_HEAD ) { send_mime( hc, 200, ok200title, hc->encodings, "", hc->type, hc->sb.st_size, hc->sb.st_mtime ); } else if ( hc->if_modified_since != (time_t) -1 && hc->if_modified_since >= hc->sb.st_mtime ) { send_mime( hc, 304, err304title, hc->encodings, "", hc->type, (off_t) -1, hc->sb.st_mtime ); } else { hc->file_address = mmc_map( hc->expnfilename, &(hc->sb), nowP ); if ( hc->file_address == (char*) 0 ) { httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl ); return -1; } send_mime( hc, 200, ok200title, hc->encodings, "", hc->type, hc->sb.st_size, hc->sb.st_mtime ); } return 0; } int httpd_start_request( httpd_conn* hc, struct timeval* nowP ) { int r; /* Really start the request. */ r = really_start_request( hc, nowP ); /* And return the status. */ return r; } static void make_log_entry( httpd_conn* hc, struct timeval* nowP ) { char* ru; char url[305]; char bytes[40]; if ( hc->hs->no_log ) return; /* This is straight CERN Combined Log Format - the only tweak ** being that if we're using syslog() we leave out the date, because ** syslogd puts it in. The included syslogtocern script turns the ** results into true CERN format. */ /* Format remote user. */ if ( hc->remoteuser[0] != '\0' ) ru = hc->remoteuser; else ru = "-"; /* If we're vhosting, prepend the hostname to the url. This is ** a little weird, perhaps writing separate log files for ** each vhost would make more sense. */ if ( hc->hs->vhost && ! hc->tildemapped ) (void) my_snprintf( url, sizeof(url), "/%.100s%.200s", hc->hostname == (char*) 0 ? hc->hs->server_hostname : hc->hostname, hc->encodedurl ); else (void) my_snprintf( url, sizeof(url), "%.200s", hc->encodedurl ); /* Format the bytes. */ if ( hc->bytes_sent >= 0 ) (void) my_snprintf( bytes, sizeof(bytes), "%lld", (int64_t) hc->bytes_sent ); else (void) strcpy( bytes, "-" ); /* Logfile or syslog? */ if ( hc->hs->logfp != (FILE*) 0 ) { time_t now; struct tm* t; const char* cernfmt_nozone = "%d/%b/%Y:%H:%M:%S"; char date_nozone[100]; int zone; char sign; char date[100]; /* Get the current time, if necessary. */ if ( nowP != (struct timeval*) 0 ) now = nowP->tv_sec; else now = time( (time_t*) 0 ); /* Format the time, forcing a numeric timezone (some log analyzers ** are stoooopid about this). */ t = localtime( &now ); (void) strftime( date_nozone, sizeof(date_nozone), cernfmt_nozone, t ); zone = t->tm_gmtoff / 60L; if ( zone >= 0 ) sign = '+'; else { sign = '-'; zone = -zone; } zone = ( zone / 60 ) * 100 + zone % 60; (void) my_snprintf( date, sizeof(date), "%s %c%04d", date_nozone, sign, zone ); /* And write the log entry. */ (void) fprintf( hc->hs->logfp, "%.80s - %.80s [%s] \"%.80s %.300s %.80s\" %d %s \"%.200s\" \"%.200s\"\n", httpd_ntoa( &hc->client_addr ), ru, date, httpd_method_str( hc->method ), url, hc->protocol, hc->status, bytes, hc->referer, hc->useragent ); #ifdef FLUSH_LOG_EVERY_TIME (void) fflush( hc->hs->logfp ); #endif } else syslog( LOG_INFO, "%.80s - %.80s \"%.80s %.200s %.80s\" %d %s \"%.200s\" \"%.200s\"", httpd_ntoa( &hc->client_addr ), ru, httpd_method_str( hc->method ), url, hc->protocol, hc->status, bytes, hc->referer, hc->useragent ); } /* Returns 1 if ok to serve the url, 0 if not. */ static int check_referer( httpd_conn* hc ) { int r; char* cp; /* Are we doing referer checking at all? */ if ( hc->hs->url_pattern == (char*) 0 ) return 1; r = really_check_referer( hc ); if ( ! r ) { if ( hc->hs->vhost && hc->hostname != (char*) 0 ) cp = hc->hostname; else cp = hc->hs->server_hostname; if ( cp == (char*) 0 ) cp = ""; syslog( LOG_INFO, "%.80s non-local referer \"%.80s%.80s\" \"%.80s\"", httpd_ntoa( &hc->client_addr ), cp, hc->encodedurl, hc->referer ); httpd_send_err( hc, 403, err403title, "", ERROR_FORM( err403form, "You must supply a local referer to get URL '%.80s' from this server.\n" ), hc->encodedurl ); } return r; } /* Returns 1 if ok to serve the url, 0 if not. */ static int really_check_referer( httpd_conn* hc ) { httpd_server* hs; char* cp1; char* cp2; char* cp3; static char* refhost = (char*) 0; static size_t refhost_size = 0; char *lp; hs = hc->hs; /* Check for an empty referer. */ if ( hc->referer == (char*) 0 || hc->referer[0] == '\0' || ( cp1 = strstr( hc->referer, "//" ) ) == (char*) 0 ) { /* Disallow if we require a referer and the url matches. */ if ( hs->no_empty_referers && match( hs->url_pattern, hc->origfilename ) ) return 0; /* Otherwise ok. */ return 1; } /* Extract referer host. */ cp1 += 2; for ( cp2 = cp1; *cp2 != '/' && *cp2 != ':' && *cp2 != '\0'; ++cp2 ) continue; httpd_realloc_str( &refhost, &refhost_size, cp2 - cp1 ); for ( cp3 = refhost; cp1 < cp2; ++cp1, ++cp3 ) if ( isupper(*cp1) ) *cp3 = tolower(*cp1); else *cp3 = *cp1; *cp3 = '\0'; /* Local pattern? */ if ( hs->local_pattern != (char*) 0 ) lp = hs->local_pattern; else { /* No local pattern. What's our hostname? */ if ( ! hs->vhost ) { /* Not vhosting, use the server name. */ lp = hs->server_hostname; if ( lp == (char*) 0 ) /* Couldn't figure out local hostname - give up. */ return 1; } else { /* We are vhosting, use the hostname on this connection. */ lp = hc->hostname; if ( lp == (char*) 0 ) /* Oops, no hostname. Maybe it's an old browser that ** doesn't send a Host: header. We could figure out ** the default hostname for this IP address, but it's ** not worth it for the few requests like this. */ return 1; } } /* If the referer host doesn't match the local host pattern, and ** the filename does match the url pattern, it's an illegal reference. */ if ( ! match( lp, refhost ) && match( hs->url_pattern, hc->origfilename ) ) return 0; /* Otherwise ok. */ return 1; } char* httpd_ntoa( httpd_sockaddr* saP ) { #ifdef USE_IPV6 static char str[200]; if ( getnameinfo( &saP->sa, sockaddr_len( saP ), str, sizeof(str), 0, 0, NI_NUMERICHOST ) != 0 ) { str[0] = '?'; str[1] = '\0'; } else if ( IN6_IS_ADDR_V4MAPPED( &saP->sa_in6.sin6_addr ) && strncmp( str, "::ffff:", 7 ) == 0 ) /* Elide IPv6ish prefix for IPv4 addresses. */ (void) memmove( str, &str[7], strlen( str ) - 6 ); return str; #else /* USE_IPV6 */ return inet_ntoa( saP->sa_in.sin_addr ); #endif /* USE_IPV6 */ } static int sockaddr_check( httpd_sockaddr* saP ) { switch ( saP->sa.sa_family ) { case AF_INET: return 1; #ifdef USE_IPV6 case AF_INET6: return 1; #endif /* USE_IPV6 */ default: return 0; } } static size_t sockaddr_len( httpd_sockaddr* saP ) { switch ( saP->sa.sa_family ) { case AF_INET: return sizeof(struct sockaddr_in); #ifdef USE_IPV6 case AF_INET6: return sizeof(struct sockaddr_in6); #endif /* USE_IPV6 */ default: return 0; /* shouldn't happen */ } } /* Some systems don't have snprintf(), so we make our own that uses ** either vsnprintf() or vsprintf(). If your system doesn't have ** vsnprintf(), it is probably vulnerable to buffer overruns. ** Upgrade! */ static int my_snprintf( char* str, size_t size, const char* format, ... ) { va_list ap; int r; va_start( ap, format ); #ifdef HAVE_VSNPRINTF r = vsnprintf( str, size, format, ap ); #else /* HAVE_VSNPRINTF */ r = vsprintf( str, format, ap ); #endif /* HAVE_VSNPRINTF */ va_end( ap ); return r; } #ifndef HAVE_ATOLL static long long atoll( const char* str ) { long long value; long long sign; while ( isspace( *str ) ) ++str; switch ( *str ) { case '-': sign = -1; ++str; break; case '+': sign = 1; ++str; break; default: sign = 1; break; } value = 0; while ( isdigit( *str ) ) { value = value * 10 + ( *str - '0' ); ++str; } return sign * value; } #endif /* HAVE_ATOLL */ /* Read the requested buffer completely, accounting for interruptions. */ int httpd_read_fully( int fd, void* buf, size_t nbytes ) { int nread; nread = 0; while ( nread < nbytes ) { int r; r = read( fd, (char*) buf + nread, nbytes - nread ); if ( r < 0 && ( errno == EINTR || errno == EAGAIN ) ) { sleep( 1 ); continue; } if ( r < 0 ) return r; if ( r == 0 ) break; nread += r; } return nread; } /* Write the requested buffer completely, accounting for interruptions. */ int httpd_write_fully( int fd, const void* buf, size_t nbytes ) { int nwritten; nwritten = 0; while ( nwritten < nbytes ) { int r; r = write( fd, (char*) buf + nwritten, nbytes - nwritten ); if ( r < 0 && ( errno == EINTR || errno == EAGAIN ) ) { sleep( 1 ); continue; } if ( r < 0 ) return r; if ( r == 0 ) break; nwritten += r; } return nwritten; } /* Generate debugging statistics syslog message. */ void httpd_logstats( long secs ) { if ( str_alloc_count > 0 ) syslog( LOG_INFO, " libhttpd - %d strings allocated, %lu bytes (%g bytes/str)", str_alloc_count, (unsigned long) str_alloc_size, (float) str_alloc_size / str_alloc_count ); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2553_0
crossvul-cpp_data_bad_940_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC % % SS T A A T I SS T I C % % SSS T AAAAA T I SSS T I C % % SS T A A T I SS T I C % % SSSSS T A A T IIIII SSSSS T IIIII CCCC % % % % % % MagickCore Image Statistical Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/animate.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/image-private.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/timer.h" #include "MagickCore/utility.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E v a l u a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EvaluateImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the EvaluateImage method is: % % MagickBooleanType EvaluateImage(Image *image, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImages(Image *images, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A channel op. % % o value: A value value. % % o exception: return any errors or warnings in this structure. % */ typedef struct _PixelChannels { double channel[CompositePixelChannel]; } PixelChannels; static PixelChannels **DestroyPixelThreadSet(PixelChannels **pixels) { register ssize_t i; assert(pixels != (PixelChannels **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (PixelChannels *) NULL) pixels[i]=(PixelChannels *) RelinquishMagickMemory(pixels[i]); pixels=(PixelChannels **) RelinquishMagickMemory(pixels); return(pixels); } static PixelChannels **AcquirePixelThreadSet(const Image *images) { const Image *next; PixelChannels **pixels; register ssize_t i; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } static inline double EvaluateMax(const double x,const double y) { if (x > y) return(x); return(y); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { const PixelChannels *color_1, *color_2; double distance; register ssize_t i; color_1=(const PixelChannels *) x; color_2=(const PixelChannels *) y; distance=0.0; for (i=0; i < MaxPixelChannels; i++) distance+=color_1->channel[i]-(double) color_2->channel[i]; return(distance < 0 ? -1 : distance > 0 ? 1 : 0); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static double ApplyEvaluateOperator(RandomInfo *random_info,const Quantum pixel, const MagickEvaluateOperator op,const double value) { double result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(double) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(double) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() that returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(double) ((size_t) pixel & (size_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(double) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(double) (QuantumRange*exp((double) (value*QuantumScale*pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,ImpulseNoise, value); break; } case LaplacianNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(double) ((size_t) pixel << (size_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(double) (QuantumRange*log((double) (QuantumScale*value*pixel+ 1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(double) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(double) (pixel+value); break; } case MedianEvaluateOperator: { result=(double) (pixel+value); break; } case MinEvaluateOperator: { result=(double) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(double) (value*pixel); break; } case OrEvaluateOperator: { result=(double) ((size_t) pixel | (size_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,PoissonNoise, value); break; } case PowEvaluateOperator: { result=(double) (QuantumRange*pow((double) (QuantumScale*pixel),(double) value)); break; } case RightShiftEvaluateOperator: { result=(double) ((size_t) pixel >> (size_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(double) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(double) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(double) (pixel-value); break; } case SumEvaluateOperator: { result=(double) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(double) (((double) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(double) (((double) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(double) (((double) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,UniformNoise, value); break; } case XorEvaluateOperator: { result=(double) ((size_t) pixel ^ (size_t) (value+0.5)); break; } } return(result); } static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception) { const Image *p, *q; size_t columns, rows; q=images; columns=images->columns; rows=images->rows; for (p=images; p != (Image *) NULL; p=p->next) { if (p->number_channels > q->number_channels) q=p; if (p->columns > columns) columns=p->columns; if (p->rows > rows) rows=p->rows; } return(CloneImage(q,columns,rows,MagickTrue,exception)); } MagickExport Image *EvaluateImages(const Image *images, const MagickEvaluateOperator op,ExceptionInfo *exception) { #define EvaluateImageTag "Evaluate/Image" CacheView *evaluate_view; Image *image; MagickBooleanType status; MagickOffsetType progress; PixelChannels **magick_restrict evaluate_pixels; RandomInfo **magick_restrict random_info; size_t number_images; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImage(image); return((Image *) NULL); } number_images=GetImageListLength(images); evaluate_pixels=AcquirePixelThreadSet(images); if (evaluate_pixels == (PixelChannels **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Evaluate image pixels. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); evaluate_view=AcquireAuthenticCacheView(image,exception); if (op == MedianEvaluateOperator) { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register PixelChannels *evaluate_pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j, k; for (j=0; j < (ssize_t) number_images; j++) for (k=0; k < MaxPixelChannels; k++) evaluate_pixel[j].channel[k]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; register ssize_t i; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait evaluate_traits=GetPixelChannelTraits(image,channel); PixelTrait traits = GetPixelChannelTraits(next,channel); if ((traits == UndefinedPixelTrait) || (evaluate_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; evaluate_pixel[j].channel[i]=ApplyEvaluateOperator( random_info[id],GetPixelChannel(image,channel,p),op, evaluate_pixel[j].channel[i]); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel), IntensityCompare); for (k=0; k < (ssize_t) GetPixelChannels(image); k++) q[k]=ClampToQuantum(evaluate_pixel[j/2].channel[k]); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,EvaluateImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } else { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register ssize_t i, x; register PixelChannels *evaluate_pixel; register Quantum *magick_restrict q; ssize_t j; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } evaluate_pixel=evaluate_pixels[id]; for (j=0; j < (ssize_t) image->columns; j++) for (i=0; i < MaxPixelChannels; i++) evaluate_pixel[j].channel[i]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(next); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(next,channel); PixelTrait evaluate_traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (evaluate_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; evaluate_pixel[x].channel[i]=ApplyEvaluateOperator( random_info[id],GetPixelChannel(image,channel,p),j == 0 ? AddEvaluateOperator : op,evaluate_pixel[x].channel[i]); } p+=GetPixelChannels(next); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; switch (op) { case MeanEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) evaluate_pixel[x].channel[i]/=(double) number_images; break; } case MultiplyEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; for (j=0; j < (ssize_t) (number_images-1); j++) evaluate_pixel[x].channel[i]*=QuantumScale; } break; } case RootMeanSquareEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) evaluate_pixel[x].channel[i]=sqrt(evaluate_pixel[x].channel[i]/ number_images); break; } default: break; } } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(evaluate_pixel[x].channel[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,EvaluateImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } evaluate_view=DestroyCacheView(evaluate_view); evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) image=DestroyImage(image); return(image); } MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double result; register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & CopyPixelTrait) != 0) continue; if ((traits & UpdatePixelTrait) == 0) continue; result=ApplyEvaluateOperator(random_info[id],q[i],op,value); if (op == MeanEvaluateOperator) result/=2.0; q[i]=ClampToQuantum(result); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EvaluateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F u n c t i o n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FunctionImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the FunctionImage method is: % % MagickBooleanType FunctionImage(Image *image, % const MagickFunction function,const ssize_t number_parameters, % const double *parameters,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o function: A channel function. % % o parameters: one or more parameters. % % o exception: return any errors or warnings in this structure. % */ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { double result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* Polynomial: polynomial constants, highest to lowest order (e.g. c0*x^3+ c1*x^2+c2*x+c3). */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel+parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { double amplitude, bias, frequency, phase; /* Sinusoid: frequency, phase, amplitude, bias. */ frequency=(number_parameters >= 1) ? parameters[0] : 1.0; phase=(number_parameters >= 2) ? parameters[1] : 0.0; amplitude=(number_parameters >= 3) ? parameters[2] : 0.5; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=(double) (QuantumRange*(amplitude*sin((double) (2.0* MagickPI*(frequency*QuantumScale*pixel+phase/360.0)))+bias)); break; } case ArcsinFunction: { double bias, center, range, width; /* Arcsin (peged at range limits for invalid results): width, center, range, and bias. */ width=(number_parameters >= 1) ? parameters[0] : 1.0; center=(number_parameters >= 2) ? parameters[1] : 0.5; range=(number_parameters >= 3) ? parameters[2] : 1.0; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=2.0/width*(QuantumScale*pixel-center); if ( result <= -1.0 ) result=bias-range/2.0; else if (result >= 1.0) result=bias+range/2.0; else result=(double) (range/MagickPI*asin((double) result)+bias); result*=QuantumRange; break; } case ArctanFunction: { double center, bias, range, slope; /* Arctan: slope, center, range, and bias. */ slope=(number_parameters >= 1) ? parameters[0] : 1.0; center=(number_parameters >= 2) ? parameters[1] : 0.5; range=(number_parameters >= 3) ? parameters[2] : 1.0; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=(double) (MagickPI*slope*(QuantumScale*pixel-center)); result=(double) (QuantumRange*(range/MagickPI*atan((double) result)+bias)); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } MagickExport MagickBooleanType FunctionImage(Image *image, const MagickFunction function,const size_t number_parameters, const double *parameters,ExceptionInfo *exception) { #define FunctionImageTag "Function/Image " CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateFunctionImage(image,function,number_parameters,parameters, exception) != MagickFalse) return(MagickTrue); #endif if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ApplyFunction(q[i],function,number_parameters,parameters, exception); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,FunctionImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e E n t r o p y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageEntropy() returns the entropy of one or more image channels. % % The format of the GetImageEntropy method is: % % MagickBooleanType GetImageEntropy(const Image *image,double *entropy, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o entropy: the average entropy of the selected channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageEntropy(const Image *image, double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *entropy=channel_statistics[CompositePixelChannel].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtrema() returns the extrema of one or more image channels. % % The format of the GetImageExtrema method is: % % MagickBooleanType GetImageExtrema(const Image *image,size_t *minima, % size_t *maxima,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageExtrema(const Image *image, size_t *minima,size_t *maxima,ExceptionInfo *exception) { double max, min; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageRange(image,&min,&max,exception); *minima=(size_t) ceil(min-0.5); *maxima=(size_t) floor(max+0.5); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e K u r t o s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageKurtosis() returns the kurtosis and skewness of one or more image % channels. % % The format of the GetImageKurtosis method is: % % MagickBooleanType GetImageKurtosis(const Image *image,double *kurtosis, % double *skewness,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o kurtosis: the kurtosis of the channel. % % o skewness: the skewness of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageKurtosis(const Image *image, double *kurtosis,double *skewness,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *kurtosis=channel_statistics[CompositePixelChannel].kurtosis; *skewness=channel_statistics[CompositePixelChannel].skewness; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M e a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMean() returns the mean and standard deviation of one or more image % channels. % % The format of the GetImageMean method is: % % MagickBooleanType GetImageMean(const Image *image,double *mean, % double *standard_deviation,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mean: the average value in the channel. % % o standard_deviation: the standard deviation of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean, double *standard_deviation,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *mean=channel_statistics[CompositePixelChannel].mean; *standard_deviation= channel_statistics[CompositePixelChannel].standard_deviation; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M o m e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMoments() returns the normalized moments of one or more image % channels. % % The format of the GetImageMoments method is: % % ChannelMoments *GetImageMoments(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static size_t GetImageChannels(const Image *image) { register ssize_t i; size_t channels; channels=0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; channels++; } return((size_t) (channels == 0 ? 1 : channels)); } MagickExport ChannelMoments *GetImageMoments(const Image *image, ExceptionInfo *exception) { #define MaxNumberImageMoments 8 CacheView *image_view; ChannelMoments *channel_moments; double M00[MaxPixelChannels+1], M01[MaxPixelChannels+1], M02[MaxPixelChannels+1], M03[MaxPixelChannels+1], M10[MaxPixelChannels+1], M11[MaxPixelChannels+1], M12[MaxPixelChannels+1], M20[MaxPixelChannels+1], M21[MaxPixelChannels+1], M22[MaxPixelChannels+1], M30[MaxPixelChannels+1]; PointInfo centroid[MaxPixelChannels+1]; ssize_t channel, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_moments=(ChannelMoments *) AcquireQuantumMemory(MaxPixelChannels+1, sizeof(*channel_moments)); if (channel_moments == (ChannelMoments *) NULL) return(channel_moments); (void) memset(channel_moments,0,(MaxPixelChannels+1)* sizeof(*channel_moments)); (void) memset(centroid,0,sizeof(centroid)); (void) memset(M00,0,sizeof(M00)); (void) memset(M01,0,sizeof(M01)); (void) memset(M02,0,sizeof(M02)); (void) memset(M03,0,sizeof(M03)); (void) memset(M10,0,sizeof(M10)); (void) memset(M11,0,sizeof(M11)); (void) memset(M12,0,sizeof(M12)); (void) memset(M20,0,sizeof(M20)); (void) memset(M21,0,sizeof(M21)); (void) memset(M22,0,sizeof(M22)); (void) memset(M30,0,sizeof(M30)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute center of mass (centroid). */ p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; M00[channel]+=QuantumScale*p[i]; M00[MaxPixelChannels]+=QuantumScale*p[i]; M10[channel]+=x*QuantumScale*p[i]; M10[MaxPixelChannels]+=x*QuantumScale*p[i]; M01[channel]+=y*QuantumScale*p[i]; M01[MaxPixelChannels]+=y*QuantumScale*p[i]; } p+=GetPixelChannels(image); } } for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute center of mass (centroid). */ if (M00[channel] < MagickEpsilon) { M00[channel]+=MagickEpsilon; centroid[channel].x=(double) image->columns/2.0; centroid[channel].y=(double) image->rows/2.0; continue; } M00[channel]+=MagickEpsilon; centroid[channel].x=M10[channel]/M00[channel]; centroid[channel].y=M01[channel]/M00[channel]; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute the image moments. */ p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; M11[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)* QuantumScale*p[i]; M11[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)* QuantumScale*p[i]; M20[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* QuantumScale*p[i]; M20[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* QuantumScale*p[i]; M02[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)* QuantumScale*p[i]; M02[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)* QuantumScale*p[i]; M21[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*QuantumScale*p[i]; M21[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*QuantumScale*p[i]; M12[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M12[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M22[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i]; M22[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i]; M30[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (x-centroid[channel].x)*QuantumScale*p[i]; M30[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (x-centroid[channel].x)*QuantumScale*p[i]; M03[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M03[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; } p+=GetPixelChannels(image); } } M00[MaxPixelChannels]/=GetImageChannels(image); M01[MaxPixelChannels]/=GetImageChannels(image); M02[MaxPixelChannels]/=GetImageChannels(image); M03[MaxPixelChannels]/=GetImageChannels(image); M10[MaxPixelChannels]/=GetImageChannels(image); M11[MaxPixelChannels]/=GetImageChannels(image); M12[MaxPixelChannels]/=GetImageChannels(image); M20[MaxPixelChannels]/=GetImageChannels(image); M21[MaxPixelChannels]/=GetImageChannels(image); M22[MaxPixelChannels]/=GetImageChannels(image); M30[MaxPixelChannels]/=GetImageChannels(image); for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute elliptical angle, major and minor axes, eccentricity, & intensity. */ channel_moments[channel].centroid=centroid[channel]; channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0* M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon))); if (fabs(M11[channel]) < MagickEpsilon) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } else if (M11[channel] < 0.0) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=180.0; } else { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } channel_moments[channel].ellipse_eccentricity=sqrt(1.0-( channel_moments[channel].ellipse_axis.y/ (channel_moments[channel].ellipse_axis.x+MagickEpsilon))); channel_moments[channel].ellipse_intensity=M00[channel]/ (MagickPI*channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.y+MagickEpsilon); } for (channel=0; channel <= MaxPixelChannels; channel++) { /* Normalize image moments. */ M10[channel]=0.0; M01[channel]=0.0; M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0); M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0); M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0); M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0); M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0); M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0); M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0); M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0); M00[channel]=1.0; } image_view=DestroyCacheView(image_view); for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute Hu invariant moments. */ channel_moments[channel].invariant[0]=M20[channel]+M02[channel]; channel_moments[channel].invariant[1]=(M20[channel]-M02[channel])* (M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel]; channel_moments[channel].invariant[2]=(M30[channel]-3.0*M12[channel])* (M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])* (3.0*M21[channel]-M03[channel]); channel_moments[channel].invariant[3]=(M30[channel]+M12[channel])* (M30[channel]+M12[channel])+(M21[channel]+M03[channel])* (M21[channel]+M03[channel]); channel_moments[channel].invariant[4]=(M30[channel]-3.0*M12[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].invariant[5]=(M20[channel]-M02[channel])* ((M30[channel]+M12[channel])*(M30[channel]+M12[channel])- (M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+ 4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]); channel_moments[channel].invariant[6]=(3.0*M21[channel]-M03[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].invariant[7]=M11[channel]*((M30[channel]+ M12[channel])*(M30[channel]+M12[channel])-(M03[channel]+M21[channel])* (M03[channel]+M21[channel]))-(M20[channel]-M02[channel])* (M30[channel]+M12[channel])*(M03[channel]+M21[channel]); } if (y < (ssize_t) image->rows) channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments); return(channel_moments); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePerceptualHash() returns the perceptual hash of one or more % image channels. % % The format of the GetImagePerceptualHash method is: % % ChannelPerceptualHash *GetImagePerceptualHash(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelPerceptualHash *GetImagePerceptualHash(const Image *image, ExceptionInfo *exception) { ChannelPerceptualHash *perceptual_hash; char *colorspaces, *q; const char *artifact; MagickBooleanType status; register char *p; register ssize_t i; perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory( MaxPixelChannels+1UL,sizeof(*perceptual_hash)); if (perceptual_hash == (ChannelPerceptualHash *) NULL) return((ChannelPerceptualHash *) NULL); artifact=GetImageArtifact(image,"phash:colorspaces"); if (artifact != NULL) colorspaces=AcquireString(artifact); else colorspaces=AcquireString("sRGB,HCLp"); perceptual_hash[0].number_colorspaces=0; perceptual_hash[0].number_channels=0; q=colorspaces; for (i=0; (p=StringToken(",",&q)) != (char *) NULL; i++) { ChannelMoments *moments; Image *hash_image; size_t j; ssize_t channel, colorspace; if (i >= MaximumNumberOfPerceptualColorspaces) break; colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse,p); if (colorspace < 0) break; perceptual_hash[0].colorspace[i]=(ColorspaceType) colorspace; hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) break; hash_image->depth=8; status=TransformImageColorspace(hash_image,(ColorspaceType) colorspace, exception); if (status == MagickFalse) break; moments=GetImageMoments(hash_image,exception); perceptual_hash[0].number_colorspaces++; perceptual_hash[0].number_channels+=GetImageChannels(hash_image); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) break; for (channel=0; channel <= MaxPixelChannels; channel++) for (j=0; j < MaximumNumberOfImageMoments; j++) perceptual_hash[channel].phash[i][j]= (-MagickLog10(moments[channel].invariant[j])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); } colorspaces=DestroyString(colorspaces); return(perceptual_hash); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageRange() returns the range of one or more image channels. % % The format of the GetImageRange method is: % % MagickBooleanType GetImageRange(const Image *image,double *minima, % double *maxima,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageRange(const Image *image,double *minima, double *maxima,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType initialize, status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; initialize=MagickTrue; *maxima=0.0; *minima=0.0; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,initialize) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double row_maxima = 0.0, row_minima = 0.0; MagickBooleanType row_initialize; register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } row_initialize=MagickTrue; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; if (row_initialize != MagickFalse) { row_minima=(double) p[i]; row_maxima=(double) p[i]; row_initialize=MagickFalse; } else { if ((double) p[i] < row_minima) row_minima=(double) p[i]; if ((double) p[i] > row_maxima) row_maxima=(double) p[i]; } } p+=GetPixelChannels(image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetImageRange) #endif { if (initialize != MagickFalse) { *minima=row_minima; *maxima=row_maxima; initialize=MagickFalse; } else { if (row_minima < *minima) *minima=row_minima; if (row_maxima > *maxima) *maxima=row_maxima; } } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e S t a t i s t i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageStatistics() returns statistics for each channel in the image. The % statistics include the channel depth, its minima, maxima, mean, standard % deviation, kurtosis and skewness. You can access the red channel mean, for % example, like this: % % channel_statistics=GetImageStatistics(image,exception); % red_mean=channel_statistics[RedPixelChannel].mean; % % Use MagickRelinquishMemory() to free the statistics buffer. % % The format of the GetImageStatistics method is: % % ChannelStatistics *GetImageStatistics(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelStatistics *GetImageStatistics(const Image *image, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; double area, *histogram, standard_deviation; MagickStatusType status; QuantumAny range; register ssize_t i; size_t depth; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); channel_statistics=(ChannelStatistics *) AcquireQuantumMemory( MaxPixelChannels+1,sizeof(*channel_statistics)); if ((channel_statistics == (ChannelStatistics *) NULL) || (histogram == (double *) NULL)) { if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (channel_statistics != (ChannelStatistics *) NULL) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } (void) memset(channel_statistics,0,(MaxPixelChannels+1)* sizeof(*channel_statistics)); for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { channel_statistics[i].depth=1; channel_statistics[i].maxima=(-MagickMaximumValue); channel_statistics[i].minima=MagickMaximumValue; } (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute pixel statistics. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; if (channel_statistics[channel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[channel].depth; range=GetQuantumRange(depth); status=p[i] != ScaleAnyToQuantum(ScaleQuantumToAny(p[i],range), range) ? MagickTrue : MagickFalse; if (status != MagickFalse) { channel_statistics[channel].depth++; i--; continue; } } if ((double) p[i] < channel_statistics[channel].minima) channel_statistics[channel].minima=(double) p[i]; if ((double) p[i] > channel_statistics[channel].maxima) channel_statistics[channel].maxima=(double) p[i]; channel_statistics[channel].sum+=p[i]; channel_statistics[channel].sum_squared+=(double) p[i]*p[i]; channel_statistics[channel].sum_cubed+=(double) p[i]*p[i]*p[i]; channel_statistics[channel].sum_fourth_power+=(double) p[i]*p[i]*p[i]* p[i]; channel_statistics[channel].area++; if ((double) p[i] < channel_statistics[CompositePixelChannel].minima) channel_statistics[CompositePixelChannel].minima=(double) p[i]; if ((double) p[i] > channel_statistics[CompositePixelChannel].maxima) channel_statistics[CompositePixelChannel].maxima=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum((double) p[i]))+i]++; channel_statistics[CompositePixelChannel].sum+=(double) p[i]; channel_statistics[CompositePixelChannel].sum_squared+=(double) p[i]*p[i]; channel_statistics[CompositePixelChannel].sum_cubed+=(double) p[i]*p[i]*p[i]; channel_statistics[CompositePixelChannel].sum_fourth_power+=(double) p[i]*p[i]*p[i]*p[i]; channel_statistics[CompositePixelChannel].area++; } p+=GetPixelChannels(image); } } for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { /* Normalize pixel statistics. */ area=PerceptibleReciprocal(channel_statistics[i].area); channel_statistics[i].sum*=area; channel_statistics[i].sum_squared*=area; channel_statistics[i].sum_cubed*=area; channel_statistics[i].sum_fourth_power*=area; channel_statistics[i].mean=channel_statistics[i].sum; channel_statistics[i].variance=channel_statistics[i].sum_squared; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); standard_deviation=sqrt(PerceptibleReciprocal(channel_statistics[i].area- 1.0)*channel_statistics[i].area*standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double number_bins; register ssize_t j; /* Compute pixel entropy. */ PixelChannel channel = GetPixelChannelChannel(image,i); number_bins=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) if (histogram[GetPixelChannels(image)*j+i] > 0.0) number_bins++; area=PerceptibleReciprocal(channel_statistics[channel].area); for (j=0; j <= (ssize_t) MaxMap; j++) { double count; count=area*histogram[GetPixelChannels(image)*j+i]; channel_statistics[channel].entropy+=-count*MagickLog10(count)* PerceptibleReciprocal(MagickLog10(number_bins)); channel_statistics[CompositePixelChannel].entropy+=-count* MagickLog10(count)*PerceptibleReciprocal(MagickLog10(number_bins))/ GetPixelChannels(image); } } histogram=(double *) RelinquishMagickMemory(histogram); for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { /* Compute kurtosis & skewness statistics. */ standard_deviation=PerceptibleReciprocal( channel_statistics[i].standard_deviation); channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0* channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation); channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0* channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean* channel_statistics[i].mean*1.0*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation*standard_deviation)-3.0; } channel_statistics[CompositePixelChannel].mean=0.0; channel_statistics[CompositePixelChannel].standard_deviation=0.0; channel_statistics[CompositePixelChannel].entropy=0.0; for (i=0; i < (ssize_t) MaxPixelChannels; i++) { channel_statistics[CompositePixelChannel].mean+= channel_statistics[i].mean; channel_statistics[CompositePixelChannel].standard_deviation+= channel_statistics[i].standard_deviation; channel_statistics[CompositePixelChannel].entropy+= channel_statistics[i].entropy; } channel_statistics[CompositePixelChannel].mean/=(double) GetImageChannels(image); channel_statistics[CompositePixelChannel].standard_deviation/=(double) GetImageChannels(image); channel_statistics[CompositePixelChannel].entropy/=(double) GetImageChannels(image); if (y < (ssize_t) image->rows) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l y n o m i a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolynomialImage() returns a new image where each pixel is the sum of the % pixels in the image sequence after applying its corresponding terms % (coefficient and degree pairs). % % The format of the PolynomialImage method is: % % Image *PolynomialImage(const Image *images,const size_t number_terms, % const double *terms,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o number_terms: the number of terms in the list. The actual list length % is 2 x number_terms + 1 (the constant). % % o terms: the list of polynomial coefficients and degree pairs and a % constant. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolynomialImage(const Image *images, const size_t number_terms,const double *terms,ExceptionInfo *exception) { #define PolynomialImageTag "Polynomial/Image" CacheView *polynomial_view; Image *image; MagickBooleanType status; MagickOffsetType progress; PixelChannels **magick_restrict polynomial_pixels; size_t number_images; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImage(image); return((Image *) NULL); } number_images=GetImageListLength(images); polynomial_pixels=AcquirePixelThreadSet(images); if (polynomial_pixels == (PixelChannels **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Polynomial image pixels. */ status=MagickTrue; progress=0; polynomial_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register ssize_t i, x; register PixelChannels *polynomial_pixel; register Quantum *magick_restrict q; ssize_t j; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } polynomial_pixel=polynomial_pixels[id]; for (j=0; j < (ssize_t) image->columns; j++) for (i=0; i < MaxPixelChannels; i++) polynomial_pixel[j].channel[i]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; if (j >= (ssize_t) number_terms) continue; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(next); i++) { MagickRealType coefficient, degree; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(next,channel); PixelTrait polynomial_traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (polynomial_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; coefficient=(MagickRealType) terms[2*j]; degree=(MagickRealType) terms[(j << 1)+1]; polynomial_pixel[x].channel[i]+=coefficient* pow(QuantumScale*GetPixelChannel(image,channel,p),degree); } p+=GetPixelChannels(next); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(QuantumRange*polynomial_pixel[x].channel[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,PolynomialImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } polynomial_view=DestroyCacheView(polynomial_view); polynomial_pixels=DestroyPixelThreadSet(polynomial_pixels); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t a t i s t i c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StatisticImage() makes each pixel the min / max / median / mode / etc. of % the neighborhood of the specified width and height. % % The format of the StatisticImage method is: % % Image *StatisticImage(const Image *image,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the statistic type (median, mode, etc.). % % o width: the width of the pixel neighborhood. % % o height: the height of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ typedef struct _SkipNode { size_t next[9], count, signature; } SkipNode; typedef struct _SkipList { ssize_t level; SkipNode *nodes; } SkipList; typedef struct _PixelList { size_t length, seed; SkipList skip_list; size_t signature; } PixelList; static PixelList *DestroyPixelList(PixelList *pixel_list) { if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); if (pixel_list->skip_list.nodes != (SkipNode *) NULL) pixel_list->skip_list.nodes=(SkipNode *) RelinquishAlignedMemory( pixel_list->skip_list.nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list) { register ssize_t i; assert(pixel_list != (PixelList **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_list[i] != (PixelList *) NULL) pixel_list[i]=DestroyPixelList(pixel_list[i]); pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList *AcquirePixelList(const size_t width,const size_t height) { PixelList *pixel_list; pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list)); if (pixel_list == (PixelList *) NULL) return(pixel_list); (void) memset((void *) pixel_list,0,sizeof(*pixel_list)); pixel_list->length=width*height; pixel_list->skip_list.nodes=(SkipNode *) AcquireAlignedMemory(65537UL, sizeof(*pixel_list->skip_list.nodes)); if (pixel_list->skip_list.nodes == (SkipNode *) NULL) return(DestroyPixelList(pixel_list)); (void) memset(pixel_list->skip_list.nodes,0,65537UL* sizeof(*pixel_list->skip_list.nodes)); pixel_list->signature=MagickCoreSignature; return(pixel_list); } static PixelList **AcquirePixelListThreadSet(const size_t width, const size_t height) { PixelList **pixel_list; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixel_list=(PixelList **) AcquireQuantumMemory(number_threads, sizeof(*pixel_list)); if (pixel_list == (PixelList **) NULL) return((PixelList **) NULL); (void) memset(pixel_list,0,number_threads*sizeof(*pixel_list)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_list[i]=AcquirePixelList(width,height); if (pixel_list[i] == (PixelList *) NULL) return(DestroyPixelListThreadSet(pixel_list)); } return(pixel_list); } static void AddNodePixelList(PixelList *pixel_list,const size_t color) { register SkipList *p; register ssize_t level; size_t search, update[9]; /* Initialize the node. */ p=(&pixel_list->skip_list); p->nodes[color].signature=pixel_list->signature; p->nodes[color].count=1; /* Determine where it belongs in the list. */ search=65536UL; for (level=p->level; level >= 0; level--) { while (p->nodes[search].next[level] < color) search=p->nodes[search].next[level]; update[level]=search; } /* Generate a pseudo-random level for this node. */ for (level=0; ; level++) { pixel_list->seed=(pixel_list->seed*42893621L)+1L; if ((pixel_list->seed & 0x300) != 0x300) break; } if (level > 8) level=8; if (level > (p->level+2)) level=p->level+2; /* If we're raising the list's level, link back to the root node. */ while (level > p->level) { p->level++; update[p->level]=65536UL; } /* Link the node into the skip-list. */ do { p->nodes[color].next[level]=p->nodes[update[level]].next[level]; p->nodes[update[level]].next[level]=color; } while (level-- > 0); } static inline void GetMaximumPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, maximum; ssize_t count; /* Find the maximum value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; maximum=p->nodes[color].next[0]; do { color=p->nodes[color].next[0]; if (color > maximum) maximum=color; count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) maximum); } static inline void GetMeanPixelList(PixelList *pixel_list,Quantum *pixel) { double sum; register SkipList *p; size_t color; ssize_t count; /* Find the mean value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; sum=0.0; do { color=p->nodes[color].next[0]; sum+=(double) p->nodes[color].count*color; count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; *pixel=ScaleShortToQuantum((unsigned short) sum); } static inline void GetMedianPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color; ssize_t count; /* Find the median value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; do { color=p->nodes[color].next[0]; count+=p->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); *pixel=ScaleShortToQuantum((unsigned short) color); } static inline void GetMinimumPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, minimum; ssize_t count; /* Find the minimum value for each of the color. */ p=(&pixel_list->skip_list); count=0; color=65536UL; minimum=p->nodes[color].next[0]; do { color=p->nodes[color].next[0]; if (color < minimum) minimum=color; count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) minimum); } static inline void GetModePixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, max_count, mode; ssize_t count; /* Make each pixel the 'predominant color' of the specified neighborhood. */ p=(&pixel_list->skip_list); color=65536L; mode=color; max_count=p->nodes[mode].count; count=0; do { color=p->nodes[color].next[0]; if (p->nodes[color].count > max_count) { mode=color; max_count=p->nodes[mode].count; } count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) mode); } static inline void GetNonpeakPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, next, previous; ssize_t count; /* Finds the non peak value for each of the colors. */ p=(&pixel_list->skip_list); color=65536L; next=p->nodes[color].next[0]; count=0; do { previous=color; color=next; next=p->nodes[color].next[0]; count+=p->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); if ((previous == 65536UL) && (next != 65536UL)) color=next; else if ((previous != 65536UL) && (next == 65536UL)) color=previous; *pixel=ScaleShortToQuantum((unsigned short) color); } static inline void GetRootMeanSquarePixelList(PixelList *pixel_list, Quantum *pixel) { double sum; register SkipList *p; size_t color; ssize_t count; /* Find the root mean square value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; sum=0.0; do { color=p->nodes[color].next[0]; sum+=(double) (p->nodes[color].count*color*color); count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; *pixel=ScaleShortToQuantum((unsigned short) sqrt(sum)); } static inline void GetStandardDeviationPixelList(PixelList *pixel_list, Quantum *pixel) { double sum, sum_squared; register SkipList *p; size_t color; ssize_t count; /* Find the standard-deviation value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; sum=0.0; sum_squared=0.0; do { register ssize_t i; color=p->nodes[color].next[0]; sum+=(double) p->nodes[color].count*color; for (i=0; i < (ssize_t) p->nodes[color].count; i++) sum_squared+=((double) color)*((double) color); count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; sum_squared/=pixel_list->length; *pixel=ScaleShortToQuantum((unsigned short) sqrt(sum_squared-(sum*sum))); } static inline void InsertPixelList(const Quantum pixel,PixelList *pixel_list) { size_t signature; unsigned short index; index=ScaleQuantumToShort(pixel); signature=pixel_list->skip_list.nodes[index].signature; if (signature == pixel_list->signature) { pixel_list->skip_list.nodes[index].count++; return; } AddNodePixelList(pixel_list,index); } static void ResetPixelList(PixelList *pixel_list) { int level; register SkipNode *root; register SkipList *p; /* Reset the skip-list. */ p=(&pixel_list->skip_list); root=p->nodes+65536UL; p->level=0; for (level=0; level < 9; level++) root->next[level]=65536UL; pixel_list->seed=pixel_list->signature++; } MagickExport Image *StatisticImage(const Image *image,const StatisticType type, const size_t width,const size_t height,ExceptionInfo *exception) { #define StatisticImageTag "Statistic/Image" CacheView *image_view, *statistic_view; Image *statistic_image; MagickBooleanType status; MagickOffsetType progress; PixelList **magick_restrict pixel_list; ssize_t center, y; /* Initialize statistics image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); statistic_image=CloneImage(image,0,0,MagickTrue, exception); if (statistic_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(statistic_image,DirectClass,exception); if (status == MagickFalse) { statistic_image=DestroyImage(statistic_image); return((Image *) NULL); } pixel_list=AcquirePixelListThreadSet(MagickMax(width,1),MagickMax(height,1)); if (pixel_list == (PixelList **) NULL) { statistic_image=DestroyImage(statistic_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Make each pixel the min / max / median / mode / etc. of the neighborhood. */ center=(ssize_t) GetPixelChannels(image)*(image->columns+MagickMax(width,1))* (MagickMax(height,1)/2L)+GetPixelChannels(image)*(MagickMax(width,1)/2L); status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); statistic_view=AcquireAuthenticCacheView(statistic_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,statistic_image,statistic_image->rows,1) #endif for (y=0; y < (ssize_t) statistic_image->rows; y++) { const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) MagickMax(width,1)/2L),y- (ssize_t) (MagickMax(height,1)/2L),image->columns+MagickMax(width,1), MagickMax(height,1),exception); q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) statistic_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { Quantum pixel; register const Quantum *magick_restrict pixels; register ssize_t u; ssize_t v; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait statistic_traits=GetPixelChannelTraits(statistic_image, channel); if ((traits == UndefinedPixelTrait) || (statistic_traits == UndefinedPixelTrait)) continue; if (((statistic_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(image,p) <= (QuantumRange/2))) { SetPixelChannel(statistic_image,channel,p[center+i],q); continue; } if ((statistic_traits & UpdatePixelTrait) == 0) continue; pixels=p; ResetPixelList(pixel_list[id]); for (v=0; v < (ssize_t) MagickMax(height,1); v++) { for (u=0; u < (ssize_t) MagickMax(width,1); u++) { InsertPixelList(pixels[i],pixel_list[id]); pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } switch (type) { case GradientStatistic: { double maximum, minimum; GetMinimumPixelList(pixel_list[id],&pixel); minimum=(double) pixel; GetMaximumPixelList(pixel_list[id],&pixel); maximum=(double) pixel; pixel=ClampToQuantum(MagickAbsoluteValue(maximum-minimum)); break; } case MaximumStatistic: { GetMaximumPixelList(pixel_list[id],&pixel); break; } case MeanStatistic: { GetMeanPixelList(pixel_list[id],&pixel); break; } case MedianStatistic: default: { GetMedianPixelList(pixel_list[id],&pixel); break; } case MinimumStatistic: { GetMinimumPixelList(pixel_list[id],&pixel); break; } case ModeStatistic: { GetModePixelList(pixel_list[id],&pixel); break; } case NonpeakStatistic: { GetNonpeakPixelList(pixel_list[id],&pixel); break; } case RootMeanSquareStatistic: { GetRootMeanSquarePixelList(pixel_list[id],&pixel); break; } case StandardDeviationStatistic: { GetStandardDeviationPixelList(pixel_list[id],&pixel); break; } } SetPixelChannel(statistic_image,channel,pixel,q); } p+=GetPixelChannels(image); q+=GetPixelChannels(statistic_image); } if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,StatisticImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } statistic_view=DestroyCacheView(statistic_view); image_view=DestroyCacheView(image_view); pixel_list=DestroyPixelListThreadSet(pixel_list); if (status == MagickFalse) statistic_image=DestroyImage(statistic_image); return(statistic_image); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_940_0
crossvul-cpp_data_bad_552_0
/* -*- Mode: C; c-file-style: "gnu" -*- */ /* Copyright (c) 2000 Petter Reinholdtsen 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. */ /* * scandir.c -- if scandir() is missing, make a replacement */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include "compat.h" /* * XXX This is a simple hack version which doesn't sort the data, and * just passes all unsorted. */ int scandir(const char *dir, struct dirent ***namelist, int (*select) (const struct dirent *), int (*compar) (const struct dirent **, const struct dirent **)) { DIR *d = opendir(dir); struct dirent *current; struct dirent **names; int count = 0; int pos = 0; int result = -1; if (NULL == d) return -1; while (NULL != readdir(d)) count++; names = malloc(sizeof (struct dirent *) * count); closedir(d); d = opendir(dir); if (NULL == d) return -1; while (NULL != (current = readdir(d))) { if (NULL == select || select(current)) { struct dirent *copyentry = malloc(current->d_reclen); memcpy(copyentry, current, current->d_reclen); names[pos] = copyentry; pos++; } } result = closedir(d); if (pos != count) names = realloc(names, sizeof (struct dirent *) * pos); *namelist = names; return pos; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_552_0
crossvul-cpp_data_bad_4743_2
/* * The Python Imaging Library. * $Id: //modules/pil/libImaging/TiffDecode.c#1 $ * * LibTiff-based Group3 and Group4 decoder * * * started modding to use non-private tiff functions to port to libtiff 4.x * eds 3/12/12 * */ #include "Imaging.h" #ifdef HAVE_LIBTIFF #ifndef uint #define uint uint32 #endif #include "TiffDecode.h" void dump_state(const TIFFSTATE *state){ TRACE(("State: Location %u size %d eof %d data: %p ifd: %d\n", (uint)state->loc, (int)state->size, (uint)state->eof, state->data, state->ifd)); } /* procs for TIFFOpenClient */ tsize_t _tiffReadProc(thandle_t hdata, tdata_t buf, tsize_t size) { TIFFSTATE *state = (TIFFSTATE *)hdata; tsize_t to_read; TRACE(("_tiffReadProc: %d \n", (int)size)); dump_state(state); to_read = min(size, min(state->size, (tsize_t)state->eof) - (tsize_t)state->loc); TRACE(("to_read: %d\n", (int)to_read)); _TIFFmemcpy(buf, (UINT8 *)state->data + state->loc, to_read); state->loc += (toff_t)to_read; TRACE( ("location: %u\n", (uint)state->loc)); return to_read; } tsize_t _tiffWriteProc(thandle_t hdata, tdata_t buf, tsize_t size) { TIFFSTATE *state = (TIFFSTATE *)hdata; tsize_t to_write; TRACE(("_tiffWriteProc: %d \n", (int)size)); dump_state(state); to_write = min(size, state->size - (tsize_t)state->loc); if (state->flrealloc && size>to_write) { tdata_t new; tsize_t newsize=state->size; while (newsize < (size + state->size)) { newsize += 64*1024; // newsize*=2; // UNDONE, by 64k chunks? } TRACE(("Reallocing in write to %d bytes\n", (int)newsize)); new = realloc(state->data, newsize); if (!new) { // fail out return 0; } state->data = new; state->size = newsize; to_write = size; } TRACE(("to_write: %d\n", (int)to_write)); _TIFFmemcpy((UINT8 *)state->data + state->loc, buf, to_write); state->loc += (toff_t)to_write; state->eof = max(state->loc, state->eof); dump_state(state); return to_write; } toff_t _tiffSeekProc(thandle_t hdata, toff_t off, int whence) { TIFFSTATE *state = (TIFFSTATE *)hdata; TRACE(("_tiffSeekProc: off: %u whence: %d \n", (uint)off, whence)); dump_state(state); switch (whence) { case 0: state->loc = off; break; case 1: state->loc += off; break; case 2: state->loc = state->eof + off; break; } dump_state(state); return state->loc; } int _tiffCloseProc(thandle_t hdata) { TIFFSTATE *state = (TIFFSTATE *)hdata; TRACE(("_tiffCloseProc \n")); dump_state(state); return 0; } toff_t _tiffSizeProc(thandle_t hdata) { TIFFSTATE *state = (TIFFSTATE *)hdata; TRACE(("_tiffSizeProc \n")); dump_state(state); return (toff_t)state->size; } int _tiffMapProc(thandle_t hdata, tdata_t* pbase, toff_t* psize) { TIFFSTATE *state = (TIFFSTATE *)hdata; TRACE(("_tiffMapProc input size: %u, data: %p\n", (uint)*psize, *pbase)); dump_state(state); *pbase = state->data; *psize = state->size; TRACE(("_tiffMapProc returning size: %u, data: %p\n", (uint)*psize, *pbase)); return (1); } int _tiffNullMapProc(thandle_t hdata, tdata_t* pbase, toff_t* psize) { (void) hdata; (void) pbase; (void) psize; return (0); } void _tiffUnmapProc(thandle_t hdata, tdata_t base, toff_t size) { TRACE(("_tiffUnMapProc\n")); (void) hdata; (void) base; (void) size; } int ImagingLibTiffInit(ImagingCodecState state, int fp, int offset) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; TRACE(("initing libtiff\n")); TRACE(("filepointer: %d \n", fp)); TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, state->x, state->y, state->ystep)); TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("State: context %p \n", state->context)); clientstate->loc = 0; clientstate->size = 0; clientstate->data = 0; clientstate->fp = fp; clientstate->ifd = offset; clientstate->eof = 0; return 1; } int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, int bytes) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; char *filename = "tempfile.tif"; char *mode = "r"; TIFF *tiff; int size; /* buffer is the encoded file, bytes is the length of the encoded file */ /* it all ends up in state->buffer, which is a uint8* from Imaging.h */ TRACE(("in decoder: bytes %d\n", bytes)); TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, state->x, state->y, state->ystep)); TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); TRACE(("State->Buffer: %c%c%c%c\n", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3])); TRACE(("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n", im->mode, im->type, im->bands, im->xsize, im->ysize)); TRACE(("Image: image8 %p, image32 %p, image %p, block %p \n", im->image8, im->image32, im->image, im->block)); TRACE(("Image: pixelsize: %d, linesize %d \n", im->pixelsize, im->linesize)); dump_state(clientstate); clientstate->size = bytes; clientstate->eof = clientstate->size; clientstate->loc = 0; clientstate->data = (tdata_t)buffer; clientstate->flrealloc = 0; dump_state(clientstate); TIFFSetWarningHandler(NULL); TIFFSetWarningHandlerExt(NULL); if (clientstate->fp) { TRACE(("Opening using fd: %d\n",clientstate->fp)); lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end. tiff = TIFFFdOpen(clientstate->fp, filename, mode); } else { TRACE(("Opening from string\n")); tiff = TIFFClientOpen(filename, mode, (thandle_t) clientstate, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); } if (!tiff){ TRACE(("Error, didn't get the tiff\n")); state->errcode = IMAGING_CODEC_BROKEN; return -1; } if (clientstate->ifd){ int rv; unsigned int ifdoffset = clientstate->ifd; TRACE(("reading tiff ifd %d\n", ifdoffset)); rv = TIFFSetSubDirectory(tiff, ifdoffset); if (!rv){ TRACE(("error in TIFFSetSubDirectory")); return -1; } } size = TIFFScanlineSize(tiff); TRACE(("ScanlineSize: %d \n", size)); if (size > state->bytes) { TRACE(("Error, scanline size > buffer size\n")); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } // Have to do this row by row and shove stuff into the buffer that way, // with shuffle. (or, just alloc a buffer myself, then figure out how to get it // back in. Can't use read encoded stripe. // This thing pretty much requires that I have the whole image in one shot. // Perhaps a stub version would work better??? while(state->y < state->ysize){ if (TIFFReadScanline(tiff, (tdata_t)state->buffer, (uint32)state->y, 0) == -1) { TRACE(("Decode Error, row %d\n", state->y)); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } /* TRACE(("Decoded row %d \n", state->y)); */ state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->xoff * im->pixelsize, state->buffer, state->xsize); state->y++; } TIFFClose(tiff); TRACE(("Done Decoding, Returning \n")); // Returning -1 here to force ImageFile.load to break, rather than // even think about looping back around. return -1; } int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) { // Open the FD or the pointer as a tiff file, for writing. // We may have to do some monkeying around to make this really work. // If we have a fp, then we're good. // If we have a memory string, we're probably going to have to malloc, then // shuffle bytes into the writescanline process. // Going to have to deal with the directory as well. TIFFSTATE *clientstate = (TIFFSTATE *)state->context; int bufsize = 64*1024; char *mode = "w"; TRACE(("initing libtiff\n")); TRACE(("Filename %s, filepointer: %d \n", filename, fp)); TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, state->x, state->y, state->ystep)); TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("State: context %p \n", state->context)); clientstate->loc = 0; clientstate->size = 0; clientstate->eof =0; clientstate->data = 0; clientstate->flrealloc = 0; clientstate->fp = fp; state->state = 0; if (fp) { TRACE(("Opening using fd: %d for writing \n",clientstate->fp)); clientstate->tiff = TIFFFdOpen(clientstate->fp, filename, mode); } else { // malloc a buffer to write the tif, we're going to need to realloc or something if we need bigger. TRACE(("Opening a buffer for writing \n")); clientstate->data = malloc(bufsize); clientstate->size = bufsize; clientstate->flrealloc=1; if (!clientstate->data) { TRACE(("Error, couldn't allocate a buffer of size %d\n", bufsize)); return 0; } clientstate->tiff = TIFFClientOpen(filename, mode, (thandle_t) clientstate, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffNullMapProc, _tiffUnmapProc); /*force no mmap*/ } if (!clientstate->tiff) { TRACE(("Error, couldn't open tiff file\n")); return 0; } return 1; } int ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...){ // after tif_dir.c->TIFFSetField. TIFFSTATE *clientstate = (TIFFSTATE *)state->context; va_list ap; int status; va_start(ap, tag); status = TIFFVSetField(clientstate->tiff, tag, ap); va_end(ap); return status; } int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int bytes) { /* One shot encoder. Encode everything to the tiff in the clientstate. If we're running off of a FD, then run once, we're good, everything ends up in the file, we close and we're done. If we're going to memory, then we need to write the whole file into memory, then parcel it back out to the pystring buffer bytes at a time. */ TIFFSTATE *clientstate = (TIFFSTATE *)state->context; TIFF *tiff = clientstate->tiff; TRACE(("in encoder: bytes %d\n", bytes)); TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, state->x, state->y, state->ystep)); TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); TRACE(("State->Buffer: %c%c%c%c\n", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3])); TRACE(("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n", im->mode, im->type, im->bands, im->xsize, im->ysize)); TRACE(("Image: image8 %p, image32 %p, image %p, block %p \n", im->image8, im->image32, im->image, im->block)); TRACE(("Image: pixelsize: %d, linesize %d \n", im->pixelsize, im->linesize)); dump_state(clientstate); if (state->state == 0) { TRACE(("Encoding line bt line")); while(state->y < state->ysize){ state->shuffle(state->buffer, (UINT8*) im->image[state->y + state->yoff] + state->xoff * im->pixelsize, state->xsize); if (TIFFWriteScanline(tiff, (tdata_t)(state->buffer), (uint32)state->y, 0) == -1) { TRACE(("Encode Error, row %d\n", state->y)); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); if (!clientstate->fp){ free(clientstate->data); } return -1; } state->y++; } if (state->y == state->ysize) { state->state=1; TRACE(("Flushing \n")); if (!TIFFFlush(tiff)) { TRACE(("Error flushing the tiff")); // likely reason is memory. state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); if (!clientstate->fp){ free(clientstate->data); } return -1; } TRACE(("Closing \n")); TIFFClose(tiff); // reset the clientstate metadata to use it to read out the buffer. clientstate->loc = 0; clientstate->size = clientstate->eof; // redundant? } } if (state->state == 1 && !clientstate->fp) { int read = (int)_tiffReadProc(clientstate, (tdata_t)buffer, (tsize_t)bytes); TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); if (clientstate->loc == clientstate->eof) { TRACE(("Hit EOF, calling an end, freeing data")); state->errcode = IMAGING_CODEC_END; free(clientstate->data); } return read; } state->errcode = IMAGING_CODEC_END; return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4743_2
crossvul-cpp_data_bad_5733_10
/* * Copyright (c) 2013 Clément Bœsch * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <float.h> /* DBL_MAX */ #include "libavutil/opt.h" #include "libavutil/eval.h" #include "libavutil/avassert.h" #include "libavutil/pixdesc.h" #include "avfilter.h" #include "formats.h" #include "internal.h" #include "video.h" static const char *const var_names[] = { "w", // stream width "h", // stream height "n", // frame count "pts", // presentation timestamp expressed in AV_TIME_BASE units "r", // frame rate "t", // timestamp expressed in seconds "tb", // timebase NULL }; enum var_name { VAR_W, VAR_H, VAR_N, VAR_PTS, VAR_R, VAR_T, VAR_TB, VAR_NB }; typedef struct { const AVClass *class; const AVPixFmtDescriptor *desc; int backward; enum EvalMode { EVAL_MODE_INIT, EVAL_MODE_FRAME, EVAL_MODE_NB } eval_mode; #define DEF_EXPR_FIELDS(name) AVExpr *name##_pexpr; char *name##_expr; double name DEF_EXPR_FIELDS(angle); DEF_EXPR_FIELDS(x0); DEF_EXPR_FIELDS(y0); double var_values[VAR_NB]; float *fmap; int fmap_linesize; double dmax; float xscale, yscale; uint32_t dither; int do_dither; AVRational aspect; AVRational scale; } VignetteContext; #define OFFSET(x) offsetof(VignetteContext, x) #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM static const AVOption vignette_options[] = { { "angle", "set lens angle", OFFSET(angle_expr), AV_OPT_TYPE_STRING, {.str="PI/5"}, .flags = FLAGS }, { "a", "set lens angle", OFFSET(angle_expr), AV_OPT_TYPE_STRING, {.str="PI/5"}, .flags = FLAGS }, { "x0", "set circle center position on x-axis", OFFSET(x0_expr), AV_OPT_TYPE_STRING, {.str="w/2"}, .flags = FLAGS }, { "y0", "set circle center position on y-axis", OFFSET(y0_expr), AV_OPT_TYPE_STRING, {.str="h/2"}, .flags = FLAGS }, { "mode", "set forward/backward mode", OFFSET(backward), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, FLAGS, "mode" }, { "forward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 0}, INT_MIN, INT_MAX, FLAGS, "mode"}, { "backward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, INT_MIN, INT_MAX, FLAGS, "mode"}, { "eval", "specify when to evaluate expressions", OFFSET(eval_mode), AV_OPT_TYPE_INT, {.i64 = EVAL_MODE_INIT}, 0, EVAL_MODE_NB-1, FLAGS, "eval" }, { "init", "eval expressions once during initialization", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_INIT}, .flags = FLAGS, .unit = "eval" }, { "frame", "eval expressions for each frame", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_FRAME}, .flags = FLAGS, .unit = "eval" }, { "dither", "set dithering", OFFSET(do_dither), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, FLAGS }, { "aspect", "set aspect ratio", OFFSET(aspect), AV_OPT_TYPE_RATIONAL, {.dbl = 1}, 0, DBL_MAX, .flags = FLAGS }, { NULL } }; AVFILTER_DEFINE_CLASS(vignette); static av_cold int init(AVFilterContext *ctx) { VignetteContext *s = ctx->priv; #define PARSE_EXPR(name) do { \ int ret = av_expr_parse(&s->name##_pexpr, s->name##_expr, var_names, \ NULL, NULL, NULL, NULL, 0, ctx); \ if (ret < 0) { \ av_log(ctx, AV_LOG_ERROR, "Unable to parse expression for '" \ AV_STRINGIFY(name) "'\n"); \ return ret; \ } \ } while (0) PARSE_EXPR(angle); PARSE_EXPR(x0); PARSE_EXPR(y0); return 0; } static av_cold void uninit(AVFilterContext *ctx) { VignetteContext *s = ctx->priv; av_freep(&s->fmap); av_expr_free(s->angle_pexpr); av_expr_free(s->x0_pexpr); av_expr_free(s->y0_pexpr); } static int query_formats(AVFilterContext *ctx) { static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV440P, AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE }; ff_set_common_formats(ctx, ff_make_format_list(pix_fmts)); return 0; } static double get_natural_factor(const VignetteContext *s, int x, int y) { const int xx = (x - s->x0) * s->xscale; const int yy = (y - s->y0) * s->yscale; const double dnorm = hypot(xx, yy) / s->dmax; if (dnorm > 1) { return 0; } else { const double c = cos(s->angle * dnorm); return (c*c)*(c*c); // do not remove braces, it helps compilers } } #define TS2D(ts) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts)) #define TS2T(ts, tb) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts) * av_q2d(tb)) static void update_context(VignetteContext *s, AVFilterLink *inlink, AVFrame *frame) { int x, y; float *dst = s->fmap; int dst_linesize = s->fmap_linesize; if (frame) { s->var_values[VAR_N] = inlink->frame_count; s->var_values[VAR_T] = TS2T(frame->pts, inlink->time_base); s->var_values[VAR_PTS] = TS2D(frame->pts); } else { s->var_values[VAR_N] = 0; s->var_values[VAR_T] = NAN; s->var_values[VAR_PTS] = NAN; } s->angle = av_clipf(av_expr_eval(s->angle_pexpr, s->var_values, NULL), 0, M_PI_2); s->x0 = av_expr_eval(s->x0_pexpr, s->var_values, NULL); s->y0 = av_expr_eval(s->y0_pexpr, s->var_values, NULL); if (s->backward) { for (y = 0; y < inlink->h; y++) { for (x = 0; x < inlink->w; x++) dst[x] = 1. / get_natural_factor(s, x, y); dst += dst_linesize; } } else { for (y = 0; y < inlink->h; y++) { for (x = 0; x < inlink->w; x++) dst[x] = get_natural_factor(s, x, y); dst += dst_linesize; } } } static inline double get_dither_value(VignetteContext *s) { double dv = 0; if (s->do_dither) { dv = s->dither / (double)(1LL<<32); s->dither = s->dither * 1664525 + 1013904223; } return dv; } static int filter_frame(AVFilterLink *inlink, AVFrame *in) { unsigned x, y; AVFilterContext *ctx = inlink->dst; VignetteContext *s = ctx->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); if (s->eval_mode == EVAL_MODE_FRAME) update_context(s, inlink, in); if (s->desc->flags & AV_PIX_FMT_FLAG_RGB) { uint8_t *dst = out->data[0]; const uint8_t *src = in ->data[0]; const float *fmap = s->fmap; const int dst_linesize = out->linesize[0]; const int src_linesize = in ->linesize[0]; const int fmap_linesize = s->fmap_linesize; for (y = 0; y < inlink->h; y++) { uint8_t *dstp = dst; const uint8_t *srcp = src; for (x = 0; x < inlink->w; x++, dstp += 3, srcp += 3) { const float f = fmap[x]; dstp[0] = av_clip_uint8(srcp[0] * f + get_dither_value(s)); dstp[1] = av_clip_uint8(srcp[1] * f + get_dither_value(s)); dstp[2] = av_clip_uint8(srcp[2] * f + get_dither_value(s)); } dst += dst_linesize; src += src_linesize; fmap += fmap_linesize; } } else { int plane; for (plane = 0; plane < 4 && in->data[plane]; plane++) { uint8_t *dst = out->data[plane]; const uint8_t *src = in ->data[plane]; const float *fmap = s->fmap; const int dst_linesize = out->linesize[plane]; const int src_linesize = in ->linesize[plane]; const int fmap_linesize = s->fmap_linesize; const int chroma = plane == 1 || plane == 2; const int hsub = chroma ? s->desc->log2_chroma_w : 0; const int vsub = chroma ? s->desc->log2_chroma_h : 0; const int w = FF_CEIL_RSHIFT(inlink->w, hsub); const int h = FF_CEIL_RSHIFT(inlink->h, vsub); for (y = 0; y < h; y++) { uint8_t *dstp = dst; const uint8_t *srcp = src; for (x = 0; x < w; x++) { const double dv = get_dither_value(s); if (chroma) *dstp++ = av_clip_uint8(fmap[x << hsub] * (*srcp++ - 127) + 127 + dv); else *dstp++ = av_clip_uint8(fmap[x ] * *srcp++ + dv); } dst += dst_linesize; src += src_linesize; fmap += fmap_linesize << vsub; } } } return ff_filter_frame(outlink, out); } static int config_props(AVFilterLink *inlink) { VignetteContext *s = inlink->dst->priv; AVRational sar = inlink->sample_aspect_ratio; s->desc = av_pix_fmt_desc_get(inlink->format); s->var_values[VAR_W] = inlink->w; s->var_values[VAR_H] = inlink->h; s->var_values[VAR_TB] = av_q2d(inlink->time_base); s->var_values[VAR_R] = inlink->frame_rate.num == 0 || inlink->frame_rate.den == 0 ? NAN : av_q2d(inlink->frame_rate); if (!sar.num || !sar.den) sar.num = sar.den = 1; if (sar.num > sar.den) { s->xscale = av_q2d(av_div_q(sar, s->aspect)); s->yscale = 1; } else { s->yscale = av_q2d(av_div_q(s->aspect, sar)); s->xscale = 1; } s->dmax = hypot(inlink->w / 2., inlink->h / 2.); av_log(s, AV_LOG_DEBUG, "xscale=%f yscale=%f dmax=%f\n", s->xscale, s->yscale, s->dmax); s->fmap_linesize = FFALIGN(inlink->w, 32); s->fmap = av_malloc(s->fmap_linesize * inlink->h * sizeof(*s->fmap)); if (!s->fmap) return AVERROR(ENOMEM); if (s->eval_mode == EVAL_MODE_INIT) update_context(s, inlink, NULL); return 0; } static const AVFilterPad vignette_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .filter_frame = filter_frame, .config_props = config_props, }, { NULL } }; static const AVFilterPad vignette_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, }, { NULL } }; AVFilter avfilter_vf_vignette = { .name = "vignette", .description = NULL_IF_CONFIG_SMALL("Make or reverse a vignette effect."), .priv_size = sizeof(VignetteContext), .init = init, .uninit = uninit, .query_formats = query_formats, .inputs = vignette_inputs, .outputs = vignette_outputs, .priv_class = &vignette_class, .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5733_10
crossvul-cpp_data_bad_246_0
/** * @file * IMAP helper functions * * @authors * Copyright (C) 1996-1998,2010,2012-2013 Michael R. Elkins <me@mutt.org> * Copyright (C) 1996-1999 Brandon Long <blong@fiction.net> * Copyright (C) 1999-2009,2012 Brendan Cully <brendan@kublai.com> * * @copyright * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @page imap_util IMAP helper functions * * IMAP helper functions */ #include "config.h" #include <ctype.h> #include <errno.h> #include <netdb.h> #include <netinet/in.h> #include <signal.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include "imap_private.h" #include "mutt/mutt.h" #include "conn/conn.h" #include "bcache.h" #include "context.h" #include "globals.h" #include "header.h" #include "imap/imap.h" #include "mailbox.h" #include "message.h" #include "mutt_account.h" #include "mutt_socket.h" #include "mx.h" #include "options.h" #include "protos.h" #include "url.h" #ifdef USE_HCACHE #include "hcache/hcache.h" #endif /** * imap_expand_path - Canonicalise an IMAP path * @param path Buffer containing path * @param len Buffer length * @retval 0 Success * @retval -1 Error * * IMAP implementation of mutt_expand_path. Rewrite an IMAP path in canonical * and absolute form. The buffer is rewritten in place with the canonical IMAP * path. * * Function can fail if imap_parse_path() or url_tostring() fail, * of if the buffer isn't large enough. */ int imap_expand_path(char *path, size_t len) { struct ImapMbox mx; struct ImapData *idata = NULL; struct Url url; char fixedpath[LONG_STRING]; int rc; if (imap_parse_path(path, &mx) < 0) return -1; idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW); mutt_account_tourl(&mx.account, &url); imap_fix_path(idata, mx.mbox, fixedpath, sizeof(fixedpath)); url.path = fixedpath; rc = url_tostring(&url, path, len, U_DECODE_PASSWD); FREE(&mx.mbox); return rc; } /** * imap_get_parent - Get an IMAP folder's parent * @param output Buffer for the result * @param mbox Mailbox whose parent is to be determined * @param olen Length of the buffer * @param delim Path delimiter */ void imap_get_parent(char *output, const char *mbox, size_t olen, char delim) { int n; /* Make a copy of the mailbox name, but only if the pointers are different */ if (mbox != output) mutt_str_strfcpy(output, mbox, olen); n = mutt_str_strlen(output); /* Let's go backwards until the next delimiter * * If output[n] is a '/', the first n-- will allow us * to ignore it. If it isn't, then output looks like * "/aaaaa/bbbb". There is at least one "b", so we can't skip * the "/" after the 'a's. * * If output == '/', then n-- => n == 0, so the loop ends * immediately */ for (n--; n >= 0 && output[n] != delim; n--) ; /* We stopped before the beginning. There is a trailing * slash. */ if (n > 0) { /* Strip the trailing delimiter. */ output[n] = '\0'; } else { output[0] = (n == 0) ? delim : '\0'; } } /** * imap_get_parent_path - Get the path of the parent folder * @param output Buffer for the result * @param path Mailbox whose parent is to be determined * @param olen Length of the buffer * * Provided an imap path, returns in output the parent directory if * existent. Else returns the same path. */ void imap_get_parent_path(char *output, const char *path, size_t olen) { struct ImapMbox mx; struct ImapData *idata = NULL; char mbox[LONG_STRING] = ""; if (imap_parse_path(path, &mx) < 0) { mutt_str_strfcpy(output, path, olen); return; } idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW); if (!idata) { mutt_str_strfcpy(output, path, olen); return; } /* Stores a fixed path in mbox */ imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox)); /* Gets the parent mbox in mbox */ imap_get_parent(mbox, mbox, sizeof(mbox), idata->delim); /* Returns a fully qualified IMAP url */ imap_qualify_path(output, olen, &mx, mbox); FREE(&mx.mbox); } /** * imap_clean_path - Cleans an IMAP path using imap_fix_path * @param path Path to be cleaned * @param plen Length of the buffer * * Does it in place. */ void imap_clean_path(char *path, size_t plen) { struct ImapMbox mx; struct ImapData *idata = NULL; char mbox[LONG_STRING] = ""; if (imap_parse_path(path, &mx) < 0) return; idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW); if (!idata) return; /* Stores a fixed path in mbox */ imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox)); /* Returns a fully qualified IMAP url */ imap_qualify_path(path, plen, &mx, mbox); } #ifdef USE_HCACHE /** * imap_hcache_namer - Generate a filename for the header cache * @param path Path for the header cache file * @param dest Buffer for result * @param dlen Length of buffer * @retval num Chars written to dest */ static int imap_hcache_namer(const char *path, char *dest, size_t dlen) { return snprintf(dest, dlen, "%s.hcache", path); } /** * imap_hcache_open - Open a header cache * @param idata Server data * @param path Path to the header cache * @retval ptr HeaderCache * @retval NULL Failure */ header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path) { struct ImapMbox mx; struct Url url; char cachepath[PATH_MAX]; char mbox[PATH_MAX]; if (path) imap_cachepath(idata, path, mbox, sizeof(mbox)); else { if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0) return NULL; imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox)); FREE(&mx.mbox); } if (strstr(mbox, "/../") || (strcmp(mbox, "..") == 0) || (strncmp(mbox, "../", 3) == 0)) return NULL; size_t len = strlen(mbox); if ((len > 3) && (strcmp(mbox + len - 3, "/..") == 0)) return NULL; mutt_account_tourl(&idata->conn->account, &url); url.path = mbox; url_tostring(&url, cachepath, sizeof(cachepath), U_PATH); return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer); } /** * imap_hcache_close - Close the header cache * @param idata Server data */ void imap_hcache_close(struct ImapData *idata) { if (!idata->hcache) return; mutt_hcache_close(idata->hcache); idata->hcache = NULL; } /** * imap_hcache_get - Get a header cache entry by its UID * @param idata Server data * @param uid UID to find * @retval ptr Email Header * @retval NULL Failure */ struct Header *imap_hcache_get(struct ImapData *idata, unsigned int uid) { char key[16]; void *uv = NULL; struct Header *h = NULL; if (!idata->hcache) return NULL; sprintf(key, "/%u", uid); uv = mutt_hcache_fetch(idata->hcache, key, imap_hcache_keylen(key)); if (uv) { if (*(unsigned int *) uv == idata->uid_validity) h = mutt_hcache_restore(uv); else mutt_debug(3, "hcache uidvalidity mismatch: %u\n", *(unsigned int *) uv); mutt_hcache_free(idata->hcache, &uv); } return h; } /** * imap_hcache_put - Add an entry to the header cache * @param idata Server data * @param h Email Header * @retval 0 Success * @retval -1 Failure */ int imap_hcache_put(struct ImapData *idata, struct Header *h) { char key[16]; if (!idata->hcache) return -1; sprintf(key, "/%u", HEADER_DATA(h)->uid); return mutt_hcache_store(idata->hcache, key, imap_hcache_keylen(key), h, idata->uid_validity); } /** * imap_hcache_del - Delete an item from the header cache * @param idata Server data * @param uid UID of entry to delete * @retval 0 Success * @retval -1 Failure */ int imap_hcache_del(struct ImapData *idata, unsigned int uid) { char key[16]; if (!idata->hcache) return -1; sprintf(key, "/%u", uid); return mutt_hcache_delete(idata->hcache, key, imap_hcache_keylen(key)); } #endif /** * imap_parse_path - Parse an IMAP mailbox name into name,host,port * @param path Mailbox path to parse * @param mx An IMAP mailbox * @retval 0 Success * @retval -1 Failure * * Given an IMAP mailbox name, return host, port and a path IMAP servers will * recognize. mx.mbox is malloc'd, caller must free it */ int imap_parse_path(const char *path, struct ImapMbox *mx) { static unsigned short ImapPort = 0; static unsigned short ImapsPort = 0; struct servent *service = NULL; struct Url url; char *c = NULL; if (!ImapPort) { service = getservbyname("imap", "tcp"); if (service) ImapPort = ntohs(service->s_port); else ImapPort = IMAP_PORT; mutt_debug(3, "Using default IMAP port %d\n", ImapPort); } if (!ImapsPort) { service = getservbyname("imaps", "tcp"); if (service) ImapsPort = ntohs(service->s_port); else ImapsPort = IMAP_SSL_PORT; mutt_debug(3, "Using default IMAPS port %d\n", ImapsPort); } /* Defaults */ memset(&mx->account, 0, sizeof(mx->account)); mx->account.port = ImapPort; mx->account.type = MUTT_ACCT_TYPE_IMAP; c = mutt_str_strdup(path); url_parse(&url, c); if (url.scheme == U_IMAP || url.scheme == U_IMAPS) { if (mutt_account_fromurl(&mx->account, &url) < 0 || !*mx->account.host) { url_free(&url); FREE(&c); return -1; } mx->mbox = mutt_str_strdup(url.path); if (url.scheme == U_IMAPS) mx->account.flags |= MUTT_ACCT_SSL; url_free(&url); FREE(&c); } /* old PINE-compatibility code */ else { url_free(&url); FREE(&c); char tmp[128]; if (sscanf(path, "{%127[^}]}", tmp) != 1) return -1; c = strchr(path, '}'); if (!c) return -1; else { /* walk past closing '}' */ mx->mbox = mutt_str_strdup(c + 1); } c = strrchr(tmp, '@'); if (c) { *c = '\0'; mutt_str_strfcpy(mx->account.user, tmp, sizeof(mx->account.user)); mutt_str_strfcpy(tmp, c + 1, sizeof(tmp)); mx->account.flags |= MUTT_ACCT_USER; } const int n = sscanf(tmp, "%127[^:/]%127s", mx->account.host, tmp); if (n < 1) { mutt_debug(1, "NULL host in %s\n", path); FREE(&mx->mbox); return -1; } if (n > 1) { if (sscanf(tmp, ":%hu%127s", &(mx->account.port), tmp) >= 1) mx->account.flags |= MUTT_ACCT_PORT; if (sscanf(tmp, "/%s", tmp) == 1) { if (mutt_str_strncmp(tmp, "ssl", 3) == 0) mx->account.flags |= MUTT_ACCT_SSL; else { mutt_debug(1, "Unknown connection type in %s\n", path); FREE(&mx->mbox); return -1; } } } } if ((mx->account.flags & MUTT_ACCT_SSL) && !(mx->account.flags & MUTT_ACCT_PORT)) mx->account.port = ImapsPort; return 0; } /** * imap_mxcmp - Compare mailbox names, giving priority to INBOX * @param mx1 First mailbox name * @param mx2 Second mailbox name * @retval <0 First mailbox precedes Second mailbox * @retval 0 Mailboxes are the same * @retval >0 Second mailbox precedes First mailbox * * Like a normal sort function except that "INBOX" will be sorted to the * beginning of the list. */ int imap_mxcmp(const char *mx1, const char *mx2) { char *b1 = NULL; char *b2 = NULL; int rc; if (!mx1 || !*mx1) mx1 = "INBOX"; if (!mx2 || !*mx2) mx2 = "INBOX"; if ((mutt_str_strcasecmp(mx1, "INBOX") == 0) && (mutt_str_strcasecmp(mx2, "INBOX") == 0)) { return 0; } b1 = mutt_mem_malloc(strlen(mx1) + 1); b2 = mutt_mem_malloc(strlen(mx2) + 1); imap_fix_path(NULL, mx1, b1, strlen(mx1) + 1); imap_fix_path(NULL, mx2, b2, strlen(mx2) + 1); rc = mutt_str_strcmp(b1, b2); FREE(&b1); FREE(&b2); return rc; } /** * imap_pretty_mailbox - Prettify an IMAP mailbox name * @param path Mailbox name to be tidied * * Called by mutt_pretty_mailbox() to make IMAP paths look nice. */ void imap_pretty_mailbox(char *path) { struct ImapMbox home, target; struct Url url; char *delim = NULL; int tlen; int hlen = 0; bool home_match = false; if (imap_parse_path(path, &target) < 0) return; tlen = mutt_str_strlen(target.mbox); /* check whether we can do '=' substitution */ if (mx_is_imap(Folder) && !imap_parse_path(Folder, &home)) { hlen = mutt_str_strlen(home.mbox); if (tlen && mutt_account_match(&home.account, &target.account) && (mutt_str_strncmp(home.mbox, target.mbox, hlen) == 0)) { if (hlen == 0) home_match = true; else if (ImapDelimChars) { for (delim = ImapDelimChars; *delim != '\0'; delim++) if (target.mbox[hlen] == *delim) home_match = true; } } FREE(&home.mbox); } /* do the '=' substitution */ if (home_match) { *path++ = '='; /* copy remaining path, skipping delimiter */ if (hlen == 0) hlen = -1; memcpy(path, target.mbox + hlen + 1, tlen - hlen - 1); path[tlen - hlen - 1] = '\0'; } else { mutt_account_tourl(&target.account, &url); url.path = target.mbox; /* FIXME: That hard-coded constant is bogus. But we need the actual * size of the buffer from mutt_pretty_mailbox. And these pretty * operations usually shrink the result. Still... */ url_tostring(&url, path, 1024, 0); } FREE(&target.mbox); } /** * imap_continue - display a message and ask the user if they want to go on * @param msg Location of the error * @param resp Message for user * @retval num Result: #MUTT_YES, #MUTT_NO, #MUTT_ABORT */ int imap_continue(const char *msg, const char *resp) { imap_error(msg, resp); return mutt_yesorno(_("Continue?"), 0); } /** * imap_error - show an error and abort * @param where Location of the error * @param msg Message for user */ void imap_error(const char *where, const char *msg) { mutt_error("%s [%s]\n", where, msg); } /** * imap_new_idata - Allocate and initialise a new ImapData structure * @retval NULL Failure (no mem) * @retval ptr New ImapData */ struct ImapData *imap_new_idata(void) { struct ImapData *idata = mutt_mem_calloc(1, sizeof(struct ImapData)); idata->cmdbuf = mutt_buffer_new(); idata->cmdslots = ImapPipelineDepth + 2; idata->cmds = mutt_mem_calloc(idata->cmdslots, sizeof(*idata->cmds)); STAILQ_INIT(&idata->flags); STAILQ_INIT(&idata->mboxcache); return idata; } /** * imap_free_idata - Release and clear storage in an ImapData structure * @param idata Server data */ void imap_free_idata(struct ImapData **idata) { if (!idata) return; FREE(&(*idata)->capstr); mutt_list_free(&(*idata)->flags); imap_mboxcache_free(*idata); mutt_buffer_free(&(*idata)->cmdbuf); FREE(&(*idata)->buf); mutt_bcache_close(&(*idata)->bcache); FREE(&(*idata)->cmds); FREE(idata); } /** * imap_fix_path - Fix up the imap path * @param idata Server data * @param mailbox Mailbox path * @param path Buffer for the result * @param plen Length of buffer * @retval ptr Fixed-up path * * This is necessary because the rest of neomutt assumes a hierarchy delimiter of * '/', which is not necessarily true in IMAP. Additionally, the filesystem * converts multiple hierarchy delimiters into a single one, ie "///" is equal * to "/". IMAP servers are not required to do this. * Moreover, IMAP servers may dislike the path ending with the delimiter. */ char *imap_fix_path(struct ImapData *idata, const char *mailbox, char *path, size_t plen) { int i = 0; char delim = '\0'; if (idata) delim = idata->delim; while (mailbox && *mailbox && i < plen - 1) { if ((ImapDelimChars && strchr(ImapDelimChars, *mailbox)) || (delim && *mailbox == delim)) { /* use connection delimiter if known. Otherwise use user delimiter */ if (!idata) delim = *mailbox; while (*mailbox && ((ImapDelimChars && strchr(ImapDelimChars, *mailbox)) || (delim && *mailbox == delim))) { mailbox++; } path[i] = delim; } else { path[i] = *mailbox; mailbox++; } i++; } if (i && path[--i] != delim) i++; path[i] = '\0'; return path; } /** * imap_cachepath - Generate a cache path for a mailbox * @param idata Server data * @param mailbox Mailbox name * @param dest Buffer to store cache path * @param dlen Length of buffer */ void imap_cachepath(struct ImapData *idata, const char *mailbox, char *dest, size_t dlen) { char *s = NULL; const char *p = mailbox; for (s = dest; p && *p && dlen; dlen--) { if (*p == idata->delim) { *s = '/'; /* simple way to avoid collisions with UIDs */ if (*(p + 1) >= '0' && *(p + 1) <= '9') { if (--dlen) *++s = '_'; } } else *s = *p; p++; s++; } *s = '\0'; } /** * imap_get_literal_count - write number of bytes in an IMAP literal into bytes * @param[in] buf Number as a string * @param[out] bytes Resulting number * @retval 0 Success * @retval -1 Failure */ int imap_get_literal_count(const char *buf, unsigned int *bytes) { char *pc = NULL; char *pn = NULL; if (!buf || !(pc = strchr(buf, '{'))) return -1; pc++; pn = pc; while (isdigit((unsigned char) *pc)) pc++; *pc = '\0'; if (mutt_str_atoui(pn, bytes) < 0) return -1; return 0; } /** * imap_get_qualifier - Get the qualifier from a tagged response * @param buf Command string to process * @retval ptr Start of the qualifier * * In a tagged response, skip tag and status for the qualifier message. * Used by imap_copy_message for TRYCREATE */ char *imap_get_qualifier(char *buf) { char *s = buf; /* skip tag */ s = imap_next_word(s); /* skip OK/NO/BAD response */ s = imap_next_word(s); return s; } /** * imap_next_word - Find where the next IMAP word begins * @param s Command string to process * @retval ptr Next IMAP word */ char *imap_next_word(char *s) { int quoted = 0; while (*s) { if (*s == '\\') { s++; if (*s) s++; continue; } if (*s == '\"') quoted = quoted ? 0 : 1; if (!quoted && ISSPACE(*s)) break; s++; } SKIPWS(s); return s; } /** * imap_qualify_path - Make an absolute IMAP folder target * @param dest Buffer for the result * @param len Length of buffer * @param mx Imap mailbox * @param path Path relative to the mailbox * * given ImapMbox and relative path. */ void imap_qualify_path(char *dest, size_t len, struct ImapMbox *mx, char *path) { struct Url url; mutt_account_tourl(&mx->account, &url); url.path = path; url_tostring(&url, dest, len, 0); } /** * imap_quote_string - quote string according to IMAP rules * @param dest Buffer for the result * @param dlen Length of the buffer * @param src String to be quoted * * Surround string with quotes, escape " and \ with backslash */ void imap_quote_string(char *dest, size_t dlen, const char *src, bool quote_backtick) { const char *quote = "`\"\\"; if (!quote_backtick) quote++; char *pt = dest; const char *s = src; *pt++ = '"'; /* save room for trailing quote-char */ dlen -= 2; for (; *s && dlen; s++) { if (strchr(quote, *s)) { if (dlen < 2) break; dlen -= 2; *pt++ = '\\'; *pt++ = *s; } else { *pt++ = *s; dlen--; } } *pt++ = '"'; *pt = '\0'; } /** * imap_unquote_string - equally stupid unquoting routine * @param s String to be unquoted */ void imap_unquote_string(char *s) { char *d = s; if (*s == '\"') s++; else return; while (*s) { if (*s == '\"') { *d = '\0'; return; } if (*s == '\\') { s++; } if (*s) { *d = *s; d++; s++; } } *d = '\0'; } /** * imap_munge_mbox_name - Quote awkward characters in a mailbox name * @param idata Server data * @param dest Buffer to store safe mailbox name * @param dlen Length of buffer * @param src Mailbox name */ void imap_munge_mbox_name(struct ImapData *idata, char *dest, size_t dlen, const char *src) { char *buf = mutt_str_strdup(src); imap_utf_encode(idata, &buf); imap_quote_string(dest, dlen, buf, false); FREE(&buf); } /** * imap_unmunge_mbox_name - Remove quoting from a mailbox name * @param idata Server data * @param s Mailbox name * * The string will be altered in-place. */ void imap_unmunge_mbox_name(struct ImapData *idata, char *s) { imap_unquote_string(s); char *buf = mutt_str_strdup(s); if (buf) { imap_utf_decode(idata, &buf); strncpy(s, buf, strlen(s)); } FREE(&buf); } /** * imap_keepalive - poll the current folder to keep the connection alive */ void imap_keepalive(void) { struct Connection *conn = NULL; struct ImapData *idata = NULL; time_t now = time(NULL); TAILQ_FOREACH(conn, mutt_socket_head(), entries) { if (conn->account.type == MUTT_ACCT_TYPE_IMAP) { idata = conn->data; if (idata->state >= IMAP_AUTHENTICATED && now >= idata->lastread + ImapKeepalive) { imap_check(idata, 1); } } } } /** * imap_wait_keepalive - Wait for a process to change state * @param pid Process ID to listen to * @retval num 'wstatus' from waitpid() */ int imap_wait_keepalive(pid_t pid) { struct sigaction oldalrm; struct sigaction act; sigset_t oldmask; int rc; bool imap_passive = ImapPassive; ImapPassive = true; OptKeepQuiet = true; sigprocmask(SIG_SETMASK, NULL, &oldmask); sigemptyset(&act.sa_mask); act.sa_handler = mutt_sig_empty_handler; #ifdef SA_INTERRUPT act.sa_flags = SA_INTERRUPT; #else act.sa_flags = 0; #endif sigaction(SIGALRM, &act, &oldalrm); alarm(ImapKeepalive); while (waitpid(pid, &rc, 0) < 0 && errno == EINTR) { alarm(0); /* cancel a possibly pending alarm */ imap_keepalive(); alarm(ImapKeepalive); } alarm(0); /* cancel a possibly pending alarm */ sigaction(SIGALRM, &oldalrm, NULL); sigprocmask(SIG_SETMASK, &oldmask, NULL); OptKeepQuiet = false; if (!imap_passive) ImapPassive = false; return rc; } /** * imap_allow_reopen - Allow re-opening a folder upon expunge * @param ctx Context */ void imap_allow_reopen(struct Context *ctx) { struct ImapData *idata = NULL; if (!ctx || !ctx->data || ctx->magic != MUTT_IMAP) return; idata = ctx->data; if (idata->ctx == ctx) idata->reopen |= IMAP_REOPEN_ALLOW; } /** * imap_disallow_reopen - Disallow re-opening a folder upon expunge * @param ctx Context */ void imap_disallow_reopen(struct Context *ctx) { struct ImapData *idata = NULL; if (!ctx || !ctx->data || ctx->magic != MUTT_IMAP) return; idata = ctx->data; if (idata->ctx == ctx) idata->reopen &= ~IMAP_REOPEN_ALLOW; } /** * imap_account_match - Compare two Accounts * @param a1 First Account * @param a2 Second Account * @retval true Accounts match */ int imap_account_match(const struct Account *a1, const struct Account *a2) { struct ImapData *a1_idata = imap_conn_find(a1, MUTT_IMAP_CONN_NONEW); struct ImapData *a2_idata = imap_conn_find(a2, MUTT_IMAP_CONN_NONEW); const struct Account *a1_canon = a1_idata == NULL ? a1 : &a1_idata->conn->account; const struct Account *a2_canon = a2_idata == NULL ? a2 : &a2_idata->conn->account; return mutt_account_match(a1_canon, a2_canon); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_246_0
crossvul-cpp_data_good_5733_4
/* * Copyright (c) 2010 Nolan Lum <nol888@gmail.com> * Copyright (c) 2009 Loren Merritt <lorenm@u.washignton.edu> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * gradfun debanding filter, ported from MPlayer * libmpcodecs/vf_gradfun.c * * Apply a boxblur debanding algorithm (based on the gradfun2db * AviSynth filter by prunedtree). * Foreach pixel, if it's within threshold of the blurred value, make it closer. * So now we have a smoothed and higher bitdepth version of all the shallow * gradients, while leaving detailed areas untouched. * Dither it back to 8bit. */ #include "libavutil/imgutils.h" #include "libavutil/common.h" #include "libavutil/cpu.h" #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "libavutil/opt.h" #include "avfilter.h" #include "formats.h" #include "gradfun.h" #include "internal.h" #include "video.h" DECLARE_ALIGNED(16, static const uint16_t, dither)[8][8] = { {0x00,0x60,0x18,0x78,0x06,0x66,0x1E,0x7E}, {0x40,0x20,0x58,0x38,0x46,0x26,0x5E,0x3E}, {0x10,0x70,0x08,0x68,0x16,0x76,0x0E,0x6E}, {0x50,0x30,0x48,0x28,0x56,0x36,0x4E,0x2E}, {0x04,0x64,0x1C,0x7C,0x02,0x62,0x1A,0x7A}, {0x44,0x24,0x5C,0x3C,0x42,0x22,0x5A,0x3A}, {0x14,0x74,0x0C,0x6C,0x12,0x72,0x0A,0x6A}, {0x54,0x34,0x4C,0x2C,0x52,0x32,0x4A,0x2A}, }; void ff_gradfun_filter_line_c(uint8_t *dst, const uint8_t *src, const uint16_t *dc, int width, int thresh, const uint16_t *dithers) { int x; for (x = 0; x < width; dc += x & 1, x++) { int pix = src[x] << 7; int delta = dc[0] - pix; int m = abs(delta) * thresh >> 16; m = FFMAX(0, 127 - m); m = m * m * delta >> 14; pix += m + dithers[x & 7]; dst[x] = av_clip_uint8(pix >> 7); } } void ff_gradfun_blur_line_c(uint16_t *dc, uint16_t *buf, const uint16_t *buf1, const uint8_t *src, int src_linesize, int width) { int x, v, old; for (x = 0; x < width; x++) { v = buf1[x] + src[2 * x] + src[2 * x + 1] + src[2 * x + src_linesize] + src[2 * x + 1 + src_linesize]; old = buf[x]; buf[x] = v; dc[x] = v - old; } } static void filter(GradFunContext *ctx, uint8_t *dst, const uint8_t *src, int width, int height, int dst_linesize, int src_linesize, int r) { int bstride = FFALIGN(width, 16) / 2; int y; uint32_t dc_factor = (1 << 21) / (r * r); uint16_t *dc = ctx->buf + 16; uint16_t *buf = ctx->buf + bstride + 32; int thresh = ctx->thresh; memset(dc, 0, (bstride + 16) * sizeof(*buf)); for (y = 0; y < r; y++) ctx->blur_line(dc, buf + y * bstride, buf + (y - 1) * bstride, src + 2 * y * src_linesize, src_linesize, width / 2); for (;;) { if (y < height - r) { int mod = ((y + r) / 2) % r; uint16_t *buf0 = buf + mod * bstride; uint16_t *buf1 = buf + (mod ? mod - 1 : r - 1) * bstride; int x, v; ctx->blur_line(dc, buf0, buf1, src + (y + r) * src_linesize, src_linesize, width / 2); for (x = v = 0; x < r; x++) v += dc[x]; for (; x < width / 2; x++) { v += dc[x] - dc[x-r]; dc[x-r] = v * dc_factor >> 16; } for (; x < (width + r + 1) / 2; x++) dc[x-r] = v * dc_factor >> 16; for (x = -r / 2; x < 0; x++) dc[x] = dc[0]; } if (y == r) { for (y = 0; y < r; y++) ctx->filter_line(dst + y * dst_linesize, src + y * src_linesize, dc - r / 2, width, thresh, dither[y & 7]); } ctx->filter_line(dst + y * dst_linesize, src + y * src_linesize, dc - r / 2, width, thresh, dither[y & 7]); if (++y >= height) break; ctx->filter_line(dst + y * dst_linesize, src + y * src_linesize, dc - r / 2, width, thresh, dither[y & 7]); if (++y >= height) break; } } static av_cold int init(AVFilterContext *ctx) { GradFunContext *s = ctx->priv; s->thresh = (1 << 15) / s->strength; s->radius = av_clip((s->radius + 1) & ~1, 4, 32); s->blur_line = ff_gradfun_blur_line_c; s->filter_line = ff_gradfun_filter_line_c; if (ARCH_X86) ff_gradfun_init_x86(s); av_log(ctx, AV_LOG_VERBOSE, "threshold:%.2f radius:%d\n", s->strength, s->radius); return 0; } static av_cold void uninit(AVFilterContext *ctx) { GradFunContext *s = ctx->priv; av_freep(&s->buf); } static int query_formats(AVFilterContext *ctx) { static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_GRAY8, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV440P, AV_PIX_FMT_NONE }; ff_set_common_formats(ctx, ff_make_format_list(pix_fmts)); return 0; } static int config_input(AVFilterLink *inlink) { GradFunContext *s = inlink->dst->priv; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); int hsub = desc->log2_chroma_w; int vsub = desc->log2_chroma_h; av_freep(&s->buf); s->buf = av_mallocz((FFALIGN(inlink->w, 16) * (s->radius + 1) / 2 + 32) * sizeof(uint16_t)); if (!s->buf) return AVERROR(ENOMEM); s->chroma_w = FF_CEIL_RSHIFT(inlink->w, hsub); s->chroma_h = FF_CEIL_RSHIFT(inlink->h, vsub); s->chroma_r = av_clip(((((s->radius >> hsub) + (s->radius >> vsub)) / 2 ) + 1) & ~1, 4, 32); return 0; } static int filter_frame(AVFilterLink *inlink, AVFrame *in) { GradFunContext *s = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int p, direct; if (av_frame_is_writable(in)) { direct = 1; out = in; } else { direct = 0; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } for (p = 0; p < 4 && in->data[p] && in->linesize[p]; p++) { int w = inlink->w; int h = inlink->h; int r = s->radius; if (p) { w = s->chroma_w; h = s->chroma_h; r = s->chroma_r; } if (FFMIN(w, h) > 2 * r) filter(s, out->data[p], in->data[p], w, h, out->linesize[p], in->linesize[p], r); else if (out->data[p] != in->data[p]) av_image_copy_plane(out->data[p], out->linesize[p], in->data[p], in->linesize[p], w, h); } if (!direct) av_frame_free(&in); return ff_filter_frame(outlink, out); } #define OFFSET(x) offsetof(GradFunContext, x) #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM static const AVOption gradfun_options[] = { { "strength", "The maximum amount by which the filter will change any one pixel.", OFFSET(strength), AV_OPT_TYPE_FLOAT, { .dbl = 1.2 }, 0.51, 64, FLAGS }, { "radius", "The neighborhood to fit the gradient to.", OFFSET(radius), AV_OPT_TYPE_INT, { .i64 = 16 }, 4, 32, FLAGS }, { NULL }, }; AVFILTER_DEFINE_CLASS(gradfun); static const AVFilterPad avfilter_vf_gradfun_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .config_props = config_input, .filter_frame = filter_frame, }, { NULL } }; static const AVFilterPad avfilter_vf_gradfun_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, }, { NULL } }; AVFilter avfilter_vf_gradfun = { .name = "gradfun", .description = NULL_IF_CONFIG_SMALL("Debands video quickly using gradients."), .priv_size = sizeof(GradFunContext), .priv_class = &gradfun_class, .init = init, .uninit = uninit, .query_formats = query_formats, .inputs = avfilter_vf_gradfun_inputs, .outputs = avfilter_vf_gradfun_outputs, .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC, };
./CrossVul/dataset_final_sorted/CWE-119/c/good_5733_4
crossvul-cpp_data_good_671_1
/** * FreeRDP: A Remote Desktop Protocol Implementation * ZGFX (RDP8) Bulk Data Compression * * Copyright 2014 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2017 Armin Novak <armin.novak@thincast.com> * Copyright 2017 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/bitstream.h> #include <freerdp/log.h> #include <freerdp/codec/zgfx.h> #define TAG FREERDP_TAG("codec") /** * RDP8 Compressor Limits: * * Maximum number of uncompressed bytes in a single segment: 65535 * Maximum match distance / minimum history size: 2500000 bytes. * Maximum number of segments: 65535 * Maximum expansion of a segment (when compressed size exceeds uncompressed): 1000 bytes * Minimum match length: 3 bytes */ struct _ZGFX_TOKEN { UINT32 prefixLength; UINT32 prefixCode; UINT32 valueBits; UINT32 tokenType; UINT32 valueBase; }; typedef struct _ZGFX_TOKEN ZGFX_TOKEN; struct _ZGFX_CONTEXT { BOOL Compressor; const BYTE* pbInputCurrent; const BYTE* pbInputEnd; UINT32 bits; UINT32 cBitsRemaining; UINT32 BitsCurrent; UINT32 cBitsCurrent; BYTE OutputBuffer[65536]; UINT32 OutputCount; BYTE HistoryBuffer[2500000]; UINT32 HistoryIndex; UINT32 HistoryBufferSize; }; static const ZGFX_TOKEN ZGFX_TOKEN_TABLE[] = { // len code vbits type vbase { 1, 0, 8, 0, 0 }, // 0 { 5, 17, 5, 1, 0 }, // 10001 { 5, 18, 7, 1, 32 }, // 10010 { 5, 19, 9, 1, 160 }, // 10011 { 5, 20, 10, 1, 672 }, // 10100 { 5, 21, 12, 1, 1696 }, // 10101 { 5, 24, 0, 0, 0x00 }, // 11000 { 5, 25, 0, 0, 0x01 }, // 11001 { 6, 44, 14, 1, 5792 }, // 101100 { 6, 45, 15, 1, 22176 }, // 101101 { 6, 52, 0, 0, 0x02 }, // 110100 { 6, 53, 0, 0, 0x03 }, // 110101 { 6, 54, 0, 0, 0xFF }, // 110110 { 7, 92, 18, 1, 54944 }, // 1011100 { 7, 93, 20, 1, 317088 }, // 1011101 { 7, 110, 0, 0, 0x04 }, // 1101110 { 7, 111, 0, 0, 0x05 }, // 1101111 { 7, 112, 0, 0, 0x06 }, // 1110000 { 7, 113, 0, 0, 0x07 }, // 1110001 { 7, 114, 0, 0, 0x08 }, // 1110010 { 7, 115, 0, 0, 0x09 }, // 1110011 { 7, 116, 0, 0, 0x0A }, // 1110100 { 7, 117, 0, 0, 0x0B }, // 1110101 { 7, 118, 0, 0, 0x3A }, // 1110110 { 7, 119, 0, 0, 0x3B }, // 1110111 { 7, 120, 0, 0, 0x3C }, // 1111000 { 7, 121, 0, 0, 0x3D }, // 1111001 { 7, 122, 0, 0, 0x3E }, // 1111010 { 7, 123, 0, 0, 0x3F }, // 1111011 { 7, 124, 0, 0, 0x40 }, // 1111100 { 7, 125, 0, 0, 0x80 }, // 1111101 { 8, 188, 20, 1, 1365664 }, // 10111100 { 8, 189, 21, 1, 2414240 }, // 10111101 { 8, 252, 0, 0, 0x0C }, // 11111100 { 8, 253, 0, 0, 0x38 }, // 11111101 { 8, 254, 0, 0, 0x39 }, // 11111110 { 8, 255, 0, 0, 0x66 }, // 11111111 { 9, 380, 22, 1, 4511392 }, // 101111100 { 9, 381, 23, 1, 8705696 }, // 101111101 { 9, 382, 24, 1, 17094304 }, // 101111110 { 0 } }; static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits) { if (!_zgfx) return FALSE; while (_zgfx->cBitsCurrent < _nbits) { _zgfx->BitsCurrent <<= 8; if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd) _zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++; _zgfx->cBitsCurrent += 8; } _zgfx->cBitsRemaining -= _nbits; _zgfx->cBitsCurrent -= _nbits; _zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent; _zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1); } static void zgfx_history_buffer_ring_write(ZGFX_CONTEXT* zgfx, const BYTE* src, size_t count) { UINT32 front; if (count <= 0) return; if (count > zgfx->HistoryBufferSize) { const size_t residue = count - zgfx->HistoryBufferSize; count = zgfx->HistoryBufferSize; src += residue; zgfx->HistoryIndex = (zgfx->HistoryIndex + residue) % zgfx->HistoryBufferSize; } if (zgfx->HistoryIndex + count <= zgfx->HistoryBufferSize) { CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, count); if ((zgfx->HistoryIndex += count) == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; } else { front = zgfx->HistoryBufferSize - zgfx->HistoryIndex; CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, front); CopyMemory(zgfx->HistoryBuffer, &src[front], count - front); zgfx->HistoryIndex = count - front; } } static void zgfx_history_buffer_ring_read(ZGFX_CONTEXT* zgfx, int offset, BYTE* dst, UINT32 count) { UINT32 front; UINT32 index; UINT32 bytes; UINT32 valid; UINT32 bytesLeft; BYTE* dptr = dst; BYTE* origDst = dst; if (count <= 0) return; bytesLeft = count; index = (zgfx->HistoryIndex + zgfx->HistoryBufferSize - offset) % zgfx->HistoryBufferSize; bytes = MIN(bytesLeft, offset); if ((index + bytes) <= zgfx->HistoryBufferSize) { CopyMemory(dptr, &(zgfx->HistoryBuffer[index]), bytes); } else { front = zgfx->HistoryBufferSize - index; CopyMemory(dptr, &(zgfx->HistoryBuffer[index]), front); CopyMemory(&dptr[front], zgfx->HistoryBuffer, bytes - front); } if ((bytesLeft -= bytes) == 0) return; dptr += bytes; valid = bytes; do { bytes = valid; if (bytes > bytesLeft) bytes = bytesLeft; CopyMemory(dptr, origDst, bytes); dptr += bytes; valid <<= 1; } while ((bytesLeft -= bytes) > 0); } static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize) { BYTE c; BYTE flags; UINT32 extra = 0; int opIndex; int haveBits; int inPrefix; UINT32 count; UINT32 distance; BYTE* pbSegment; size_t cbSegment = segmentSize - 1; if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1)) return FALSE; Stream_Read_UINT8(stream, flags); /* header (1 byte) */ zgfx->OutputCount = 0; pbSegment = Stream_Pointer(stream); Stream_Seek(stream, cbSegment); if (!(flags & PACKET_COMPRESSED)) { zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment); CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); zgfx->OutputCount = cbSegment; return TRUE; } zgfx->pbInputCurrent = pbSegment; zgfx->pbInputEnd = &pbSegment[cbSegment - 1]; /* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */ zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; while (zgfx->cBitsRemaining) { haveBits = 0; inPrefix = 0; for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++) { while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength) { zgfx_GetBits(zgfx, 1); inPrefix = (inPrefix << 1) + zgfx->bits; haveBits++; } if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode) { if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0) { /* Literal */ zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits); zgfx->HistoryBuffer[zgfx->HistoryIndex] = c; if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; zgfx->OutputBuffer[zgfx->OutputCount++] = c; } else { zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits; if (distance != 0) { /* Match */ zgfx_GetBits(zgfx, 1); if (zgfx->bits == 0) { count = 3; } else { count = 4; extra = 2; zgfx_GetBits(zgfx, 1); while (zgfx->bits == 1) { count *= 2; extra++; zgfx_GetBits(zgfx, 1); } zgfx_GetBits(zgfx, extra); count += zgfx->bits; } zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx->OutputCount += count; } else { /* Unencoded */ zgfx_GetBits(zgfx, 15); count = zgfx->bits; zgfx->cBitsRemaining -= zgfx->cBitsCurrent; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count); zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count); zgfx->pbInputCurrent += count; zgfx->cBitsRemaining -= (8 * count); zgfx->OutputCount += count; } } break; } } } return TRUE; } int zgfx_decompress(ZGFX_CONTEXT* zgfx, const BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32 flags) { int status = -1; BYTE descriptor; wStream* stream = Stream_New((BYTE*)pSrcData, SrcSize); if (!stream) return -1; if (Stream_GetRemainingLength(stream) < 1) goto fail; Stream_Read_UINT8(stream, descriptor); /* descriptor (1 byte) */ if (descriptor == ZGFX_SEGMENTED_SINGLE) { if (!zgfx_decompress_segment(zgfx, stream, Stream_GetRemainingLength(stream))) goto fail; *ppDstData = NULL; if (zgfx->OutputCount > 0) *ppDstData = (BYTE*) malloc(zgfx->OutputCount); if (!*ppDstData) goto fail; *pDstSize = zgfx->OutputCount; CopyMemory(*ppDstData, zgfx->OutputBuffer, zgfx->OutputCount); } else if (descriptor == ZGFX_SEGMENTED_MULTIPART) { UINT32 segmentSize; UINT16 segmentNumber; UINT16 segmentCount; UINT32 uncompressedSize; BYTE* pConcatenated; size_t used = 0; if (Stream_GetRemainingLength(stream) < 6) goto fail; Stream_Read_UINT16(stream, segmentCount); /* segmentCount (2 bytes) */ Stream_Read_UINT32(stream, uncompressedSize); /* uncompressedSize (4 bytes) */ if (Stream_GetRemainingLength(stream) < segmentCount * sizeof(UINT32)) goto fail; pConcatenated = (BYTE*) malloc(uncompressedSize); if (!pConcatenated) goto fail; *ppDstData = pConcatenated; *pDstSize = uncompressedSize; for (segmentNumber = 0; segmentNumber < segmentCount; segmentNumber++) { if (Stream_GetRemainingLength(stream) < sizeof(UINT32)) goto fail; Stream_Read_UINT32(stream, segmentSize); /* segmentSize (4 bytes) */ if (!zgfx_decompress_segment(zgfx, stream, segmentSize)) goto fail; if (zgfx->OutputCount > UINT32_MAX - used) goto fail; if (used + zgfx->OutputCount > uncompressedSize) goto fail; CopyMemory(pConcatenated, zgfx->OutputBuffer, zgfx->OutputCount); pConcatenated += zgfx->OutputCount; used += zgfx->OutputCount; } } else { goto fail; } status = 1; fail: Stream_Free(stream, FALSE); return status; } static BOOL zgfx_compress_segment(ZGFX_CONTEXT* zgfx, wStream* s, const BYTE* pSrcData, UINT32 SrcSize, UINT32* pFlags) { /* FIXME: Currently compression not implemented. Just copy the raw source */ if (!Stream_EnsureRemainingCapacity(s, SrcSize + 1)) { WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); return FALSE; } (*pFlags) |= ZGFX_PACKET_COMPR_TYPE_RDP8; /* RDP 8.0 compression format */ Stream_Write_UINT8(s, (*pFlags)); /* header (1 byte) */ Stream_Write(s, pSrcData, SrcSize); return TRUE; } int zgfx_compress_to_stream(ZGFX_CONTEXT* zgfx, wStream* sDst, const BYTE* pUncompressed, UINT32 uncompressedSize, UINT32* pFlags) { int fragment; UINT16 maxLength; UINT32 totalLength; size_t posSegmentCount = 0; const BYTE* pSrcData; int status = 0; maxLength = ZGFX_SEGMENTED_MAXSIZE; totalLength = uncompressedSize; pSrcData = pUncompressed; for (fragment = 0; (totalLength > 0) || (fragment == 0); fragment++) { UINT32 SrcSize; size_t posDstSize; size_t posDataStart; UINT32 DstSize; SrcSize = (totalLength > maxLength) ? maxLength : totalLength; posDstSize = 0; totalLength -= SrcSize; /* Ensure we have enough space for headers */ if (!Stream_EnsureRemainingCapacity(sDst, 12)) { WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); return -1; } if (fragment == 0) { /* First fragment */ /* descriptor (1 byte) */ Stream_Write_UINT8(sDst, (totalLength == 0) ? ZGFX_SEGMENTED_SINGLE : ZGFX_SEGMENTED_MULTIPART); if (totalLength > 0) { posSegmentCount = Stream_GetPosition(sDst); /* segmentCount (2 bytes) */ Stream_Seek(sDst, 2); Stream_Write_UINT32(sDst, uncompressedSize); /* uncompressedSize (4 bytes) */ } } if (fragment > 0 || totalLength > 0) { /* Multipart */ posDstSize = Stream_GetPosition(sDst); /* size (4 bytes) */ Stream_Seek(sDst, 4); } posDataStart = Stream_GetPosition(sDst); if (!zgfx_compress_segment(zgfx, sDst, pSrcData, SrcSize, pFlags)) return -1; if (posDstSize) { /* Fill segment data size */ DstSize = Stream_GetPosition(sDst) - posDataStart; Stream_SetPosition(sDst, posDstSize); Stream_Write_UINT32(sDst, DstSize); Stream_SetPosition(sDst, posDataStart + DstSize); } pSrcData += SrcSize; } Stream_SealLength(sDst); /* fill back segmentCount */ if (posSegmentCount) { Stream_SetPosition(sDst, posSegmentCount); Stream_Write_UINT16(sDst, fragment); Stream_SetPosition(sDst, Stream_Length(sDst)); } return status; } int zgfx_compress(ZGFX_CONTEXT* zgfx, const BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32* pFlags) { int status; wStream* s = Stream_New(NULL, SrcSize); status = zgfx_compress_to_stream(zgfx, s, pSrcData, SrcSize, pFlags); (*ppDstData) = Stream_Buffer(s); (*pDstSize) = Stream_GetPosition(s); Stream_Free(s, FALSE); return status; } void zgfx_context_reset(ZGFX_CONTEXT* zgfx, BOOL flush) { zgfx->HistoryIndex = 0; } ZGFX_CONTEXT* zgfx_context_new(BOOL Compressor) { ZGFX_CONTEXT* zgfx; zgfx = (ZGFX_CONTEXT*) calloc(1, sizeof(ZGFX_CONTEXT)); if (zgfx) { zgfx->Compressor = Compressor; zgfx->HistoryBufferSize = sizeof(zgfx->HistoryBuffer); zgfx_context_reset(zgfx, FALSE); } return zgfx; } void zgfx_context_free(ZGFX_CONTEXT* zgfx) { free(zgfx); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_671_1
crossvul-cpp_data_bad_5079_1
/* * Packet matching code. * * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling * Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org> * Copyright (C) 2006-2010 Patrick McHardy <kaber@trash.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/cache.h> #include <linux/capability.h> #include <linux/skbuff.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/netdevice.h> #include <linux/module.h> #include <linux/icmp.h> #include <net/ip.h> #include <net/compat.h> #include <asm/uaccess.h> #include <linux/mutex.h> #include <linux/proc_fs.h> #include <linux/err.h> #include <linux/cpumask.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_ipv4/ip_tables.h> #include <net/netfilter/nf_log.h> #include "../../netfilter/xt_repldata.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("Netfilter Core Team <coreteam@netfilter.org>"); MODULE_DESCRIPTION("IPv4 packet filter"); /*#define DEBUG_IP_FIREWALL*/ /*#define DEBUG_ALLOW_ALL*/ /* Useful for remote debugging */ /*#define DEBUG_IP_FIREWALL_USER*/ #ifdef DEBUG_IP_FIREWALL #define dprintf(format, args...) pr_info(format , ## args) #else #define dprintf(format, args...) #endif #ifdef DEBUG_IP_FIREWALL_USER #define duprintf(format, args...) pr_info(format , ## args) #else #define duprintf(format, args...) #endif #ifdef CONFIG_NETFILTER_DEBUG #define IP_NF_ASSERT(x) WARN_ON(!(x)) #else #define IP_NF_ASSERT(x) #endif #if 0 /* All the better to debug you with... */ #define static #define inline #endif void *ipt_alloc_initial_table(const struct xt_table *info) { return xt_alloc_initial_table(ipt, IPT); } EXPORT_SYMBOL_GPL(ipt_alloc_initial_table); /* Returns whether matches rule or not. */ /* Performance critical - called for every packet */ static inline bool ip_packet_match(const struct iphdr *ip, const char *indev, const char *outdev, const struct ipt_ip *ipinfo, int isfrag) { unsigned long ret; #define FWINV(bool, invflg) ((bool) ^ !!(ipinfo->invflags & (invflg))) if (FWINV((ip->saddr&ipinfo->smsk.s_addr) != ipinfo->src.s_addr, IPT_INV_SRCIP) || FWINV((ip->daddr&ipinfo->dmsk.s_addr) != ipinfo->dst.s_addr, IPT_INV_DSTIP)) { dprintf("Source or dest mismatch.\n"); dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n", &ip->saddr, &ipinfo->smsk.s_addr, &ipinfo->src.s_addr, ipinfo->invflags & IPT_INV_SRCIP ? " (INV)" : ""); dprintf("DST: %pI4 Mask: %pI4 Target: %pI4.%s\n", &ip->daddr, &ipinfo->dmsk.s_addr, &ipinfo->dst.s_addr, ipinfo->invflags & IPT_INV_DSTIP ? " (INV)" : ""); return false; } ret = ifname_compare_aligned(indev, ipinfo->iniface, ipinfo->iniface_mask); if (FWINV(ret != 0, IPT_INV_VIA_IN)) { dprintf("VIA in mismatch (%s vs %s).%s\n", indev, ipinfo->iniface, ipinfo->invflags & IPT_INV_VIA_IN ? " (INV)" : ""); return false; } ret = ifname_compare_aligned(outdev, ipinfo->outiface, ipinfo->outiface_mask); if (FWINV(ret != 0, IPT_INV_VIA_OUT)) { dprintf("VIA out mismatch (%s vs %s).%s\n", outdev, ipinfo->outiface, ipinfo->invflags & IPT_INV_VIA_OUT ? " (INV)" : ""); return false; } /* Check specific protocol */ if (ipinfo->proto && FWINV(ip->protocol != ipinfo->proto, IPT_INV_PROTO)) { dprintf("Packet protocol %hi does not match %hi.%s\n", ip->protocol, ipinfo->proto, ipinfo->invflags & IPT_INV_PROTO ? " (INV)" : ""); return false; } /* If we have a fragment rule but the packet is not a fragment * then we return zero */ if (FWINV((ipinfo->flags&IPT_F_FRAG) && !isfrag, IPT_INV_FRAG)) { dprintf("Fragment rule but not fragment.%s\n", ipinfo->invflags & IPT_INV_FRAG ? " (INV)" : ""); return false; } return true; } static bool ip_checkentry(const struct ipt_ip *ip) { if (ip->flags & ~IPT_F_MASK) { duprintf("Unknown flag bits set: %08X\n", ip->flags & ~IPT_F_MASK); return false; } if (ip->invflags & ~IPT_INV_MASK) { duprintf("Unknown invflag bits set: %08X\n", ip->invflags & ~IPT_INV_MASK); return false; } return true; } static unsigned int ipt_error(struct sk_buff *skb, const struct xt_action_param *par) { net_info_ratelimited("error: `%s'\n", (const char *)par->targinfo); return NF_DROP; } /* Performance critical */ static inline struct ipt_entry * get_entry(const void *base, unsigned int offset) { return (struct ipt_entry *)(base + offset); } /* All zeroes == unconditional rule. */ /* Mildly perf critical (only if packet tracing is on) */ static inline bool unconditional(const struct ipt_ip *ip) { static const struct ipt_ip uncond; return memcmp(ip, &uncond, sizeof(uncond)) == 0; #undef FWINV } /* for const-correctness */ static inline const struct xt_entry_target * ipt_get_target_c(const struct ipt_entry *e) { return ipt_get_target((struct ipt_entry *)e); } #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE) static const char *const hooknames[] = { [NF_INET_PRE_ROUTING] = "PREROUTING", [NF_INET_LOCAL_IN] = "INPUT", [NF_INET_FORWARD] = "FORWARD", [NF_INET_LOCAL_OUT] = "OUTPUT", [NF_INET_POST_ROUTING] = "POSTROUTING", }; enum nf_ip_trace_comments { NF_IP_TRACE_COMMENT_RULE, NF_IP_TRACE_COMMENT_RETURN, NF_IP_TRACE_COMMENT_POLICY, }; static const char *const comments[] = { [NF_IP_TRACE_COMMENT_RULE] = "rule", [NF_IP_TRACE_COMMENT_RETURN] = "return", [NF_IP_TRACE_COMMENT_POLICY] = "policy", }; static struct nf_loginfo trace_loginfo = { .type = NF_LOG_TYPE_LOG, .u = { .log = { .level = 4, .logflags = NF_LOG_MASK, }, }, }; /* Mildly perf critical (only if packet tracing is on) */ static inline int get_chainname_rulenum(const struct ipt_entry *s, const struct ipt_entry *e, const char *hookname, const char **chainname, const char **comment, unsigned int *rulenum) { const struct xt_standard_target *t = (void *)ipt_get_target_c(s); if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) { /* Head of user chain: ERROR target with chainname */ *chainname = t->target.data; (*rulenum) = 0; } else if (s == e) { (*rulenum)++; if (s->target_offset == sizeof(struct ipt_entry) && strcmp(t->target.u.kernel.target->name, XT_STANDARD_TARGET) == 0 && t->verdict < 0 && unconditional(&s->ip)) { /* Tail of chains: STANDARD target (return/policy) */ *comment = *chainname == hookname ? comments[NF_IP_TRACE_COMMENT_POLICY] : comments[NF_IP_TRACE_COMMENT_RETURN]; } return 1; } else (*rulenum)++; return 0; } static void trace_packet(struct net *net, const struct sk_buff *skb, unsigned int hook, const struct net_device *in, const struct net_device *out, const char *tablename, const struct xt_table_info *private, const struct ipt_entry *e) { const struct ipt_entry *root; const char *hookname, *chainname, *comment; const struct ipt_entry *iter; unsigned int rulenum = 0; root = get_entry(private->entries, private->hook_entry[hook]); hookname = chainname = hooknames[hook]; comment = comments[NF_IP_TRACE_COMMENT_RULE]; xt_entry_foreach(iter, root, private->size - private->hook_entry[hook]) if (get_chainname_rulenum(iter, e, hookname, &chainname, &comment, &rulenum) != 0) break; nf_log_trace(net, AF_INET, hook, skb, in, out, &trace_loginfo, "TRACE: %s:%s:%s:%u ", tablename, chainname, comment, rulenum); } #endif static inline struct ipt_entry *ipt_next_entry(const struct ipt_entry *entry) { return (void *)entry + entry->next_offset; } /* Returns one of the generic firewall policies, like NF_ACCEPT. */ unsigned int ipt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); const struct iphdr *ip; /* Initializing verdict to NF_DROP keeps gcc happy. */ unsigned int verdict = NF_DROP; const char *indev, *outdev; const void *table_base; struct ipt_entry *e, **jumpstack; unsigned int stackidx, cpu; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; /* Initialization */ stackidx = 0; ip = ip_hdr(skb); indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; /* We handle fragments by dealing with the first fragment as * if it was a normal packet. All other fragments are treated * normally, except that they will NEVER match rules that ask * things we don't know, ie. tcp syn flag or ports). If the * rule is also a fragment-specific rule, non-fragments won't * match it. */ acpar.fragoff = ntohs(ip->frag_off) & IP_OFFSET; acpar.thoff = ip_hdrlen(skb); acpar.hotdrop = false; acpar.net = state->net; acpar.in = state->in; acpar.out = state->out; acpar.family = NFPROTO_IPV4; acpar.hooknum = hook; IP_NF_ASSERT(table->valid_hooks & (1 << hook)); local_bh_disable(); addend = xt_write_recseq_begin(); private = table->private; cpu = smp_processor_id(); /* * Ensure we load private-> members after we've fetched the base * pointer. */ smp_read_barrier_depends(); table_base = private->entries; jumpstack = (struct ipt_entry **)private->jumpstack[cpu]; /* Switch to alternate jumpstack if we're being invoked via TEE. * TEE issues XT_CONTINUE verdict on original skb so we must not * clobber the jumpstack. * * For recursion via REJECT or SYNPROXY the stack will be clobbered * but it is no problem since absolute verdict is issued by these. */ if (static_key_false(&xt_tee_enabled)) jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated); e = get_entry(table_base, private->hook_entry[hook]); pr_debug("Entering %s(hook %u), UF %p\n", table->name, hook, get_entry(table_base, private->underflow[hook])); do { const struct xt_entry_target *t; const struct xt_entry_match *ematch; struct xt_counters *counter; IP_NF_ASSERT(e); if (!ip_packet_match(ip, indev, outdev, &e->ip, acpar.fragoff)) { no_match: e = ipt_next_entry(e); continue; } xt_ematch_foreach(ematch, e) { acpar.match = ematch->u.kernel.match; acpar.matchinfo = ematch->data; if (!acpar.match->match(skb, &acpar)) goto no_match; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, skb->len, 1); t = ipt_get_target(e); IP_NF_ASSERT(t->u.kernel.target); #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE) /* The packet is traced: log it */ if (unlikely(skb->nf_trace)) trace_packet(state->net, skb, hook, state->in, state->out, table->name, private, e); #endif /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) { e = get_entry(table_base, private->underflow[hook]); pr_debug("Underflow (this is normal) " "to %p\n", e); } else { e = jumpstack[--stackidx]; pr_debug("Pulled %p out from pos %u\n", e, stackidx); e = ipt_next_entry(e); } continue; } if (table_base + v != ipt_next_entry(e) && !(e->ip.flags & IPT_F_GOTO)) { jumpstack[stackidx++] = e; pr_debug("Pushed %p into pos %u\n", e, stackidx - 1); } e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); /* Target might have changed stuff. */ ip = ip_hdr(skb); if (verdict == XT_CONTINUE) e = ipt_next_entry(e); else /* Verdict */ break; } while (!acpar.hotdrop); pr_debug("Exiting %s; sp at %u\n", __func__, stackidx); xt_write_recseq_end(addend); local_bh_enable(); #ifdef DEBUG_ALLOW_ALL return NF_ACCEPT; #else if (acpar.hotdrop) return NF_DROP; else return verdict; #endif } /* Figures out from what hook each rule can be called: returns 0 if there are loops. Puts hook bitmask in comefrom. */ static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset to 0 as we leave), and comefrom to save source hook bitmask */ for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct ipt_entry *e = (struct ipt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)ipt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { pr_err("iptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct ipt_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->ip)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last big jump. */ do { e->comefrom ^= (1<<NF_INET_NUMHOOKS); #ifdef DEBUG_IP_FIREWALL_USER if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { duprintf("Back unset " "on hook %u " "rule %u\n", hook, pos); } #endif oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct ipt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct ipt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct ipt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct ipt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } static void cleanup_match(struct xt_entry_match *m, struct net *net) { struct xt_mtdtor_param par; par.net = net; par.match = m->u.kernel.match; par.matchinfo = m->data; par.family = NFPROTO_IPV4; if (par.match->destroy != NULL) par.match->destroy(&par); module_put(par.match->me); } static int check_entry(const struct ipt_entry *e) { const struct xt_entry_target *t; if (!ip_checkentry(&e->ip)) return -EINVAL; if (e->target_offset + sizeof(struct xt_entry_target) > e->next_offset) return -EINVAL; t = ipt_get_target_c(e); if (e->target_offset + t->u.target_size > e->next_offset) return -EINVAL; return 0; } static int check_match(struct xt_entry_match *m, struct xt_mtchk_param *par) { const struct ipt_ip *ip = par->entryinfo; int ret; par->match = m->u.kernel.match; par->matchinfo = m->data; ret = xt_check_match(par, m->u.match_size - sizeof(*m), ip->proto, ip->invflags & IPT_INV_PROTO); if (ret < 0) { duprintf("check failed for `%s'.\n", par->match->name); return ret; } return 0; } static int find_check_match(struct xt_entry_match *m, struct xt_mtchk_param *par) { struct xt_match *match; int ret; match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name, m->u.user.revision); if (IS_ERR(match)) { duprintf("find_check_match: `%s' not found\n", m->u.user.name); return PTR_ERR(match); } m->u.kernel.match = match; ret = check_match(m, par); if (ret) goto err; return 0; err: module_put(m->u.kernel.match->me); return ret; } static int check_target(struct ipt_entry *e, struct net *net, const char *name) { struct xt_entry_target *t = ipt_get_target(e); struct xt_tgchk_param par = { .net = net, .table = name, .entryinfo = e, .target = t->u.kernel.target, .targinfo = t->data, .hook_mask = e->comefrom, .family = NFPROTO_IPV4, }; int ret; ret = xt_check_target(&par, t->u.target_size - sizeof(*t), e->ip.proto, e->ip.invflags & IPT_INV_PROTO); if (ret < 0) { duprintf("check failed for `%s'.\n", t->u.kernel.target->name); return ret; } return 0; } static int find_check_entry(struct ipt_entry *e, struct net *net, const char *name, unsigned int size) { struct xt_entry_target *t; struct xt_target *target; int ret; unsigned int j; struct xt_mtchk_param mtpar; struct xt_entry_match *ematch; e->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(e->counters.pcnt)) return -ENOMEM; j = 0; mtpar.net = net; mtpar.table = name; mtpar.entryinfo = &e->ip; mtpar.hook_mask = e->comefrom; mtpar.family = NFPROTO_IPV4; xt_ematch_foreach(ematch, e) { ret = find_check_match(ematch, &mtpar); if (ret != 0) goto cleanup_matches; ++j; } t = ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("find_check_entry: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto cleanup_matches; } t->u.kernel.target = target; ret = check_target(e, net, name); if (ret) goto err; return 0; err: module_put(t->u.kernel.target->me); cleanup_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; cleanup_match(ematch, net); } xt_percpu_counter_free(e->counters.pcnt); return ret; } static bool check_underflow(const struct ipt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(&e->ip)) return false; t = ipt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; } static int check_entry_size_and_hooks(struct ipt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 || (unsigned char *)e + sizeof(struct ipt_entry) >= limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } static void cleanup_entry(struct ipt_entry *e, struct net *net) { struct xt_tgdtor_param par; struct xt_entry_target *t; struct xt_entry_match *ematch; /* Cleanup all matches */ xt_ematch_foreach(ematch, e) cleanup_match(ematch, net); t = ipt_get_target(e); par.net = net; par.target = t->u.kernel.target; par.targinfo = t->data; par.family = NFPROTO_IPV4; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); xt_percpu_counter_free(e->counters.pcnt); } /* Checks and translates the user-supplied table segment (held in newinfo) */ static int translate_table(struct net *net, struct xt_table_info *newinfo, void *entry0, const struct ipt_replace *repl) { struct ipt_entry *iter; unsigned int i; int ret = 0; newinfo->size = repl->size; newinfo->number = repl->num_entries; /* Init all hooks to impossible value. */ for (i = 0; i < NF_INET_NUMHOOKS; i++) { newinfo->hook_entry[i] = 0xFFFFFFFF; newinfo->underflow[i] = 0xFFFFFFFF; } duprintf("translate_table: size %u\n", newinfo->size); i = 0; /* Walk through entries, checking offsets. */ xt_entry_foreach(iter, entry0, newinfo->size) { ret = check_entry_size_and_hooks(iter, newinfo, entry0, entry0 + repl->size, repl->hook_entry, repl->underflow, repl->valid_hooks); if (ret != 0) return ret; ++i; if (strcmp(ipt_get_target(iter)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } if (i != repl->num_entries) { duprintf("translate_table: %u not %u entries\n", i, repl->num_entries); return -EINVAL; } /* Check hooks all assigned */ for (i = 0; i < NF_INET_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(repl->valid_hooks & (1 << i))) continue; if (newinfo->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, repl->hook_entry[i]); return -EINVAL; } if (newinfo->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, repl->underflow[i]); return -EINVAL; } } if (!mark_source_chains(newinfo, repl->valid_hooks, entry0)) return -ELOOP; /* Finally, each sanity check must pass */ i = 0; xt_entry_foreach(iter, entry0, newinfo->size) { ret = find_check_entry(iter, net, repl->name, repl->size); if (ret != 0) break; ++i; } if (ret != 0) { xt_entry_foreach(iter, entry0, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter, net); } return ret; } return ret; } static void get_counters(const struct xt_table_info *t, struct xt_counters counters[]) { struct ipt_entry *iter; unsigned int cpu; unsigned int i; for_each_possible_cpu(cpu) { seqcount_t *s = &per_cpu(xt_recseq, cpu); i = 0; xt_entry_foreach(iter, t->entries, t->size) { struct xt_counters *tmp; u64 bcnt, pcnt; unsigned int start; tmp = xt_get_per_cpu_counter(&iter->counters, cpu); do { start = read_seqcount_begin(s); bcnt = tmp->bcnt; pcnt = tmp->pcnt; } while (read_seqcount_retry(s, start)); ADD_COUNTER(counters[i], bcnt, pcnt); ++i; /* macro does multi eval of i */ } } } static struct xt_counters *alloc_counters(const struct xt_table *table) { unsigned int countersize; struct xt_counters *counters; const struct xt_table_info *private = table->private; /* We need atomic snapshot of counters: rest doesn't change (other than comefrom, which userspace doesn't care about). */ countersize = sizeof(struct xt_counters) * private->number; counters = vzalloc(countersize); if (counters == NULL) return ERR_PTR(-ENOMEM); get_counters(private, counters); return counters; } static int copy_entries_to_user(unsigned int total_size, const struct xt_table *table, void __user *userptr) { unsigned int off, num; const struct ipt_entry *e; struct xt_counters *counters; const struct xt_table_info *private = table->private; int ret = 0; const void *loc_cpu_entry; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); loc_cpu_entry = private->entries; if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) { ret = -EFAULT; goto free_counters; } /* FIXME: use iterator macros --RR */ /* ... then go back and fix counters and names */ for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){ unsigned int i; const struct xt_entry_match *m; const struct xt_entry_target *t; e = (struct ipt_entry *)(loc_cpu_entry + off); if (copy_to_user(userptr + off + offsetof(struct ipt_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } for (i = sizeof(struct ipt_entry); i < e->target_offset; i += m->u.match_size) { m = (void *)e + i; if (copy_to_user(userptr + off + i + offsetof(struct xt_entry_match, u.user.name), m->u.kernel.match->name, strlen(m->u.kernel.match->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } t = ipt_get_target_c(e); if (copy_to_user(userptr + off + e->target_offset + offsetof(struct xt_entry_target, u.user.name), t->u.kernel.target->name, strlen(t->u.kernel.target->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } free_counters: vfree(counters); return ret; } #ifdef CONFIG_COMPAT static void compat_standard_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v > 0) v += xt_compat_calc_jump(AF_INET, v); memcpy(dst, &v, sizeof(v)); } static int compat_standard_to_user(void __user *dst, const void *src) { compat_int_t cv = *(int *)src; if (cv > 0) cv -= xt_compat_calc_jump(AF_INET, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } static int compat_calc_entry(const struct ipt_entry *e, const struct xt_table_info *info, const void *base, struct xt_table_info *newinfo) { const struct xt_entry_match *ematch; const struct xt_entry_target *t; unsigned int entry_offset; int off, i, ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - base; xt_ematch_foreach(ematch, e) off += xt_compat_match_offset(ematch->u.kernel.match); t = ipt_get_target_c(e); off += xt_compat_target_offset(t->u.kernel.target); newinfo->size -= off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_INET_NUMHOOKS; i++) { if (info->hook_entry[i] && (e < (struct ipt_entry *)(base + info->hook_entry[i]))) newinfo->hook_entry[i] -= off; if (info->underflow[i] && (e < (struct ipt_entry *)(base + info->underflow[i]))) newinfo->underflow[i] -= off; } return 0; } static int compat_table_info(const struct xt_table_info *info, struct xt_table_info *newinfo) { struct ipt_entry *iter; const void *loc_cpu_entry; int ret; if (!newinfo || !info) return -EINVAL; /* we dont care about newinfo->entries */ memcpy(newinfo, info, offsetof(struct xt_table_info, entries)); newinfo->initial_entries = 0; loc_cpu_entry = info->entries; xt_compat_init_offsets(AF_INET, info->number); xt_entry_foreach(iter, loc_cpu_entry, info->size) { ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo); if (ret != 0) return ret; } return 0; } #endif static int get_info(struct net *net, void __user *user, const int *len, int compat) { char name[XT_TABLE_MAXNAMELEN]; struct xt_table *t; int ret; if (*len != sizeof(struct ipt_getinfo)) { duprintf("length %u != %zu\n", *len, sizeof(struct ipt_getinfo)); return -EINVAL; } if (copy_from_user(name, user, sizeof(name)) != 0) return -EFAULT; name[XT_TABLE_MAXNAMELEN-1] = '\0'; #ifdef CONFIG_COMPAT if (compat) xt_compat_lock(AF_INET); #endif t = try_then_request_module(xt_find_table_lock(net, AF_INET, name), "iptable_%s", name); if (!IS_ERR_OR_NULL(t)) { struct ipt_getinfo info; const struct xt_table_info *private = t->private; #ifdef CONFIG_COMPAT struct xt_table_info tmp; if (compat) { ret = compat_table_info(private, &tmp); xt_compat_flush_offsets(AF_INET); private = &tmp; } #endif memset(&info, 0, sizeof(info)); info.valid_hooks = t->valid_hooks; memcpy(info.hook_entry, private->hook_entry, sizeof(info.hook_entry)); memcpy(info.underflow, private->underflow, sizeof(info.underflow)); info.num_entries = private->number; info.size = private->size; strcpy(info.name, name); if (copy_to_user(user, &info, *len) != 0) ret = -EFAULT; else ret = 0; xt_table_unlock(t); module_put(t->me); } else ret = t ? PTR_ERR(t) : -ENOENT; #ifdef CONFIG_COMPAT if (compat) xt_compat_unlock(AF_INET); #endif return ret; } static int get_entries(struct net *net, struct ipt_get_entries __user *uptr, const int *len) { int ret; struct ipt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct ipt_get_entries) + get.size) { duprintf("get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } t = xt_find_table_lock(net, AF_INET, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; duprintf("t->private->number = %u\n", private->number); if (get.size == private->size) ret = copy_entries_to_user(private->size, t, uptr->entrytable); else { duprintf("get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; return ret; } static int __do_replace(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info *newinfo, unsigned int num_counters, void __user *counters_ptr) { int ret; struct xt_table *t; struct xt_table_info *oldinfo; struct xt_counters *counters; struct ipt_entry *iter; ret = 0; counters = vzalloc(num_counters * sizeof(struct xt_counters)); if (!counters) { ret = -ENOMEM; goto out; } t = try_then_request_module(xt_find_table_lock(net, AF_INET, name), "iptable_%s", name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free_newinfo_counters_untrans; } /* You lied! */ if (valid_hooks != t->valid_hooks) { duprintf("Valid hook crap: %08X vs %08X\n", valid_hooks, t->valid_hooks); ret = -EINVAL; goto put_module; } oldinfo = xt_replace_table(t, num_counters, newinfo, &ret); if (!oldinfo) goto put_module; /* Update module usage count based on number of rules */ duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n", oldinfo->number, oldinfo->initial_entries, newinfo->number); if ((oldinfo->number > oldinfo->initial_entries) || (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); if ((oldinfo->number > oldinfo->initial_entries) && (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); /* Get the old counters, and synchronize with replace */ get_counters(oldinfo, counters); /* Decrease module usage counts and free resource */ xt_entry_foreach(iter, oldinfo->entries, oldinfo->size) cleanup_entry(iter, net); xt_free_table_info(oldinfo); if (copy_to_user(counters_ptr, counters, sizeof(struct xt_counters) * num_counters) != 0) { /* Silent error, can't fail, new table is already in place */ net_warn_ratelimited("iptables: counters copy to user failed while replacing table\n"); } vfree(counters); xt_table_unlock(t); return ret; put_module: module_put(t->me); xt_table_unlock(t); free_newinfo_counters_untrans: vfree(counters); out: return ret; } static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret; struct ipt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct ipt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_table(net, newinfo, loc_cpu_entry, &tmp); if (ret != 0) goto free_newinfo; duprintf("Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, tmp.counters); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter, net); free_newinfo: xt_free_table_info(newinfo); return ret; } static int do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; const char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct ipt_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, AF_INET, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } #ifdef CONFIG_COMPAT struct compat_ipt_replace { char name[XT_TABLE_MAXNAMELEN]; u32 valid_hooks; u32 num_entries; u32 size; u32 hook_entry[NF_INET_NUMHOOKS]; u32 underflow[NF_INET_NUMHOOKS]; u32 num_counters; compat_uptr_t counters; /* struct xt_counters * */ struct compat_ipt_entry entries[0]; }; static int compat_copy_entry_to_user(struct ipt_entry *e, void __user **dstptr, unsigned int *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_ipt_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; const struct xt_entry_match *ematch; int ret = 0; origsize = *size; ce = (struct compat_ipt_entry __user *)*dstptr; if (copy_to_user(ce, e, sizeof(struct ipt_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_ipt_entry); *size -= sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); xt_ematch_foreach(ematch, e) { ret = xt_compat_match_to_user(ematch, dstptr, size); if (ret != 0) return ret; } target_offset = e->target_offset - (origsize - *size); t = ipt_get_target(e); ret = xt_compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(target_offset, &ce->target_offset) != 0 || put_user(next_offset, &ce->next_offset) != 0) return -EFAULT; return 0; } static int compat_find_calc_match(struct xt_entry_match *m, const char *name, const struct ipt_ip *ip, int *size) { struct xt_match *match; match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name, m->u.user.revision); if (IS_ERR(match)) { duprintf("compat_check_calc_match: `%s' not found\n", m->u.user.name); return PTR_ERR(match); } m->u.kernel.match = match; *size += xt_compat_match_offset(match); return 0; } static void compat_release_entry(struct compat_ipt_entry *e) { struct xt_entry_target *t; struct xt_entry_match *ematch; /* Cleanup all matches */ xt_ematch_foreach(ematch, e) module_put(ematch->u.kernel.match->me); t = compat_ipt_get_target(e); module_put(t->u.kernel.target->me); } static int check_compat_entry_size_and_hooks(struct compat_ipt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ipt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ipt_entry *)e); if (ret) return ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ip, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } static int compat_copy_entry_from_user(struct compat_ipt_entry *e, void **dstptr, unsigned int *size, const char *name, struct xt_table_info *newinfo, unsigned char *base) { struct xt_entry_target *t; struct xt_target *target; struct ipt_entry *de; unsigned int origsize; int ret, h; struct xt_entry_match *ematch; ret = 0; origsize = *size; de = (struct ipt_entry *)*dstptr; memcpy(de, e, sizeof(struct ipt_entry)); memcpy(&de->counters, &e->counters, sizeof(e->counters)); *dstptr += sizeof(struct ipt_entry); *size += sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); xt_ematch_foreach(ematch, e) { ret = xt_compat_match_from_user(ematch, dstptr, size); if (ret != 0) return ret; } de->target_offset = e->target_offset - (origsize - *size); t = compat_ipt_get_target(e); target = t->u.kernel.target; xt_compat_target_from_user(t, dstptr, size); de->next_offset = e->next_offset - (origsize - *size); for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)de - base < newinfo->hook_entry[h]) newinfo->hook_entry[h] -= origsize - *size; if ((unsigned char *)de - base < newinfo->underflow[h]) newinfo->underflow[h] -= origsize - *size; } return ret; } static int compat_check_entry(struct ipt_entry *e, struct net *net, const char *name) { struct xt_entry_match *ematch; struct xt_mtchk_param mtpar; unsigned int j; int ret = 0; e->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(e->counters.pcnt)) return -ENOMEM; j = 0; mtpar.net = net; mtpar.table = name; mtpar.entryinfo = &e->ip; mtpar.hook_mask = e->comefrom; mtpar.family = NFPROTO_IPV4; xt_ematch_foreach(ematch, e) { ret = check_match(ematch, &mtpar); if (ret != 0) goto cleanup_matches; ++j; } ret = check_target(e, net, name); if (ret) goto cleanup_matches; return 0; cleanup_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; cleanup_match(ematch, net); } xt_percpu_counter_free(e->counters.pcnt); return ret; } static int translate_compat_table(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info **pinfo, void **pentry0, unsigned int total_size, unsigned int number, unsigned int *hook_entries, unsigned int *underflows) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_ipt_entry *iter0; struct ipt_entry *iter1; unsigned int size; int ret; info = *pinfo; entry0 = *pentry0; size = total_size; info->number = number; /* Init all hooks to impossible value. */ for (i = 0; i < NF_INET_NUMHOOKS; i++) { info->hook_entry[i] = 0xFFFFFFFF; info->underflow[i] = 0xFFFFFFFF; } duprintf("translate_compat_table: size %u\n", info->size); j = 0; xt_compat_lock(AF_INET); xt_compat_init_offsets(AF_INET, number); /* Walk through entries, checking offsets. */ xt_entry_foreach(iter0, entry0, total_size) { ret = check_compat_entry_size_and_hooks(iter0, info, &size, entry0, entry0 + total_size, hook_entries, underflows, name); if (ret != 0) goto out_unlock; ++j; } ret = -EINVAL; if (j != number) { duprintf("translate_compat_table: %u not %u entries\n", j, number); goto out_unlock; } /* Check hooks all assigned */ for (i = 0; i < NF_INET_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(valid_hooks & (1 << i))) continue; if (info->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, hook_entries[i]); goto out_unlock; } if (info->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, underflows[i]); goto out_unlock; } } ret = -ENOMEM; newinfo = xt_alloc_table_info(size); if (!newinfo) goto out_unlock; newinfo->number = number; for (i = 0; i < NF_INET_NUMHOOKS; i++) { newinfo->hook_entry[i] = info->hook_entry[i]; newinfo->underflow[i] = info->underflow[i]; } entry1 = newinfo->entries; pos = entry1; size = total_size; xt_entry_foreach(iter0, entry0, total_size) { ret = compat_copy_entry_from_user(iter0, &pos, &size, name, newinfo, entry1); if (ret != 0) break; } xt_compat_flush_offsets(AF_INET); xt_compat_unlock(AF_INET); if (ret) goto free_newinfo; ret = -ELOOP; if (!mark_source_chains(newinfo, valid_hooks, entry1)) goto free_newinfo; i = 0; xt_entry_foreach(iter1, entry1, newinfo->size) { ret = compat_check_entry(iter1, net, name); if (ret != 0) break; ++i; if (strcmp(ipt_get_target(iter1)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } if (ret) { /* * The first i matches need cleanup_entry (calls ->destroy) * because they had called ->check already. The other j-i * entries need only release. */ int skip = i; j -= i; xt_entry_foreach(iter0, entry0, newinfo->size) { if (skip-- > 0) continue; if (j-- == 0) break; compat_release_entry(iter0); } xt_entry_foreach(iter1, entry1, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter1, net); } xt_free_table_info(newinfo); return ret; } *pinfo = newinfo; *pentry0 = entry1; xt_free_table_info(info); return 0; free_newinfo: xt_free_table_info(newinfo); out: xt_entry_foreach(iter0, entry0, total_size) { if (j-- == 0) break; compat_release_entry(iter0); } return ret; out_unlock: xt_compat_flush_offsets(AF_INET); xt_compat_unlock(AF_INET); goto out; } static int compat_do_replace(struct net *net, void __user *user, unsigned int len) { int ret; struct compat_ipt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct ipt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.size >= INT_MAX / num_possible_cpus()) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_compat_table(net, tmp.name, tmp.valid_hooks, &newinfo, &loc_cpu_entry, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo; duprintf("compat_do_replace: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, compat_ptr(tmp.counters)); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter, net); free_newinfo: xt_free_table_info(newinfo); return ret; } static int compat_do_ipt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IPT_SO_SET_REPLACE: ret = compat_do_replace(sock_net(sk), user, len); break; case IPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 1); break; default: duprintf("do_ipt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } struct compat_ipt_get_entries { char name[XT_TABLE_MAXNAMELEN]; compat_uint_t size; struct compat_ipt_entry entrytable[0]; }; static int compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table, void __user *userptr) { struct xt_counters *counters; const struct xt_table_info *private = table->private; void __user *pos; unsigned int size; int ret = 0; unsigned int i = 0; struct ipt_entry *iter; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); pos = userptr; size = total_size; xt_entry_foreach(iter, private->entries, total_size) { ret = compat_copy_entry_to_user(iter, &pos, &size, counters, i++); if (ret != 0) break; } vfree(counters); return ret; } static int compat_get_entries(struct net *net, struct compat_ipt_get_entries __user *uptr, int *len) { int ret; struct compat_ipt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct compat_ipt_get_entries) + get.size) { duprintf("compat_get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } xt_compat_lock(AF_INET); t = xt_find_table_lock(net, AF_INET, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; struct xt_table_info info; duprintf("t->private->number = %u\n", private->number); ret = compat_table_info(private, &info); if (!ret && get.size == info.size) { ret = compat_copy_entries_to_user(private->size, t, uptr->entrytable); } else if (!ret) { duprintf("compat_get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } xt_compat_flush_offsets(AF_INET); module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; xt_compat_unlock(AF_INET); return ret; } static int do_ipt_get_ctl(struct sock *, int, void __user *, int *); static int compat_do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 1); break; case IPT_SO_GET_ENTRIES: ret = compat_get_entries(sock_net(sk), user, len); break; default: ret = do_ipt_get_ctl(sk, cmd, user, len); } return ret; } #endif static int do_ipt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IPT_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case IPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: duprintf("do_ipt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case IPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case IPT_SO_GET_REVISION_MATCH: case IPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; int target; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } rev.name[sizeof(rev.name)-1] = 0; if (cmd == IPT_SO_GET_REVISION_TARGET) target = 1; else target = 0; try_then_request_module(xt_find_revision(AF_INET, rev.name, rev.revision, target, &ret), "ipt_%s", rev.name); break; } default: duprintf("do_ipt_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static void __ipt_unregister_table(struct net *net, struct xt_table *table) { struct xt_table_info *private; void *loc_cpu_entry; struct module *table_owner = table->me; struct ipt_entry *iter; private = xt_unregister_table(table); /* Decrease module usage counts and free resources */ loc_cpu_entry = private->entries; xt_entry_foreach(iter, loc_cpu_entry, private->size) cleanup_entry(iter, net); if (private->number > private->initial_entries) module_put(table_owner); xt_free_table_info(private); } int ipt_register_table(struct net *net, const struct xt_table *table, const struct ipt_replace *repl, const struct nf_hook_ops *ops, struct xt_table **res) { int ret; struct xt_table_info *newinfo; struct xt_table_info bootstrap = {0}; void *loc_cpu_entry; struct xt_table *new_table; newinfo = xt_alloc_table_info(repl->size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; memcpy(loc_cpu_entry, repl->entries, repl->size); ret = translate_table(net, newinfo, loc_cpu_entry, repl); if (ret != 0) goto out_free; new_table = xt_register_table(net, table, &bootstrap, newinfo); if (IS_ERR(new_table)) { ret = PTR_ERR(new_table); goto out_free; } /* set res now, will see skbs right after nf_register_net_hooks */ WRITE_ONCE(*res, new_table); ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks)); if (ret != 0) { __ipt_unregister_table(net, new_table); *res = NULL; } return ret; out_free: xt_free_table_info(newinfo); return ret; } void ipt_unregister_table(struct net *net, struct xt_table *table, const struct nf_hook_ops *ops) { nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks)); __ipt_unregister_table(net, table); } /* Returns 1 if the type and code is matched by the range, 0 otherwise */ static inline bool icmp_type_code_match(u_int8_t test_type, u_int8_t min_code, u_int8_t max_code, u_int8_t type, u_int8_t code, bool invert) { return ((test_type == 0xFF) || (type == test_type && code >= min_code && code <= max_code)) ^ invert; } static bool icmp_match(const struct sk_buff *skb, struct xt_action_param *par) { const struct icmphdr *ic; struct icmphdr _icmph; const struct ipt_icmp *icmpinfo = par->matchinfo; /* Must not be a fragment. */ if (par->fragoff != 0) return false; ic = skb_header_pointer(skb, par->thoff, sizeof(_icmph), &_icmph); if (ic == NULL) { /* We've been asked to examine this packet, and we * can't. Hence, no choice but to drop. */ duprintf("Dropping evil ICMP tinygram.\n"); par->hotdrop = true; return false; } return icmp_type_code_match(icmpinfo->type, icmpinfo->code[0], icmpinfo->code[1], ic->type, ic->code, !!(icmpinfo->invflags&IPT_ICMP_INV)); } static int icmp_checkentry(const struct xt_mtchk_param *par) { const struct ipt_icmp *icmpinfo = par->matchinfo; /* Must specify no unknown invflags */ return (icmpinfo->invflags & ~IPT_ICMP_INV) ? -EINVAL : 0; } static struct xt_target ipt_builtin_tg[] __read_mostly = { { .name = XT_STANDARD_TARGET, .targetsize = sizeof(int), .family = NFPROTO_IPV4, #ifdef CONFIG_COMPAT .compatsize = sizeof(compat_int_t), .compat_from_user = compat_standard_from_user, .compat_to_user = compat_standard_to_user, #endif }, { .name = XT_ERROR_TARGET, .target = ipt_error, .targetsize = XT_FUNCTION_MAXNAMELEN, .family = NFPROTO_IPV4, }, }; static struct nf_sockopt_ops ipt_sockopts = { .pf = PF_INET, .set_optmin = IPT_BASE_CTL, .set_optmax = IPT_SO_SET_MAX+1, .set = do_ipt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_ipt_set_ctl, #endif .get_optmin = IPT_BASE_CTL, .get_optmax = IPT_SO_GET_MAX+1, .get = do_ipt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_ipt_get_ctl, #endif .owner = THIS_MODULE, }; static struct xt_match ipt_builtin_mt[] __read_mostly = { { .name = "icmp", .match = icmp_match, .matchsize = sizeof(struct ipt_icmp), .checkentry = icmp_checkentry, .proto = IPPROTO_ICMP, .family = NFPROTO_IPV4, }, }; static int __net_init ip_tables_net_init(struct net *net) { return xt_proto_init(net, NFPROTO_IPV4); } static void __net_exit ip_tables_net_exit(struct net *net) { xt_proto_fini(net, NFPROTO_IPV4); } static struct pernet_operations ip_tables_net_ops = { .init = ip_tables_net_init, .exit = ip_tables_net_exit, }; static int __init ip_tables_init(void) { int ret; ret = register_pernet_subsys(&ip_tables_net_ops); if (ret < 0) goto err1; /* No one else will be downing sem now, so we won't sleep */ ret = xt_register_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg)); if (ret < 0) goto err2; ret = xt_register_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt)); if (ret < 0) goto err4; /* Register setsockopt */ ret = nf_register_sockopt(&ipt_sockopts); if (ret < 0) goto err5; pr_info("(C) 2000-2006 Netfilter Core Team\n"); return 0; err5: xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt)); err4: xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg)); err2: unregister_pernet_subsys(&ip_tables_net_ops); err1: return ret; } static void __exit ip_tables_fini(void) { nf_unregister_sockopt(&ipt_sockopts); xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt)); xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg)); unregister_pernet_subsys(&ip_tables_net_ops); } EXPORT_SYMBOL(ipt_register_table); EXPORT_SYMBOL(ipt_unregister_table); EXPORT_SYMBOL(ipt_do_table); module_init(ip_tables_init); module_exit(ip_tables_fini);
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5079_1
crossvul-cpp_data_good_4946_4
#include "cache.h" #include "commit.h" #include "tag.h" #include "diff.h" #include "revision.h" #include "list-objects.h" #include "progress.h" #include "pack-revindex.h" #include "pack.h" #include "pack-bitmap.h" #include "sha1-lookup.h" #include "pack-objects.h" struct bitmapped_commit { struct commit *commit; struct ewah_bitmap *bitmap; struct ewah_bitmap *write_as; int flags; int xor_offset; uint32_t commit_pos; }; struct bitmap_writer { struct ewah_bitmap *commits; struct ewah_bitmap *trees; struct ewah_bitmap *blobs; struct ewah_bitmap *tags; khash_sha1 *bitmaps; khash_sha1 *reused; struct packing_data *to_pack; struct bitmapped_commit *selected; unsigned int selected_nr, selected_alloc; struct progress *progress; int show_progress; unsigned char pack_checksum[20]; }; static struct bitmap_writer writer; void bitmap_writer_show_progress(int show) { writer.show_progress = show; } /** * Build the initial type index for the packfile */ void bitmap_writer_build_type_index(struct pack_idx_entry **index, uint32_t index_nr) { uint32_t i; writer.commits = ewah_new(); writer.trees = ewah_new(); writer.blobs = ewah_new(); writer.tags = ewah_new(); for (i = 0; i < index_nr; ++i) { struct object_entry *entry = (struct object_entry *)index[i]; enum object_type real_type; entry->in_pack_pos = i; switch (entry->type) { case OBJ_COMMIT: case OBJ_TREE: case OBJ_BLOB: case OBJ_TAG: real_type = entry->type; break; default: real_type = sha1_object_info(entry->idx.sha1, NULL); break; } switch (real_type) { case OBJ_COMMIT: ewah_set(writer.commits, i); break; case OBJ_TREE: ewah_set(writer.trees, i); break; case OBJ_BLOB: ewah_set(writer.blobs, i); break; case OBJ_TAG: ewah_set(writer.tags, i); break; default: die("Missing type information for %s (%d/%d)", sha1_to_hex(entry->idx.sha1), real_type, entry->type); } } } /** * Compute the actual bitmaps */ static struct object **seen_objects; static unsigned int seen_objects_nr, seen_objects_alloc; static inline void push_bitmapped_commit(struct commit *commit, struct ewah_bitmap *reused) { if (writer.selected_nr >= writer.selected_alloc) { writer.selected_alloc = (writer.selected_alloc + 32) * 2; REALLOC_ARRAY(writer.selected, writer.selected_alloc); } writer.selected[writer.selected_nr].commit = commit; writer.selected[writer.selected_nr].bitmap = reused; writer.selected[writer.selected_nr].flags = 0; writer.selected_nr++; } static inline void mark_as_seen(struct object *object) { ALLOC_GROW(seen_objects, seen_objects_nr + 1, seen_objects_alloc); seen_objects[seen_objects_nr++] = object; } static inline void reset_all_seen(void) { unsigned int i; for (i = 0; i < seen_objects_nr; ++i) { seen_objects[i]->flags &= ~(SEEN | ADDED | SHOWN); } seen_objects_nr = 0; } static uint32_t find_object_pos(const unsigned char *sha1) { struct object_entry *entry = packlist_find(writer.to_pack, sha1, NULL); if (!entry) { die("Failed to write bitmap index. Packfile doesn't have full closure " "(object %s is missing)", sha1_to_hex(sha1)); } return entry->in_pack_pos; } static void show_object(struct object *object, const char *name, void *data) { struct bitmap *base = data; bitmap_set(base, find_object_pos(object->oid.hash)); mark_as_seen(object); } static void show_commit(struct commit *commit, void *data) { mark_as_seen((struct object *)commit); } static int add_to_include_set(struct bitmap *base, struct commit *commit) { khiter_t hash_pos; uint32_t bitmap_pos = find_object_pos(commit->object.oid.hash); if (bitmap_get(base, bitmap_pos)) return 0; hash_pos = kh_get_sha1(writer.bitmaps, commit->object.oid.hash); if (hash_pos < kh_end(writer.bitmaps)) { struct bitmapped_commit *bc = kh_value(writer.bitmaps, hash_pos); bitmap_or_ewah(base, bc->bitmap); return 0; } bitmap_set(base, bitmap_pos); return 1; } static int should_include(struct commit *commit, void *_data) { struct bitmap *base = _data; if (!add_to_include_set(base, commit)) { struct commit_list *parent = commit->parents; mark_as_seen((struct object *)commit); while (parent) { parent->item->object.flags |= SEEN; mark_as_seen((struct object *)parent->item); parent = parent->next; } return 0; } return 1; } static void compute_xor_offsets(void) { static const int MAX_XOR_OFFSET_SEARCH = 10; int i, next = 0; while (next < writer.selected_nr) { struct bitmapped_commit *stored = &writer.selected[next]; int best_offset = 0; struct ewah_bitmap *best_bitmap = stored->bitmap; struct ewah_bitmap *test_xor; for (i = 1; i <= MAX_XOR_OFFSET_SEARCH; ++i) { int curr = next - i; if (curr < 0) break; test_xor = ewah_pool_new(); ewah_xor(writer.selected[curr].bitmap, stored->bitmap, test_xor); if (test_xor->buffer_size < best_bitmap->buffer_size) { if (best_bitmap != stored->bitmap) ewah_pool_free(best_bitmap); best_bitmap = test_xor; best_offset = i; } else { ewah_pool_free(test_xor); } } stored->xor_offset = best_offset; stored->write_as = best_bitmap; next++; } } void bitmap_writer_build(struct packing_data *to_pack) { static const double REUSE_BITMAP_THRESHOLD = 0.2; int i, reuse_after, need_reset; struct bitmap *base = bitmap_new(); struct rev_info revs; writer.bitmaps = kh_init_sha1(); writer.to_pack = to_pack; if (writer.show_progress) writer.progress = start_progress("Building bitmaps", writer.selected_nr); init_revisions(&revs, NULL); revs.tag_objects = 1; revs.tree_objects = 1; revs.blob_objects = 1; revs.no_walk = 0; revs.include_check = should_include; reset_revision_walk(); reuse_after = writer.selected_nr * REUSE_BITMAP_THRESHOLD; need_reset = 0; for (i = writer.selected_nr - 1; i >= 0; --i) { struct bitmapped_commit *stored; struct object *object; khiter_t hash_pos; int hash_ret; stored = &writer.selected[i]; object = (struct object *)stored->commit; if (stored->bitmap == NULL) { if (i < writer.selected_nr - 1 && (need_reset || !in_merge_bases(writer.selected[i + 1].commit, stored->commit))) { bitmap_reset(base); reset_all_seen(); } add_pending_object(&revs, object, ""); revs.include_check_data = base; if (prepare_revision_walk(&revs)) die("revision walk setup failed"); traverse_commit_list(&revs, show_commit, show_object, base); revs.pending.nr = 0; revs.pending.alloc = 0; revs.pending.objects = NULL; stored->bitmap = bitmap_to_ewah(base); need_reset = 0; } else need_reset = 1; if (i >= reuse_after) stored->flags |= BITMAP_FLAG_REUSE; hash_pos = kh_put_sha1(writer.bitmaps, object->oid.hash, &hash_ret); if (hash_ret == 0) die("Duplicate entry when writing index: %s", oid_to_hex(&object->oid)); kh_value(writer.bitmaps, hash_pos) = stored; display_progress(writer.progress, writer.selected_nr - i); } bitmap_free(base); stop_progress(&writer.progress); compute_xor_offsets(); } /** * Select the commits that will be bitmapped */ static inline unsigned int next_commit_index(unsigned int idx) { static const unsigned int MIN_COMMITS = 100; static const unsigned int MAX_COMMITS = 5000; static const unsigned int MUST_REGION = 100; static const unsigned int MIN_REGION = 20000; unsigned int offset, next; if (idx <= MUST_REGION) return 0; if (idx <= MIN_REGION) { offset = idx - MUST_REGION; return (offset < MIN_COMMITS) ? offset : MIN_COMMITS; } offset = idx - MIN_REGION; next = (offset < MAX_COMMITS) ? offset : MAX_COMMITS; return (next > MIN_COMMITS) ? next : MIN_COMMITS; } static int date_compare(const void *_a, const void *_b) { struct commit *a = *(struct commit **)_a; struct commit *b = *(struct commit **)_b; return (long)b->date - (long)a->date; } void bitmap_writer_reuse_bitmaps(struct packing_data *to_pack) { if (prepare_bitmap_git() < 0) return; writer.reused = kh_init_sha1(); rebuild_existing_bitmaps(to_pack, writer.reused, writer.show_progress); } static struct ewah_bitmap *find_reused_bitmap(const unsigned char *sha1) { khiter_t hash_pos; if (!writer.reused) return NULL; hash_pos = kh_get_sha1(writer.reused, sha1); if (hash_pos >= kh_end(writer.reused)) return NULL; return kh_value(writer.reused, hash_pos); } void bitmap_writer_select_commits(struct commit **indexed_commits, unsigned int indexed_commits_nr, int max_bitmaps) { unsigned int i = 0, j, next; qsort(indexed_commits, indexed_commits_nr, sizeof(indexed_commits[0]), date_compare); if (writer.show_progress) writer.progress = start_progress("Selecting bitmap commits", 0); if (indexed_commits_nr < 100) { for (i = 0; i < indexed_commits_nr; ++i) push_bitmapped_commit(indexed_commits[i], NULL); return; } for (;;) { struct ewah_bitmap *reused_bitmap = NULL; struct commit *chosen = NULL; next = next_commit_index(i); if (i + next >= indexed_commits_nr) break; if (max_bitmaps > 0 && writer.selected_nr >= max_bitmaps) { writer.selected_nr = max_bitmaps; break; } if (next == 0) { chosen = indexed_commits[i]; reused_bitmap = find_reused_bitmap(chosen->object.oid.hash); } else { chosen = indexed_commits[i + next]; for (j = 0; j <= next; ++j) { struct commit *cm = indexed_commits[i + j]; reused_bitmap = find_reused_bitmap(cm->object.oid.hash); if (reused_bitmap || (cm->object.flags & NEEDS_BITMAP) != 0) { chosen = cm; break; } if (cm->parents && cm->parents->next) chosen = cm; } } push_bitmapped_commit(chosen, reused_bitmap); i += next + 1; display_progress(writer.progress, i); } stop_progress(&writer.progress); } static int sha1write_ewah_helper(void *f, const void *buf, size_t len) { /* sha1write will die on error */ sha1write(f, buf, len); return len; } /** * Write the bitmap index to disk */ static inline void dump_bitmap(struct sha1file *f, struct ewah_bitmap *bitmap) { if (ewah_serialize_to(bitmap, sha1write_ewah_helper, f) < 0) die("Failed to write bitmap index"); } static const unsigned char *sha1_access(size_t pos, void *table) { struct pack_idx_entry **index = table; return index[pos]->sha1; } static void write_selected_commits_v1(struct sha1file *f, struct pack_idx_entry **index, uint32_t index_nr) { int i; for (i = 0; i < writer.selected_nr; ++i) { struct bitmapped_commit *stored = &writer.selected[i]; int commit_pos = sha1_pos(stored->commit->object.oid.hash, index, index_nr, sha1_access); if (commit_pos < 0) die("BUG: trying to write commit not in index"); sha1write_be32(f, commit_pos); sha1write_u8(f, stored->xor_offset); sha1write_u8(f, stored->flags); dump_bitmap(f, stored->write_as); } } static void write_hash_cache(struct sha1file *f, struct pack_idx_entry **index, uint32_t index_nr) { uint32_t i; for (i = 0; i < index_nr; ++i) { struct object_entry *entry = (struct object_entry *)index[i]; uint32_t hash_value = htonl(entry->hash); sha1write(f, &hash_value, sizeof(hash_value)); } } void bitmap_writer_set_checksum(unsigned char *sha1) { hashcpy(writer.pack_checksum, sha1); } void bitmap_writer_finish(struct pack_idx_entry **index, uint32_t index_nr, const char *filename, uint16_t options) { static char tmp_file[PATH_MAX]; static uint16_t default_version = 1; static uint16_t flags = BITMAP_OPT_FULL_DAG; struct sha1file *f; struct bitmap_disk_header header; int fd = odb_mkstemp(tmp_file, sizeof(tmp_file), "pack/tmp_bitmap_XXXXXX"); if (fd < 0) die_errno("unable to create '%s'", tmp_file); f = sha1fd(fd, tmp_file); memcpy(header.magic, BITMAP_IDX_SIGNATURE, sizeof(BITMAP_IDX_SIGNATURE)); header.version = htons(default_version); header.options = htons(flags | options); header.entry_count = htonl(writer.selected_nr); hashcpy(header.checksum, writer.pack_checksum); sha1write(f, &header, sizeof(header)); dump_bitmap(f, writer.commits); dump_bitmap(f, writer.trees); dump_bitmap(f, writer.blobs); dump_bitmap(f, writer.tags); write_selected_commits_v1(f, index, index_nr); if (options & BITMAP_OPT_HASH_CACHE) write_hash_cache(f, index, index_nr); sha1close(f, NULL, CSUM_FSYNC); if (adjust_shared_perm(tmp_file)) die_errno("unable to make temporary bitmap file readable"); if (rename(tmp_file, filename)) die_errno("unable to rename temporary bitmap file to '%s'", filename); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_4946_4
crossvul-cpp_data_good_614_0
#include <uwsgi.h> extern struct uwsgi_server uwsgi; #ifdef __BIG_ENDIAN__ uint16_t uwsgi_swap16(uint16_t x) { return (uint16_t) ((x & 0xff) << 8 | (x & 0xff00) >> 8); } uint32_t uwsgi_swap32(uint32_t x) { x = ((x << 8) & 0xFF00FF00) | ((x >> 8) & 0x00FF00FF); return (x >> 16) | (x << 16); } // thanks to ffmpeg project for this idea :P uint64_t uwsgi_swap64(uint64_t x) { union { uint64_t ll; uint32_t l[2]; } w, r; w.ll = x; r.l[0] = uwsgi_swap32(w.l[1]); r.l[1] = uwsgi_swap32(w.l[0]); return r.ll; } #endif // check if a string is a valid hex number int check_hex(char *str, int len) { int i; for (i = 0; i < len; i++) { if ((str[i] < '0' && str[i] > '9') && (str[i] < 'a' && str[i] > 'f') && (str[i] < 'A' && str[i] > 'F') ) { return 0; } } return 1; } // increase worker harakiri void inc_harakiri(struct wsgi_request *wsgi_req, int sec) { if (uwsgi.master_process) { uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].harakiri += sec; } else { alarm(uwsgi.harakiri_options.workers + sec); } } // set worker harakiri void set_harakiri(struct wsgi_request *wsgi_req, int sec) { if (!wsgi_req) return; if (sec == 0) { uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].harakiri = 0; } else { uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].harakiri = uwsgi_now() + sec; } if (!uwsgi.master_process) { alarm(sec); } } // set user harakiri void set_user_harakiri(struct wsgi_request *wsgi_req, int sec) { if (!uwsgi.master_process) { uwsgi_log("!!! unable to set user harakiri without the master process !!!\n"); return; } // a 0 seconds value, reset the timer time_t timeout = sec == 0 ? 0 : uwsgi_now() + sec; if (uwsgi.muleid > 0) { uwsgi.mules[uwsgi.muleid - 1].user_harakiri = timeout; } else if (uwsgi.i_am_a_spooler) { struct uwsgi_spooler *uspool = uwsgi.i_am_a_spooler; uspool->user_harakiri = timeout; } else if (wsgi_req) { uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].user_harakiri = timeout; } } // set mule harakiri void set_mule_harakiri(int sec) { if (sec == 0) { uwsgi.mules[uwsgi.muleid - 1].harakiri = 0; } else { uwsgi.mules[uwsgi.muleid - 1].harakiri = uwsgi_now() + sec; } if (!uwsgi.master_process) { alarm(sec); } } // set spooler harakiri void set_spooler_harakiri(int sec) { if (sec == 0) { uwsgi.i_am_a_spooler->harakiri = 0; } else { uwsgi.i_am_a_spooler->harakiri = uwsgi_now() + sec; } if (!uwsgi.master_process) { alarm(sec); } } // daemonize to the specified logfile void daemonize(char *logfile) { pid_t pid; // do not daemonize under emperor if (uwsgi.has_emperor) { logto(logfile); return; } pid = fork(); if (pid < 0) { uwsgi_error("fork()"); exit(1); } if (pid != 0) { _exit(0); } if (setsid() < 0) { uwsgi_error("setsid()"); exit(1); } /* refork... */ pid = fork(); if (pid < 0) { uwsgi_error("fork()"); exit(1); } if (pid != 0) { _exit(0); } if (!uwsgi.do_not_change_umask) { umask(0); } /*if (chdir("/") != 0) { uwsgi_error("chdir()"); exit(1); } */ uwsgi_remap_fd(0, "/dev/null"); logto(logfile); } // get current working directory char *uwsgi_get_cwd() { #if defined(__GLIBC__) return getcwd(NULL, 0); #else // set this to static to avoid useless reallocations in stats mode static size_t newsize = 256; char *cwd = uwsgi_malloc(newsize); if (getcwd(cwd, newsize) == NULL && errno == ERANGE) { newsize += 256; uwsgi_log("need a bigger buffer (%lu bytes) for getcwd(). doing reallocation.\n", (unsigned long) newsize); free(cwd); cwd = uwsgi_malloc(newsize); if (getcwd(cwd, newsize) == NULL) { uwsgi_error("getcwd()"); exit(1); } } return cwd; #endif } #ifdef __linux__ void uwsgi_set_cgroup() { char *cgroup_taskfile; FILE *cgroup; char *cgroup_opt; struct uwsgi_string_list *usl, *uslo; if (!uwsgi.cgroup) return; if (getuid()) return; usl = uwsgi.cgroup; while (usl) { int mode = strtol(uwsgi.cgroup_dir_mode, 0, 8); if (mkdir(usl->value, mode)) { if (errno != EEXIST) { uwsgi_error("uwsgi_set_cgroup()/mkdir()"); exit(1); } if (chmod(usl->value, mode)) { uwsgi_error("uwsgi_set_cgroup()/chmod()"); exit(1); } uwsgi_log("using Linux cgroup %s with mode %o\n", usl->value, mode); } else { uwsgi_log("created Linux cgroup %s with mode %o\n", usl->value, mode); } cgroup_taskfile = uwsgi_concat2(usl->value, "/tasks"); cgroup = fopen(cgroup_taskfile, "w"); if (!cgroup) { uwsgi_error_open(cgroup_taskfile); exit(1); } if (fprintf(cgroup, "%d\n", (int) getpid()) <= 0 || ferror(cgroup) || fclose(cgroup)) { uwsgi_error("could not set cgroup"); exit(1); } uwsgi_log("assigned process %d to cgroup %s\n", (int) getpid(), cgroup_taskfile); free(cgroup_taskfile); uslo = uwsgi.cgroup_opt; while (uslo) { cgroup_opt = strchr(uslo->value, '='); if (!cgroup_opt) { cgroup_opt = strchr(uslo->value, ':'); if (!cgroup_opt) { uwsgi_log("invalid cgroup-opt syntax\n"); exit(1); } } cgroup_opt[0] = 0; cgroup_opt++; cgroup_taskfile = uwsgi_concat3(usl->value, "/", uslo->value); cgroup = fopen(cgroup_taskfile, "w"); if (cgroup) { if (fprintf(cgroup, "%s\n", cgroup_opt) <= 0 || ferror(cgroup) || fclose(cgroup)) { uwsgi_log("could not set cgroup option %s to %s\n", uslo->value, cgroup_opt); exit(1); } uwsgi_log("set %s to %s\n", cgroup_opt, cgroup_taskfile); } free(cgroup_taskfile); cgroup_opt[-1] = '='; uslo = uslo->next; } usl = usl->next; } } #endif #ifdef UWSGI_CAP void uwsgi_apply_cap(cap_value_t * cap, int caps_count) { cap_value_t minimal_cap_values[] = { CAP_SYS_CHROOT, CAP_SETUID, CAP_SETGID, CAP_SETPCAP }; cap_t caps = cap_init(); if (!caps) { uwsgi_error("cap_init()"); exit(1); } cap_clear(caps); cap_set_flag(caps, CAP_EFFECTIVE, 4, minimal_cap_values, CAP_SET); cap_set_flag(caps, CAP_PERMITTED, 4, minimal_cap_values, CAP_SET); cap_set_flag(caps, CAP_PERMITTED, caps_count, cap, CAP_SET); cap_set_flag(caps, CAP_INHERITABLE, caps_count, cap, CAP_SET); if (cap_set_proc(caps) < 0) { uwsgi_error("cap_set_proc()"); exit(1); } cap_free(caps); #ifdef __linux__ #ifdef SECBIT_KEEP_CAPS if (prctl(SECBIT_KEEP_CAPS, 1, 0, 0, 0) < 0) { uwsgi_error("prctl()"); exit(1); } #else if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0) { uwsgi_error("prctl()"); exit(1); } #endif #endif } #endif // drop privileges (as root) /* here we manage jails/namespaces too it is a pretty huge function... refactory is needed */ void uwsgi_as_root() { if (getuid() > 0) goto nonroot; #ifndef __RUMP__ if (!uwsgi.master_as_root && !uwsgi.uidname) { uwsgi_log_initial("uWSGI running as root, you can use --uid/--gid/--chroot options\n"); } #endif int in_jail = 0; #if defined(__linux__) && !defined(OBSOLETE_LINUX_KERNEL) if (uwsgi.unshare && !uwsgi.reloads) { if (unshare(uwsgi.unshare)) { uwsgi_error("unshare()"); exit(1); } else { uwsgi_log("[linux-namespace] applied unshare() mask: %d\n", uwsgi.unshare); } #ifdef CLONE_NEWUSER if (uwsgi.unshare & CLONE_NEWUSER) { if (setuid(0)) { uwsgi_error("uwsgi_as_root()/setuid(0)"); exit(1); } } #endif in_jail = 1; } #endif #ifdef UWSGI_CAP if (uwsgi.cap && uwsgi.cap_count > 0 && !uwsgi.reloads) { uwsgi_apply_cap(uwsgi.cap, uwsgi.cap_count); } #endif #if defined(__FreeBSD__) || defined(__GNU_kFreeBSD__) if (uwsgi.jail && !uwsgi.reloads) { struct jail ujail; char *jarg = uwsgi_str(uwsgi.jail); char *j_hostname = NULL; char *j_name = NULL; char *space = strchr(jarg, ' '); if (space) { *space = 0; j_hostname = space + 1; space = strchr(j_hostname, ' '); if (space) { *space = 0; j_name = space + 1; } } ujail.version = JAIL_API_VERSION; ujail.path = jarg; ujail.hostname = j_hostname ? j_hostname : ""; ujail.jailname = j_name; ujail.ip4s = 0; ujail.ip6s = 0; struct uwsgi_string_list *usl = NULL; uwsgi_foreach(usl, uwsgi.jail_ip4) { ujail.ip4s++; } struct in_addr *saddr = uwsgi_calloc(sizeof(struct in_addr) * ujail.ip4s); int i = 0; uwsgi_foreach(usl, uwsgi.jail_ip4) { if (!inet_pton(AF_INET, usl->value, &saddr[i].s_addr)) { uwsgi_error("jail()/inet_pton()"); exit(1); } i++; } ujail.ip4 = saddr; #ifdef AF_INET6 uwsgi_foreach(usl, uwsgi.jail_ip6) { ujail.ip6s++; } struct in6_addr *saddr6 = uwsgi_calloc(sizeof(struct in6_addr) * ujail.ip6s); i = 0; uwsgi_foreach(usl, uwsgi.jail_ip6) { if (!inet_pton(AF_INET6, usl->value, &saddr6[i].s6_addr)) { uwsgi_error("jail()/inet_pton()"); exit(1); } i++; } ujail.ip6 = saddr6; #endif int jail_id = jail(&ujail); if (jail_id < 0) { uwsgi_error("jail()"); exit(1); } if (uwsgi.jidfile) { if (uwsgi_write_intfile(uwsgi.jidfile, jail_id)) { uwsgi_log("unable to write jidfile\n"); exit(1); } } uwsgi_log("--- running in FreeBSD jail %d ---\n", jail_id); in_jail = 1; } #ifdef UWSGI_HAS_FREEBSD_LIBJAIL if (uwsgi.jail_attach && !uwsgi.reloads) { struct jailparam jparam; uwsgi_log("attaching to FreeBSD jail %s ...\n", uwsgi.jail_attach); if (!is_a_number(uwsgi.jail_attach)) { if (jailparam_init(&jparam, "name")) { uwsgi_error("jailparam_init()"); exit(1); } } else { if (jailparam_init(&jparam, "jid")) { uwsgi_error("jailparam_init()"); exit(1); } } jailparam_import(&jparam, uwsgi.jail_attach); int jail_id = jailparam_set(&jparam, 1, JAIL_UPDATE | JAIL_ATTACH); if (jail_id < 0) { uwsgi_error("jailparam_set()"); exit(1); } jailparam_free(&jparam, 1); uwsgi_log("--- running in FreeBSD jail %d ---\n", jail_id); in_jail = 1; } if (uwsgi.jail2 && !uwsgi.reloads) { struct uwsgi_string_list *usl = NULL; unsigned nparams = 0; uwsgi_foreach(usl, uwsgi.jail2) { nparams++; } struct jailparam *params = uwsgi_malloc(sizeof(struct jailparam) * nparams); int i = 0; uwsgi_foreach(usl, uwsgi.jail2) { uwsgi_log("FreeBSD libjail applying %s\n", usl->value); char *equal = strchr(usl->value, '='); if (equal) { *equal = 0; } if (jailparam_init(&params[i], usl->value)) { uwsgi_error("jailparam_init()"); exit(1); } if (equal) { jailparam_import(&params[i], equal + 1); *equal = '='; } else { jailparam_import(&params[i], "1"); } i++; } int jail_id = jailparam_set(params, nparams, JAIL_CREATE | JAIL_ATTACH); if (jail_id < 0) { uwsgi_error("jailparam_set()"); exit(1); } jailparam_free(params, nparams); if (uwsgi.jidfile) { if (uwsgi_write_intfile(uwsgi.jidfile, jail_id)) { uwsgi_log("unable to write jidfile\n"); exit(1); } } uwsgi_log("--- running in FreeBSD jail %d ---\n", jail_id); in_jail = 1; } #endif #endif if (in_jail || uwsgi.jailed) { uwsgi_hooks_run(uwsgi.hook_post_jail, "post-jail", 1); struct uwsgi_string_list *usl = NULL; uwsgi_foreach(usl, uwsgi.mount_post_jail) { uwsgi_log("mounting \"%s\" (post-jail)...\n", usl->value); if (uwsgi_mount_hook(usl->value)) { exit(1); } } uwsgi_foreach(usl, uwsgi.umount_post_jail) { uwsgi_log("un-mounting \"%s\" (post-jail)...\n", usl->value); if (uwsgi_umount_hook(usl->value)) { exit(1); } } uwsgi_foreach(usl, uwsgi.exec_post_jail) { uwsgi_log("running \"%s\" (post-jail)...\n", usl->value); int ret = uwsgi_run_command_and_wait(NULL, usl->value); if (ret != 0) { uwsgi_log("command \"%s\" exited with non-zero code: %d\n", usl->value, ret); exit(1); } } uwsgi_foreach(usl, uwsgi.call_post_jail) { if (uwsgi_call_symbol(usl->value)) { uwsgi_log("unable to call function \"%s\"\n", usl->value); exit(1); } } if (uwsgi.refork_post_jail) { uwsgi_log("re-fork()ing...\n"); pid_t pid = fork(); if (pid < 0) { uwsgi_error("fork()"); exit(1); } if (pid > 0) { // block all signals sigset_t smask; sigfillset(&smask); sigprocmask(SIG_BLOCK, &smask, NULL); int status; if (waitpid(pid, &status, 0) < 0) { uwsgi_error("waitpid()"); } _exit(0); } } int i; for (i = 0; i < uwsgi.gp_cnt; i++) { if (uwsgi.gp[i]->post_jail) { uwsgi.gp[i]->post_jail(); } } } if (uwsgi.chroot && !uwsgi.reloads) { if (!uwsgi.master_as_root) uwsgi_log("chroot() to %s\n", uwsgi.chroot); if (chroot(uwsgi.chroot)) { uwsgi_error("chroot()"); exit(1); } #ifdef __linux__ if (uwsgi.logging_options.memory_report) { uwsgi_log("*** Warning, on linux system you have to bind-mount the /proc fs in your chroot to get memory debug/report.\n"); } #endif } #ifdef __linux__ if (uwsgi.pivot_root && !uwsgi.reloads) { char *arg = uwsgi_str(uwsgi.pivot_root); char *space = strchr(arg, ' '); if (!space) { uwsgi_log("invalid pivot_root syntax, new_root and put_old must be separated by a space\n"); exit(1); } *space = 0; #if defined(MS_REC) && defined(MS_PRIVATE) if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL)) { uwsgi_error("mount()"); exit(1); } #endif if (chdir(arg)) { uwsgi_error("pivot_root()/chdir()"); exit(1); } space += 1 + strlen(arg); if (space[0] == '/') space++; if (pivot_root(".", space)) { uwsgi_error("pivot_root()"); exit(1); } if (uwsgi.logging_options.memory_report) { uwsgi_log("*** Warning, on linux system you have to bind-mount the /proc fs in your chroot to get memory debug/report.\n"); } free(arg); if (chdir("/")) { uwsgi_error("chdir()"); exit(1); } } #endif #if defined(__linux__) && !defined(OBSOLETE_LINUX_KERNEL) if (uwsgi.unshare2 && !uwsgi.reloads) { if (unshare(uwsgi.unshare2)) { uwsgi_error("unshare()"); exit(1); } else { uwsgi_log("[linux-namespace] applied unshare() mask: %d\n", uwsgi.unshare2); } #ifdef CLONE_NEWUSER if (uwsgi.unshare2 & CLONE_NEWUSER) { if (setuid(0)) { uwsgi_error("uwsgi_as_root()/setuid(0)"); exit(1); } } #endif in_jail = 1; } #endif if (uwsgi.refork_as_root) { uwsgi_log("re-fork()ing...\n"); pid_t pid = fork(); if (pid < 0) { uwsgi_error("fork()"); exit(1); } if (pid > 0) { // block all signals sigset_t smask; sigfillset(&smask); sigprocmask(SIG_BLOCK, &smask, NULL); int status; if (waitpid(pid, &status, 0) < 0) { uwsgi_error("waitpid()"); } _exit(0); } } struct uwsgi_string_list *usl; uwsgi_foreach(usl, uwsgi.wait_for_interface) { if (!uwsgi.wait_for_interface_timeout) { uwsgi.wait_for_interface_timeout = 60; } uwsgi_log("waiting for interface %s (max %d seconds) ...\n", usl->value, uwsgi.wait_for_interface_timeout); int counter = 0; for (;;) { if (counter > uwsgi.wait_for_interface_timeout) { uwsgi_log("interface %s unavailable after %d seconds\n", usl->value, counter); exit(1); } unsigned int index = if_nametoindex(usl->value); if (index > 0) { uwsgi_log("interface %s found with index %u\n", usl->value, index); break; } else { sleep(1); counter++; } } } uwsgi_foreach(usl, uwsgi.wait_for_fs) { if (uwsgi_wait_for_fs(usl->value, 0)) exit(1); } uwsgi_foreach(usl, uwsgi.wait_for_file) { if (uwsgi_wait_for_fs(usl->value, 1)) exit(1); } uwsgi_foreach(usl, uwsgi.wait_for_dir) { if (uwsgi_wait_for_fs(usl->value, 2)) exit(1); } uwsgi_foreach(usl, uwsgi.wait_for_mountpoint) { if (uwsgi_wait_for_mountpoint(usl->value)) exit(1); } uwsgi_hooks_run(uwsgi.hook_as_root, "as root", 1); uwsgi_foreach(usl, uwsgi.mount_as_root) { uwsgi_log("mounting \"%s\" (as root)...\n", usl->value); if (uwsgi_mount_hook(usl->value)) { exit(1); } } uwsgi_foreach(usl, uwsgi.umount_as_root) { uwsgi_log("un-mounting \"%s\" (as root)...\n", usl->value); if (uwsgi_umount_hook(usl->value)) { exit(1); } } // now run the scripts needed by root uwsgi_foreach(usl, uwsgi.exec_as_root) { uwsgi_log("running \"%s\" (as root)...\n", usl->value); int ret = uwsgi_run_command_and_wait(NULL, usl->value); if (ret != 0) { uwsgi_log("command \"%s\" exited with non-zero code: %d\n", usl->value, ret); exit(1); } } uwsgi_foreach(usl, uwsgi.call_as_root) { if (uwsgi_call_symbol(usl->value)) { uwsgi_log("unable to call function \"%s\"\n", usl->value); } } if (uwsgi.gidname) { struct group *ugroup = getgrnam(uwsgi.gidname); if (ugroup) { uwsgi.gid = ugroup->gr_gid; } else { uwsgi_log("group %s not found.\n", uwsgi.gidname); exit(1); } } if (uwsgi.uidname) { struct passwd *upasswd = getpwnam(uwsgi.uidname); if (upasswd) { uwsgi.uid = upasswd->pw_uid; } else { uwsgi_log("user %s not found.\n", uwsgi.uidname); exit(1); } } if (uwsgi.logfile_chown) { int log_fd = 2; if (uwsgi.log_master && uwsgi.original_log_fd > -1) { log_fd = uwsgi.original_log_fd; } if (fchown(log_fd, uwsgi.uid, uwsgi.gid)) { uwsgi_error("fchown()"); exit(1); } } // fix ipcsem owner if (uwsgi.lock_ops.lock_init == uwsgi_lock_ipcsem_init) { struct uwsgi_lock_item *uli = uwsgi.registered_locks; while (uli) { union semun { int val; struct semid_ds *buf; ushort *array; } semu; struct semid_ds sds; memset(&sds, 0, sizeof(sds)); semu.buf = &sds; int semid = 0; memcpy(&semid, uli->lock_ptr, sizeof(int)); if (semctl(semid, 0, IPC_STAT, semu)) { uwsgi_error("semctl()"); exit(1); } semu.buf->sem_perm.uid = uwsgi.uid; semu.buf->sem_perm.gid = uwsgi.gid; if (semctl(semid, 0, IPC_SET, semu)) { uwsgi_error("semctl()"); exit(1); } uli = uli->next; } } // ok try to call some special hook before finally dropping privileges int i; for (i = 0; i < uwsgi.gp_cnt; i++) { if (uwsgi.gp[i]->before_privileges_drop) { uwsgi.gp[i]->before_privileges_drop(); } } if (uwsgi.gid) { if (!uwsgi.master_as_root) uwsgi_log("setgid() to %d\n", uwsgi.gid); if (setgid(uwsgi.gid)) { uwsgi_error("setgid()"); exit(1); } if (uwsgi.no_initgroups || !uwsgi.uid) { if (setgroups(0, NULL)) { uwsgi_error("setgroups()"); exit(1); } } else { char *uidname = uwsgi.uidname; if (!uidname) { struct passwd *pw = getpwuid(uwsgi.uid); if (pw) uidname = pw->pw_name; } if (!uidname) uidname = uwsgi_num2str(uwsgi.uid); if (initgroups(uidname, uwsgi.gid)) { uwsgi_error("setgroups()"); exit(1); } } struct uwsgi_string_list *usl; size_t ags = 0; uwsgi_foreach(usl, uwsgi.additional_gids) ags++; if (ags > 0) { gid_t *ags_list = uwsgi_calloc(sizeof(gid_t) * ags); size_t g_pos = 0; uwsgi_foreach(usl, uwsgi.additional_gids) { ags_list[g_pos] = atoi(usl->value); if (!ags_list[g_pos]) { struct group *g = getgrnam(usl->value); if (g) { ags_list[g_pos] = g->gr_gid; } else { uwsgi_log("unable to find group %s\n", usl->value); exit(1); } } g_pos++; } if (setgroups(ags, ags_list)) { uwsgi_error("setgroups()"); exit(1); } } int additional_groups = getgroups(0, NULL); if (additional_groups > 0) { gid_t *gids = uwsgi_calloc(sizeof(gid_t) * additional_groups); if (getgroups(additional_groups, gids) > 0) { int i; for (i = 0; i < additional_groups; i++) { if (gids[i] == uwsgi.gid) continue; struct group *gr = getgrgid(gids[i]); if (gr) { uwsgi_log("set additional group %d (%s)\n", gids[i], gr->gr_name); } else { uwsgi_log("set additional group %d\n", gids[i]); } } } free(gids); } } if (uwsgi.uid) { if (!uwsgi.master_as_root) uwsgi_log("setuid() to %d\n", uwsgi.uid); if (setuid(uwsgi.uid)) { uwsgi_error("setuid()"); exit(1); } } #ifndef __RUMP__ if (!getuid()) { uwsgi_log_initial("*** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** \n"); } #endif #ifdef UWSGI_CAP if (uwsgi.cap && uwsgi.cap_count > 0 && !uwsgi.reloads) { cap_t caps = cap_init(); if (!caps) { uwsgi_error("cap_init()"); exit(1); } cap_clear(caps); cap_set_flag(caps, CAP_EFFECTIVE, uwsgi.cap_count, uwsgi.cap, CAP_SET); cap_set_flag(caps, CAP_PERMITTED, uwsgi.cap_count, uwsgi.cap, CAP_SET); cap_set_flag(caps, CAP_INHERITABLE, uwsgi.cap_count, uwsgi.cap, CAP_SET); if (cap_set_proc(caps) < 0) { uwsgi_error("cap_set_proc()"); exit(1); } cap_free(caps); } #endif if (uwsgi.refork) { uwsgi_log("re-fork()ing...\n"); pid_t pid = fork(); if (pid < 0) { uwsgi_error("fork()"); exit(1); } if (pid > 0) { // block all signals sigset_t smask; sigfillset(&smask); sigprocmask(SIG_BLOCK, &smask, NULL); int status; if (waitpid(pid, &status, 0) < 0) { uwsgi_error("waitpid()"); } _exit(0); } } uwsgi_hooks_run(uwsgi.hook_as_user, "as user", 1); // now run the scripts needed by the user uwsgi_foreach(usl, uwsgi.exec_as_user) { uwsgi_log("running \"%s\" (as uid: %d gid: %d) ...\n", usl->value, (int) getuid(), (int) getgid()); int ret = uwsgi_run_command_and_wait(NULL, usl->value); if (ret != 0) { uwsgi_log("command \"%s\" exited with non-zero code: %d\n", usl->value, ret); exit(1); } } uwsgi_foreach(usl, uwsgi.call_as_user) { if (uwsgi_call_symbol(usl->value)) { uwsgi_log("unable to call function \"%s\"\n", usl->value); exit(1); } } // we could now patch the binary if (uwsgi.unprivileged_binary_patch) { uwsgi.argv[0] = uwsgi.unprivileged_binary_patch; execvp(uwsgi.unprivileged_binary_patch, uwsgi.argv); uwsgi_error("execvp()"); exit(1); } if (uwsgi.unprivileged_binary_patch_arg) { uwsgi_exec_command_with_args(uwsgi.unprivileged_binary_patch_arg); } return; nonroot: if (uwsgi.chroot && !uwsgi.is_a_reload) { uwsgi_log("cannot chroot() as non-root user\n"); exit(1); } if (uwsgi.gid && getgid() != uwsgi.gid) { uwsgi_log("cannot setgid() as non-root user\n"); exit(1); } if (uwsgi.uid && getuid() != uwsgi.uid) { uwsgi_log("cannot setuid() as non-root user\n"); exit(1); } } static void close_and_free_request(struct wsgi_request *wsgi_req) { // close the connection with the client if (!wsgi_req->fd_closed) { // NOTE, if we close the socket before receiving eventually sent data, socket layer will send a RST wsgi_req->socket->proto_close(wsgi_req); } if (wsgi_req->post_file) { fclose(wsgi_req->post_file); } if (wsgi_req->post_read_buf) { free(wsgi_req->post_read_buf); } if (wsgi_req->post_readline_buf) { free(wsgi_req->post_readline_buf); } if (wsgi_req->proto_parser_buf) { free(wsgi_req->proto_parser_buf); } } // destroy a request void uwsgi_destroy_request(struct wsgi_request *wsgi_req) { close_and_free_request(wsgi_req); int foo; if (uwsgi.threads > 1) { // now the thread can die... pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &foo); } // reset for avoiding following requests to fail on non-uwsgi protocols // thanks Marko Tiikkaja for catching it wsgi_req->uh->_pktsize = 0; // some plugins expected async_id to be defined before setup int tmp_id = wsgi_req->async_id; memset(wsgi_req, 0, sizeof(struct wsgi_request)); wsgi_req->async_id = tmp_id; } // finalize/close/free a request void uwsgi_close_request(struct wsgi_request *wsgi_req) { int waitpid_status; int tmp_id; uint64_t tmp_rt, rss = 0, vsz = 0; #ifdef __linux__ uint64_t uss = 0, pss = 0; #endif // apply transformations if (wsgi_req->transformations) { if (uwsgi_apply_final_transformations(wsgi_req) == 0) { if (wsgi_req->transformed_chunk && wsgi_req->transformed_chunk_len > 0) { uwsgi_response_write_body_do(wsgi_req, wsgi_req->transformed_chunk, wsgi_req->transformed_chunk_len); } } uwsgi_free_transformations(wsgi_req); } // check if headers should be sent if (wsgi_req->headers) { if (!wsgi_req->headers_sent && !wsgi_req->headers_size && !wsgi_req->response_size) { uwsgi_response_write_headers_do(wsgi_req); } uwsgi_buffer_destroy(wsgi_req->headers); } uint64_t end_of_request = uwsgi_micros(); wsgi_req->end_of_request = end_of_request; if (!wsgi_req->do_not_account_avg_rt) { tmp_rt = wsgi_req->end_of_request - wsgi_req->start_of_request; uwsgi.workers[uwsgi.mywid].running_time += tmp_rt; uwsgi.workers[uwsgi.mywid].avg_response_time = (uwsgi.workers[uwsgi.mywid].avg_response_time + tmp_rt) / 2; } // get memory usage if (uwsgi.logging_options.memory_report || uwsgi.force_get_memusage) { get_memusage(&rss, &vsz); uwsgi.workers[uwsgi.mywid].vsz_size = vsz; uwsgi.workers[uwsgi.mywid].rss_size = rss; } #ifdef __linux__ if (uwsgi.logging_options.memory_report || uwsgi.reload_on_uss || uwsgi.reload_on_pss) { get_memusage_extra(&uss, &pss); uwsgi.workers[uwsgi.mywid].uss_size = uss; uwsgi.workers[uwsgi.mywid].pss_size = pss; } #endif if (!wsgi_req->do_not_account) { uwsgi.workers[0].requests++; uwsgi.workers[uwsgi.mywid].requests++; uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].requests++; uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].write_errors += wsgi_req->write_errors; uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].read_errors += wsgi_req->read_errors; // this is used for MAX_REQUESTS uwsgi.workers[uwsgi.mywid].delta_requests++; } #ifdef UWSGI_ROUTING // apply final routes after accounting uwsgi_apply_final_routes(wsgi_req); #endif // close socket and free parsers-allocated memory close_and_free_request(wsgi_req); // after_request hook if (!wsgi_req->is_raw && uwsgi.p[wsgi_req->uh->modifier1]->after_request) uwsgi.p[wsgi_req->uh->modifier1]->after_request(wsgi_req); // after_request custom hooks struct uwsgi_string_list *usl = NULL; uwsgi_foreach(usl, uwsgi.after_request_hooks) { void (*func) (struct wsgi_request *) = (void (*)(struct wsgi_request *)) usl->custom_ptr; func(wsgi_req); } if (uwsgi.threads > 1) { // now the thread can die... pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &tmp_id); } // leave harakiri mode if (uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].harakiri > 0) { set_harakiri(wsgi_req, 0); } // leave user harakiri mode if (uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].user_harakiri > 0) { set_user_harakiri(wsgi_req, 0); } if (!wsgi_req->do_not_account) { // this is racy in multithread mode if (wsgi_req->response_size > 0) { uwsgi.workers[uwsgi.mywid].tx += wsgi_req->response_size; } if (wsgi_req->headers_size > 0) { uwsgi.workers[uwsgi.mywid].tx += wsgi_req->headers_size; } } // defunct process reaper if (uwsgi.reaper == 1) { while (waitpid(WAIT_ANY, &waitpid_status, WNOHANG) > 0); } // free logvars struct uwsgi_logvar *lv = wsgi_req->logvars; while (lv) { struct uwsgi_logvar *ptr = lv; lv = lv->next; free(ptr); } // free additional headers struct uwsgi_string_list *ah = wsgi_req->additional_headers; while (ah) { struct uwsgi_string_list *ptr = ah; ah = ah->next; free(ptr->value); free(ptr); } // free remove headers ah = wsgi_req->remove_headers; while (ah) { struct uwsgi_string_list *ptr = ah; ah = ah->next; free(ptr->value); free(ptr); } // free chunked input if (wsgi_req->chunked_input_buf) { uwsgi_buffer_destroy(wsgi_req->chunked_input_buf); } if (wsgi_req->body_chunked_buf) { uwsgi_buffer_destroy(wsgi_req->body_chunked_buf); } // free websocket engine if (wsgi_req->websocket_buf) { uwsgi_buffer_destroy(wsgi_req->websocket_buf); } if (wsgi_req->websocket_send_buf) { uwsgi_buffer_destroy(wsgi_req->websocket_send_buf); } // reset request wsgi_req->uh->_pktsize = 0; tmp_id = wsgi_req->async_id; memset(wsgi_req, 0, sizeof(struct wsgi_request)); // some plugins expected async_id to be defined before setup wsgi_req->async_id = tmp_id; // yes, this is pretty useless but we cannot ensure all of the plugin have the same behaviour uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].in_request = 0; if (uwsgi.max_requests > 0 && uwsgi.workers[uwsgi.mywid].delta_requests >= (uwsgi.max_requests + ((uwsgi.mywid-1) * uwsgi.max_requests_delta)) && (end_of_request - (uwsgi.workers[uwsgi.mywid].last_spawn * 1000000) >= uwsgi.min_worker_lifetime * 1000000)) { goodbye_cruel_world("max requests reached (%llu >= %llu)", (unsigned long long) uwsgi.workers[uwsgi.mywid].delta_requests, (unsigned long long) (uwsgi.max_requests + ((uwsgi.mywid-1) * uwsgi.max_requests_delta)) ); } if (uwsgi.reload_on_as && (rlim_t) vsz >= uwsgi.reload_on_as && (end_of_request - (uwsgi.workers[uwsgi.mywid].last_spawn * 1000000) >= uwsgi.min_worker_lifetime * 1000000)) { goodbye_cruel_world("reload-on-as limit reached (%llu >= %llu)", (unsigned long long) (rlim_t) vsz, (unsigned long long) uwsgi.reload_on_as ); } if (uwsgi.reload_on_rss && (rlim_t) rss >= uwsgi.reload_on_rss && (end_of_request - (uwsgi.workers[uwsgi.mywid].last_spawn * 1000000) >= uwsgi.min_worker_lifetime * 1000000)) { goodbye_cruel_world("reload-on-rss limit reached (%llu >= %llu)", (unsigned long long) (rlim_t) rss, (unsigned long long) uwsgi.reload_on_rss ); } #ifdef __linux__ if (uwsgi.reload_on_uss && (rlim_t) uss >= uwsgi.reload_on_uss && (end_of_request - (uwsgi.workers[uwsgi.mywid].last_spawn * 1000000) >= uwsgi.min_worker_lifetime * 1000000)) { goodbye_cruel_world("reload-on-uss limit reached (%llu >= %llu)", (unsigned long long) (rlim_t) uss, (unsigned long long) uwsgi.reload_on_uss ); } if (uwsgi.reload_on_pss && (rlim_t) pss >= uwsgi.reload_on_pss && (end_of_request - (uwsgi.workers[uwsgi.mywid].last_spawn * 1000000) >= uwsgi.min_worker_lifetime * 1000000)) { goodbye_cruel_world("reload-on-pss limit reached (%llu >= %llu)", (unsigned long long) (rlim_t) pss, (unsigned long long) uwsgi.reload_on_pss ); } #endif // after the first request, if i am a vassal, signal Emperor about my loyalty if (uwsgi.has_emperor && !uwsgi.loyal) { uwsgi_log("announcing my loyalty to the Emperor...\n"); char byte = 17; if (write(uwsgi.emperor_fd, &byte, 1) != 1) { uwsgi_error("write()"); } uwsgi.loyal = 1; } #ifdef __linux__ #ifdef MADV_MERGEABLE // run the ksm mapper if (uwsgi.linux_ksm > 0 && (uwsgi.workers[uwsgi.mywid].requests % uwsgi.linux_ksm) == 0) { uwsgi_linux_ksm_map(); } #endif #endif } #ifdef __linux__ #ifdef MADV_MERGEABLE void uwsgi_linux_ksm_map(void) { int dirty = 0; size_t i; unsigned long long start = 0, end = 0; int errors = 0; int lines = 0; int fd = open("/proc/self/maps", O_RDONLY); if (fd < 0) { uwsgi_error_open("[uwsgi-KSM] /proc/self/maps"); return; } // allocate memory if not available; if (uwsgi.ksm_mappings_current == NULL) { if (!uwsgi.ksm_buffer_size) uwsgi.ksm_buffer_size = 32768; uwsgi.ksm_mappings_current = uwsgi_malloc(uwsgi.ksm_buffer_size); uwsgi.ksm_mappings_current_size = 0; } if (uwsgi.ksm_mappings_last == NULL) { if (!uwsgi.ksm_buffer_size) uwsgi.ksm_buffer_size = 32768; uwsgi.ksm_mappings_last = uwsgi_malloc(uwsgi.ksm_buffer_size); uwsgi.ksm_mappings_last_size = 0; } uwsgi.ksm_mappings_current_size = read(fd, uwsgi.ksm_mappings_current, uwsgi.ksm_buffer_size); close(fd); if (uwsgi.ksm_mappings_current_size <= 0) { uwsgi_log("[uwsgi-KSM] unable to read /proc/self/maps data\n"); return; } // we now have areas if (uwsgi.ksm_mappings_last_size == 0 || uwsgi.ksm_mappings_current_size != uwsgi.ksm_mappings_last_size) { dirty = 1; } else { if (memcmp(uwsgi.ksm_mappings_current, uwsgi.ksm_mappings_last, uwsgi.ksm_mappings_current_size) != 0) { dirty = 1; } } // it is dirty, swap addresses and parse it if (dirty) { char *tmp = uwsgi.ksm_mappings_last; uwsgi.ksm_mappings_last = uwsgi.ksm_mappings_current; uwsgi.ksm_mappings_current = tmp; size_t tmp_size = uwsgi.ksm_mappings_last_size; uwsgi.ksm_mappings_last_size = uwsgi.ksm_mappings_current_size; uwsgi.ksm_mappings_current_size = tmp_size; // scan each line and call madvise on it char *ptr = uwsgi.ksm_mappings_last; for (i = 0; i < uwsgi.ksm_mappings_last_size; i++) { if (uwsgi.ksm_mappings_last[i] == '\n') { lines++; uwsgi.ksm_mappings_last[i] = 0; if (sscanf(ptr, "%llx-%llx %*s", &start, &end) == 2) { if (madvise((void *) (long) start, (size_t) (end - start), MADV_MERGEABLE)) { errors++; } } uwsgi.ksm_mappings_last[i] = '\n'; ptr = uwsgi.ksm_mappings_last + i + 1; } } if (errors >= lines) { uwsgi_error("[uwsgi-KSM] unable to share pages"); } } } #endif #endif #ifdef __linux__ long uwsgi_num_from_file(char *filename, int quiet) { char buf[16]; ssize_t len; int fd = open(filename, O_RDONLY); if (fd < 0) { if (!quiet) uwsgi_error_open(filename); return -1L; } len = read(fd, buf, sizeof(buf)); if (len == 0) { if (!quiet) uwsgi_log("read error %s\n", filename); close(fd); return -1L; } close(fd); return strtol(buf, (char **) NULL, 10); } #endif // setup for a new request void wsgi_req_setup(struct wsgi_request *wsgi_req, int async_id, struct uwsgi_socket *uwsgi_sock) { wsgi_req->app_id = -1; wsgi_req->async_id = async_id; wsgi_req->sendfile_fd = -1; wsgi_req->hvec = uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].hvec; // skip the first 4 bytes; wsgi_req->uh = (struct uwsgi_header *) uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].buffer; wsgi_req->buffer = uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].buffer + 4; if (uwsgi.post_buffering > 0) { wsgi_req->post_buffering_buf = uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].post_buf; } if (uwsgi_sock) { wsgi_req->socket = uwsgi_sock; } uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].in_request = 0; // now check for suspend request if (uwsgi.workers[uwsgi.mywid].suspended == 1) { uwsgi_log_verbose("*** worker %d suspended ***\n", uwsgi.mywid); cycle: // wait for some signal (normally SIGTSTP) or 10 seconds (as fallback) (void) poll(NULL, 0, 10 * 1000); if (uwsgi.workers[uwsgi.mywid].suspended == 1) goto cycle; uwsgi_log_verbose("*** worker %d resumed ***\n", uwsgi.mywid); } } int wsgi_req_async_recv(struct wsgi_request *wsgi_req) { uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].in_request = 1; wsgi_req->start_of_request = uwsgi_micros(); wsgi_req->start_of_request_in_sec = wsgi_req->start_of_request / 1000000; if (!wsgi_req->do_not_add_to_async_queue) { if (event_queue_add_fd_read(uwsgi.async_queue, wsgi_req->fd) < 0) return -1; async_add_timeout(wsgi_req, uwsgi.socket_timeout); uwsgi.async_proto_fd_table[wsgi_req->fd] = wsgi_req; } // enter harakiri mode if (uwsgi.harakiri_options.workers > 0) { set_harakiri(wsgi_req, uwsgi.harakiri_options.workers); } return 0; } // receive a new request int wsgi_req_recv(int queue, struct wsgi_request *wsgi_req) { uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].in_request = 1; wsgi_req->start_of_request = uwsgi_micros(); wsgi_req->start_of_request_in_sec = wsgi_req->start_of_request / 1000000; // edge triggered sockets get the whole request during accept() phase if (!wsgi_req->socket->edge_trigger) { for (;;) { int ret = wsgi_req->socket->proto(wsgi_req); if (ret == UWSGI_OK) break; if (ret == UWSGI_AGAIN) { ret = uwsgi_wait_read_req(wsgi_req); if (ret <= 0) return -1; continue; } return -1; } } // enter harakiri mode if (uwsgi.harakiri_options.workers > 0) { set_harakiri(wsgi_req, uwsgi.harakiri_options.workers); } #ifdef UWSGI_ROUTING if (uwsgi_apply_routes(wsgi_req) == UWSGI_ROUTE_BREAK) return 0; #endif wsgi_req->async_status = uwsgi.p[wsgi_req->uh->modifier1]->request(wsgi_req); return 0; } void uwsgi_post_accept(struct wsgi_request *wsgi_req) { // set close on exec (if not a new socket) if (!wsgi_req->socket->edge_trigger && uwsgi.close_on_exec) { if (fcntl(wsgi_req->fd, F_SETFD, FD_CLOEXEC) < 0) { uwsgi_error("fcntl()"); } } // enable TCP_NODELAY ? if (uwsgi.tcp_nodelay) { uwsgi_tcp_nodelay(wsgi_req->fd); } } // accept a new request int wsgi_req_simple_accept(struct wsgi_request *wsgi_req, int fd) { wsgi_req->fd = wsgi_req->socket->proto_accept(wsgi_req, fd); if (wsgi_req->fd < 0) { return -1; } uwsgi_post_accept(wsgi_req); return 0; } // send heartbeat to the emperor void uwsgi_heartbeat() { if (!uwsgi.has_emperor) return; time_t now = uwsgi_now(); if (uwsgi.next_heartbeat <= now) { char byte = 26; if (write(uwsgi.emperor_fd, &byte, 1) != 1) { uwsgi_error("write()"); } uwsgi.next_heartbeat = now + uwsgi.heartbeat; } } // accept a request int wsgi_req_accept(int queue, struct wsgi_request *wsgi_req) { int ret; int interesting_fd = -1; struct uwsgi_socket *uwsgi_sock = uwsgi.sockets; int timeout = -1; thunder_lock; // Recheck the manage_next_request before going forward. // This is because the worker might get cheaped while it's // blocking on the thunder_lock, because thunder_lock is // not interruptable, it'll slow down the cheaping process // (the worker will handle the next request before shuts down). if (!uwsgi.workers[uwsgi.mywid].manage_next_request) { thunder_unlock; return -1; } // heartbeat // in multithreaded mode we are now locked if (uwsgi.has_emperor && uwsgi.heartbeat) { time_t now = uwsgi_now(); // overengineering ... (reduce skew problems) timeout = uwsgi.heartbeat; if (!uwsgi.next_heartbeat) { uwsgi.next_heartbeat = now; } if (uwsgi.next_heartbeat >= now) { timeout = uwsgi.next_heartbeat - now; } } // need edge trigger ? if (uwsgi.is_et) { while (uwsgi_sock) { if (uwsgi_sock->retry && uwsgi_sock->retry[wsgi_req->async_id]) { timeout = 0; break; } uwsgi_sock = uwsgi_sock->next; } // reset pointer uwsgi_sock = uwsgi.sockets; } ret = event_queue_wait(queue, timeout, &interesting_fd); if (ret < 0) { thunder_unlock; return -1; } // check for heartbeat if (uwsgi.has_emperor && uwsgi.heartbeat) { uwsgi_heartbeat(); // no need to continue if timed-out if (ret == 0) { thunder_unlock; return -1; } } // kill the thread after the request completion if (uwsgi.threads > 1) pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &ret); if (uwsgi.signal_socket > -1 && (interesting_fd == uwsgi.signal_socket || interesting_fd == uwsgi.my_signal_socket)) { thunder_unlock; uwsgi_receive_signal(wsgi_req, interesting_fd, "worker", uwsgi.mywid); if (uwsgi.threads > 1) pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &ret); return -1; } while (uwsgi_sock) { if (interesting_fd == uwsgi_sock->fd || (uwsgi_sock->retry && uwsgi_sock->retry[wsgi_req->async_id]) || (uwsgi_sock->fd_threads && interesting_fd == uwsgi_sock->fd_threads[wsgi_req->async_id])) { wsgi_req->socket = uwsgi_sock; wsgi_req->fd = wsgi_req->socket->proto_accept(wsgi_req, interesting_fd); thunder_unlock; if (wsgi_req->fd < 0) { if (uwsgi.threads > 1) pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &ret); return -1; } if (!uwsgi_sock->edge_trigger) { uwsgi_post_accept(wsgi_req); } return 0; } uwsgi_sock = uwsgi_sock->next; } thunder_unlock; if (uwsgi.threads > 1) pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &ret); return -1; } // translate a OS env to a uWSGI option void env_to_arg(char *src, char *dst) { int i; int val = 0; for (i = 0; i < (int) strlen(src); i++) { if (src[i] == '=') { val = 1; } if (val) { dst[i] = src[i]; } else { dst[i] = tolower((int) src[i]); if (dst[i] == '_') { dst[i] = '-'; } } } dst[strlen(src)] = 0; } // parse OS envs void parse_sys_envs(char **envs) { char **uenvs = envs; char *earg, *eq_pos; while (*uenvs) { if (!strncmp(*uenvs, "UWSGI_", 6) && strncmp(*uenvs, "UWSGI_RELOADS=", 14) && strncmp(*uenvs, "UWSGI_VASSALS_DIR=", 18) && strncmp(*uenvs, "UWSGI_EMPEROR_FD=", 17) && strncmp(*uenvs, "UWSGI_BROODLORD_NUM=", 20) && strncmp(*uenvs, "UWSGI_EMPEROR_FD_CONFIG=", 24) && strncmp(*uenvs, "UWSGI_EMPEROR_PROXY=", 20) && strncmp(*uenvs, "UWSGI_JAIL_PID=", 15) && strncmp(*uenvs, "UWSGI_ORIGINAL_PROC_NAME=", 25)) { earg = uwsgi_malloc(strlen(*uenvs + 6) + 1); env_to_arg(*uenvs + 6, earg); eq_pos = strchr(earg, '='); if (!eq_pos) { break; } eq_pos[0] = 0; add_exported_option(earg, eq_pos + 1, 0); } uenvs++; } } // get the application id int uwsgi_get_app_id(struct wsgi_request *wsgi_req, char *key, uint16_t key_len, int modifier1) { int i; struct stat st; int found; char *app_name = key; uint16_t app_name_len = key_len; if (app_name_len == 0 && wsgi_req) { app_name = wsgi_req->appid; app_name_len = wsgi_req->appid_len; if (app_name_len == 0) { if (!uwsgi.ignore_script_name) { app_name = wsgi_req->script_name; app_name_len = wsgi_req->script_name_len; } if (uwsgi.vhost) { char *vhost_name = uwsgi_concat3n(wsgi_req->host, wsgi_req->host_len, "|", 1, wsgi_req->script_name, wsgi_req->script_name_len); app_name_len = wsgi_req->host_len + 1 + wsgi_req->script_name_len; app_name = uwsgi_req_append(wsgi_req, "UWSGI_APPID", 11, vhost_name, app_name_len); free(vhost_name); if (!app_name) { uwsgi_log("unable to add UWSGI_APPID to the uwsgi buffer, consider increasing it\n"); return -1; } #ifdef UWSGI_DEBUG uwsgi_debug("VirtualHost KEY=%.*s\n", app_name_len, app_name); #endif } wsgi_req->appid = app_name; wsgi_req->appid_len = app_name_len; } } for (i = 0; i < uwsgi_apps_cnt; i++) { // reset check found = 0; #ifdef UWSGI_DEBUG uwsgi_log("searching for %.*s in %.*s %p\n", app_name_len, app_name, uwsgi_apps[i].mountpoint_len, uwsgi_apps[i].mountpoint, uwsgi_apps[i].callable); #endif if (!uwsgi_apps[i].callable) { continue; } if (!uwsgi_strncmp(uwsgi_apps[i].mountpoint, uwsgi_apps[i].mountpoint_len, app_name, app_name_len)) { found = 1; } if (found) { if (uwsgi_apps[i].touch_reload[0]) { if (!stat(uwsgi_apps[i].touch_reload, &st)) { if (st.st_mtime != uwsgi_apps[i].touch_reload_mtime) { // serve the new request and reload uwsgi.workers[uwsgi.mywid].manage_next_request = 0; if (uwsgi.threads > 1) { uwsgi.workers[uwsgi.mywid].destroy = 1; } #ifdef UWSGI_DEBUG uwsgi_log("mtime %d %d\n", st.st_mtime, uwsgi_apps[i].touch_reload_mtime); #endif } } } if (modifier1 == -1) return i; if (modifier1 == uwsgi_apps[i].modifier1) return i; } } return -1; } char *uwsgi_substitute(char *src, char *what, char *with) { int count = 0; if (!with) return src; size_t len = strlen(src); size_t wlen = strlen(what); size_t with_len = strlen(with); char *p = strstr(src, what); if (!p) { return src; } while (p) { count++; p = strstr(p + wlen, what); } len += (count * with_len) + 1; char *dst = uwsgi_calloc(len); char *ptr = src; p = strstr(ptr, what); while (p) { strncat(dst, ptr, (p - ptr)); strncat(dst, with, with_len); ptr = p + wlen; p = strstr(ptr, what); } strncat(dst, ptr, strlen(ptr)); return dst; } int uwsgi_is_file(char *filename) { struct stat st; if (stat(filename, &st)) { return 0; } if (S_ISREG(st.st_mode)) return 1; return 0; } int uwsgi_is_file2(char *filename, struct stat *st) { if (stat(filename, st)) { return 0; } if (S_ISREG(st->st_mode)) return 1; return 0; } int uwsgi_is_dir(char *filename) { struct stat st; if (stat(filename, &st)) { return 0; } if (S_ISDIR(st.st_mode)) return 1; return 0; } int uwsgi_is_link(char *filename) { struct stat st; if (lstat(filename, &st)) { return 0; } if (S_ISLNK(st.st_mode)) return 1; return 0; } void *uwsgi_malloc(size_t size) { char *ptr = malloc(size); if (ptr == NULL) { uwsgi_error("malloc()"); uwsgi_log("!!! tried memory allocation of %llu bytes !!!\n", (unsigned long long) size); uwsgi_backtrace(uwsgi.backtrace_depth); exit(1); } return ptr; } void *uwsgi_calloc(size_t size) { // thanks Mathieu Dupuy for pointing out that calloc is faster // than malloc + memset char *ptr = calloc(1, size); if (ptr == NULL) { uwsgi_error("calloc()"); uwsgi_log("!!! tried memory allocation of %llu bytes !!!\n", (unsigned long long) size); uwsgi_backtrace(uwsgi.backtrace_depth); exit(1); } return ptr; } #ifdef AF_INET6 #define ADDR_AF_INET_FAMILY(addrtype) (addrtype == AF_INET || addrtype == AF_INET6) #else #define ADDR_AF_INET_FAMILY(addrtype) (addrtype == AF_INET) #endif char *uwsgi_resolve_ip(char *domain) { struct hostent *he; he = gethostbyname(domain); if (!he || !*he->h_addr_list || !ADDR_AF_INET_FAMILY(he->h_addrtype)) { return NULL; } return inet_ntoa(*(struct in_addr *) he->h_addr_list[0]); } int uwsgi_file_exists(char *filename) { // TODO check for http url or stdin return !access(filename, R_OK); } int uwsgi_file_executable(char *filename) { // TODO check for http url or stdin return !access(filename, R_OK | X_OK); } char *magic_sub(char *buffer, size_t len, size_t * size, char *magic_table[]) { size_t i; size_t magic_len = 0; char *magic_buf = uwsgi_malloc(len); char *magic_ptr = magic_buf; char *old_magic_buf; for (i = 0; i < len; i++) { if (buffer[i] == '%' && (i + 1) < len && magic_table[(unsigned char) buffer[i + 1]]) { old_magic_buf = magic_buf; magic_buf = uwsgi_concat3n(old_magic_buf, magic_len, magic_table[(unsigned char) buffer[i + 1]], strlen(magic_table[(unsigned char) buffer[i + 1]]), buffer + i + 2, len - i - 2); free(old_magic_buf); magic_len += strlen(magic_table[(unsigned char) buffer[i + 1]]); magic_ptr = magic_buf + magic_len; i++; } else { *magic_ptr = buffer[i]; magic_ptr++; magic_len++; } } *size = magic_len; return magic_buf; } void init_magic_table(char *magic_table[]) { int i; for (i = 0; i <= 0xff; i++) { magic_table[i] = ""; } magic_table['%'] = "%"; magic_table['('] = "%("; } char *uwsgi_num2str(int num) { char *str = uwsgi_malloc(11); snprintf(str, 11, "%d", num); return str; } char *uwsgi_64bit2str(int64_t num) { char *str = uwsgi_malloc(sizeof(MAX64_STR) + 1); snprintf(str, sizeof(MAX64_STR) + 1, "%lld", (long long) num); return str; } int uwsgi_num2str2(int num, char *ptr) { return snprintf(ptr, 11, "%d", num); } int uwsgi_num2str2n(int num, char *ptr, int size) { return snprintf(ptr, size, "%d", num); } int uwsgi_long2str2n(unsigned long long num, char *ptr, int size) { int ret = snprintf(ptr, size, "%llu", num); if (ret <= 0 || ret > size) return 0; return ret; } int is_unix(char *socket_name, int len) { return !memchr(socket_name, ':', len); } int is_a_number(char *what) { int i; for (i = 0; i < (int) strlen(what); i++) { if (!isdigit((int) what[i])) return 0; } return 1; } void uwsgi_unix_signal(int signum, void (*func) (int)) { struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = func; sigemptyset(&sa.sa_mask); if (sigaction(signum, &sa, NULL) < 0) { uwsgi_error("sigaction()"); } } int uwsgi_list_has_num(char *list, int num) { char *list2 = uwsgi_concat2(list, ""); char *p, *ctx = NULL; uwsgi_foreach_token(list2, ",", p, ctx) { if (atoi(p) == num) { free(list2); return 1; } } free(list2); return 0; } int uwsgi_list_has_str(char *list, char *str) { char *list2 = uwsgi_str(list); char *p, *ctx = NULL; uwsgi_foreach_token(list2, " ", p, ctx) { if (!strcasecmp(p, str)) { free(list2); return 1; } } free(list2); return 0; } static char hex2num(char *str) { char val = 0; val <<= 4; if (str[0] >= '0' && str[0] <= '9') { val += str[0] & 0x0F; } else if (str[0] >= 'A' && str[0] <= 'F') { val += (str[0] & 0x0F) + 9; } else if (str[0] >= 'a' && str[0] <= 'f') { val += (str[0] & 0x0F) + 9; } else { return 0; } val <<= 4; if (str[1] >= '0' && str[1] <= '9') { val += str[1] & 0x0F; } else if (str[1] >= 'A' && str[1] <= 'F') { val += (str[1] & 0x0F) + 9; } else if (str[1] >= 'a' && str[1] <= 'f') { val += (str[1] & 0x0F) + 9; } else { return 0; } return val; } int uwsgi_str2_num(char *str) { int num = 0; num = 10 * (str[0] - 48); num += str[1] - 48; return num; } int uwsgi_str3_num(char *str) { int num = 0; num = 100 * (str[0] - 48); num += 10 * (str[1] - 48); num += str[2] - 48; return num; } int uwsgi_str4_num(char *str) { int num = 0; num = 1000 * (str[0] - 48); num += 100 * (str[1] - 48); num += 10 * (str[2] - 48); num += str[3] - 48; return num; } uint64_t uwsgi_str_num(char *str, int len) { int i; uint64_t num = 0; uint64_t delta = pow(10, len); for (i = 0; i < len; i++) { delta = delta / 10; num += delta * (str[i] - 48); } return num; } char *uwsgi_split3(char *buf, size_t len, char sep, char **part1, size_t * part1_len, char **part2, size_t * part2_len, char **part3, size_t * part3_len) { size_t i; int status = 0; *part1 = NULL; *part2 = NULL; *part3 = NULL; for (i = 0; i < len; i++) { if (buf[i] == sep) { // get part1 if (status == 0) { *part1 = buf; *part1_len = i; status = 1; } // get part2 else if (status == 1) { *part2 = *part1 + *part1_len + 1; *part2_len = (buf + i) - *part2; break; } } } if (*part1 && *part2) { if (*part2 + *part2_len + 1 > buf + len) { return NULL; } *part3 = *part2 + *part2_len + 1; *part3_len = (buf + len) - *part3; return buf + len; } return NULL; } char *uwsgi_split4(char *buf, size_t len, char sep, char **part1, size_t * part1_len, char **part2, size_t * part2_len, char **part3, size_t * part3_len, char **part4, size_t * part4_len) { size_t i; int status = 0; *part1 = NULL; *part2 = NULL; *part3 = NULL; *part4 = NULL; for (i = 0; i < len; i++) { if (buf[i] == sep) { // get part1 if (status == 0) { *part1 = buf; *part1_len = i; status = 1; } // get part2 else if (status == 1) { *part2 = *part1 + *part1_len + 1; *part2_len = (buf + i) - *part2; status = 2; } // get part3 else if (status == 2) { *part3 = *part2 + *part2_len + 1; *part3_len = (buf + i) - *part3; break; } } } if (*part1 && *part2 && *part3) { if (*part3 + *part3_len + 1 > buf + len) { return NULL; } *part4 = *part3 + *part3_len + 1; *part4_len = (buf + len) - *part4; return buf + len; } return NULL; } char *uwsgi_netstring(char *buf, size_t len, char **netstring, size_t * netstring_len) { char *ptr = buf; char *watermark = buf + len; *netstring_len = 0; while (ptr < watermark) { // end of string size ? if (*ptr == ':') { *netstring_len = uwsgi_str_num(buf, ptr - buf); if (ptr + *netstring_len + 2 > watermark) { return NULL; } *netstring = ptr + 1; return ptr + *netstring_len + 2; } ptr++; } return NULL; } struct uwsgi_dyn_dict *uwsgi_dyn_dict_new(struct uwsgi_dyn_dict **dd, char *key, int keylen, char *val, int vallen) { struct uwsgi_dyn_dict *uwsgi_dd = *dd, *old_dd; if (!uwsgi_dd) { *dd = uwsgi_malloc(sizeof(struct uwsgi_dyn_dict)); uwsgi_dd = *dd; uwsgi_dd->prev = NULL; } else { while (uwsgi_dd) { old_dd = uwsgi_dd; uwsgi_dd = uwsgi_dd->next; } uwsgi_dd = uwsgi_malloc(sizeof(struct uwsgi_dyn_dict)); old_dd->next = uwsgi_dd; uwsgi_dd->prev = old_dd; } uwsgi_dd->key = key; uwsgi_dd->keylen = keylen; uwsgi_dd->value = val; uwsgi_dd->vallen = vallen; uwsgi_dd->hits = 0; uwsgi_dd->status = 0; uwsgi_dd->next = NULL; return uwsgi_dd; } void uwsgi_dyn_dict_del(struct uwsgi_dyn_dict *item) { struct uwsgi_dyn_dict *prev = item->prev; struct uwsgi_dyn_dict *next = item->next; if (prev) { prev->next = next; } if (next) { next->prev = prev; } free(item); } void uwsgi_dyn_dict_free(struct uwsgi_dyn_dict **dd) { struct uwsgi_dyn_dict *attr = *dd; while(attr) { struct uwsgi_dyn_dict *tmp = attr; attr = attr->next; if (tmp->value) free(tmp->value); free(tmp); } *dd = NULL; } void *uwsgi_malloc_shared(size_t size) { void *addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0); if (addr == MAP_FAILED) { uwsgi_log("unable to allocate %llu bytes (%lluMB)\n", (unsigned long long) size, (unsigned long long) (size / (1024 * 1024))); uwsgi_error("mmap()"); exit(1); } return addr; } void *uwsgi_calloc_shared(size_t size) { void *ptr = uwsgi_malloc_shared(size); // NOTE by Mathieu Dupuy: // OSes guarantee mmap MAP_ANON memory area to be zero-filled (see man pages) // we should trust it, but history has taught us it is better to be paranoid. // Lucky enough this function is called ony in startup phases, so performance // tips/tricks are irrelevant (So, le'ts call memset...) memset(ptr, 0, size); return ptr; } struct uwsgi_string_list *uwsgi_string_new_list(struct uwsgi_string_list **list, char *value) { struct uwsgi_string_list *uwsgi_string = *list, *old_uwsgi_string; if (!uwsgi_string) { *list = uwsgi_malloc(sizeof(struct uwsgi_string_list)); uwsgi_string = *list; } else { while (uwsgi_string) { old_uwsgi_string = uwsgi_string; uwsgi_string = uwsgi_string->next; } uwsgi_string = uwsgi_malloc(sizeof(struct uwsgi_string_list)); old_uwsgi_string->next = uwsgi_string; } uwsgi_string->value = value; uwsgi_string->len = 0; if (value) { uwsgi_string->len = strlen(value); } uwsgi_string->next = NULL; uwsgi_string->custom = 0; uwsgi_string->custom2 = 0; uwsgi_string->custom_ptr = NULL; return uwsgi_string; } #ifdef UWSGI_PCRE struct uwsgi_regexp_list *uwsgi_regexp_custom_new_list(struct uwsgi_regexp_list **list, char *value, char *custom) { struct uwsgi_regexp_list *url = *list, *old_url; if (!url) { *list = uwsgi_malloc(sizeof(struct uwsgi_regexp_list)); url = *list; } else { while (url) { old_url = url; url = url->next; } url = uwsgi_malloc(sizeof(struct uwsgi_regexp_list)); old_url->next = url; } if (uwsgi_regexp_build(value, &url->pattern, &url->pattern_extra)) { exit(1); } url->next = NULL; url->custom = 0; url->custom_ptr = NULL; url->custom_str = custom; return url; } int uwsgi_regexp_match_pattern(char *pattern, char *str) { pcre *regexp; pcre_extra *regexp_extra; if (uwsgi_regexp_build(pattern, &regexp, &regexp_extra)) return 1; return !uwsgi_regexp_match(regexp, regexp_extra, str, strlen(str)); } #endif char *uwsgi_string_get_list(struct uwsgi_string_list **list, int pos, size_t * len) { struct uwsgi_string_list *uwsgi_string = *list; int counter = 0; while (uwsgi_string) { if (counter == pos) { *len = uwsgi_string->len; return uwsgi_string->value; } uwsgi_string = uwsgi_string->next; counter++; } *len = 0; return NULL; } void uwsgi_string_del_list(struct uwsgi_string_list **list, struct uwsgi_string_list *item) { struct uwsgi_string_list *uwsgi_string = *list, *old_uwsgi_string = NULL; while (uwsgi_string) { if (uwsgi_string == item) { // parent instance ? if (old_uwsgi_string == NULL) { *list = uwsgi_string->next; } else { old_uwsgi_string->next = uwsgi_string->next; } free(uwsgi_string); return; } old_uwsgi_string = uwsgi_string; uwsgi_string = uwsgi_string->next; } } void uwsgi_sig_pause() { sigset_t mask; sigemptyset(&mask); sigsuspend(&mask); } char *uwsgi_binsh() { struct uwsgi_string_list *usl = NULL; uwsgi_foreach(usl, uwsgi.binsh) { if (uwsgi_file_executable(usl->value)) { return usl->value; } } return "/bin/sh"; } void uwsgi_exec_command_with_args(char *cmdline) { char *argv[4]; argv[0] = uwsgi_binsh(); argv[1] = "-c"; argv[2] = cmdline; argv[3] = NULL; execvp(argv[0], argv); uwsgi_error("execvp()"); exit(1); } static int uwsgi_run_command_do(char *command, char *arg) { char *argv[4]; #ifdef __linux__ if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0)) { uwsgi_error("prctl()"); } #endif if (command == NULL) { argv[0] = uwsgi_binsh(); argv[1] = "-c"; argv[2] = arg; argv[3] = NULL; execvp(argv[0], argv); } else { argv[0] = command; argv[1] = arg; argv[2] = NULL; execvp(command, argv); } uwsgi_error("execvp()"); //never here exit(1); } int uwsgi_run_command_and_wait(char *command, char *arg) { int waitpid_status = 0; pid_t pid = fork(); if (pid < 0) { return -1; } if (pid > 0) { if (waitpid(pid, &waitpid_status, 0) < 0) { uwsgi_error("uwsgi_run_command_and_wait()/waitpid()"); return -1; } return WEXITSTATUS(waitpid_status); } return uwsgi_run_command_do(command, arg); } int uwsgi_run_command_putenv_and_wait(char *command, char *arg, char **envs, unsigned int nenvs) { int waitpid_status = 0; pid_t pid = fork(); if (pid < 0) { return -1; } if (pid > 0) { if (waitpid(pid, &waitpid_status, 0) < 0) { uwsgi_error("uwsgi_run_command_and_wait()/waitpid()"); return -1; } return WEXITSTATUS(waitpid_status); } unsigned int i; for (i = 0; i < nenvs; i++) { if (putenv(envs[i])) { uwsgi_error("uwsgi_run_command_putenv_and_wait()/putenv()"); exit(1); } } return uwsgi_run_command_do(command, arg); } pid_t uwsgi_run_command(char *command, int *stdin_fd, int stdout_fd) { char *argv[4]; int waitpid_status = 0; pid_t pid = fork(); if (pid < 0) { return -1; } if (pid > 0) { if (stdin_fd && stdin_fd[0] > -1) { close(stdin_fd[0]); } if (stdout_fd > -1) { close(stdout_fd); } if (waitpid(pid, &waitpid_status, WNOHANG) < 0) { uwsgi_error("waitpid()"); return -1; } return pid; } uwsgi_close_all_sockets(); //uwsgi_close_all_fds(); int i; for (i = 3; i < (int) uwsgi.max_fd; i++) { if (stdin_fd) { if (i == stdin_fd[0] || i == stdin_fd[1]) { continue; } } if (stdout_fd > -1) { if (i == stdout_fd) { continue; } } #ifdef __APPLE__ fcntl(i, F_SETFD, FD_CLOEXEC); #else close(i); #endif } if (stdin_fd) { close(stdin_fd[1]); } else { if (!uwsgi_valid_fd(0)) { int in_fd = open("/dev/null", O_RDONLY); if (in_fd < 0) { uwsgi_error_open("/dev/null"); } else { if (in_fd != 0) { if (dup2(in_fd, 0) < 0) { uwsgi_error("dup2()"); } } } } } if (stdout_fd > -1 && stdout_fd != 1) { if (dup2(stdout_fd, 1) < 0) { uwsgi_error("dup2()"); exit(1); } } if (stdin_fd && stdin_fd[0] > -1 && stdin_fd[0] != 0) { if (dup2(stdin_fd[0], 0) < 0) { uwsgi_error("dup2()"); exit(1); } } if (setsid() < 0) { uwsgi_error("setsid()"); exit(1); } argv[0] = uwsgi_binsh(); argv[1] = "-c"; argv[2] = command; argv[3] = NULL; execvp(uwsgi_binsh(), argv); uwsgi_error("execvp()"); //never here exit(1); } int uwsgi_endswith(char *str1, char *str2) { size_t i; size_t str1len = strlen(str1); size_t str2len = strlen(str2); char *ptr; if (str2len > str1len) return 0; ptr = (str1 + str1len) - str2len; for (i = 0; i < str2len; i++) { if (*ptr != str2[i]) return 0; ptr++; } return 1; } void uwsgi_chown(char *filename, char *owner) { uid_t new_uid = -1; uid_t new_gid = -1; struct group *new_group = NULL; struct passwd *new_user = NULL; char *colon = strchr(owner, ':'); if (colon) { colon[0] = 0; } if (is_a_number(owner)) { new_uid = atoi(owner); } else { new_user = getpwnam(owner); if (!new_user) { uwsgi_log("unable to find user %s\n", owner); exit(1); } new_uid = new_user->pw_uid; } if (colon) { colon[0] = ':'; if (is_a_number(colon + 1)) { new_gid = atoi(colon + 1); } else { new_group = getgrnam(colon + 1); if (!new_group) { uwsgi_log("unable to find group %s\n", colon + 1); exit(1); } new_gid = new_group->gr_gid; } } if (chown(filename, new_uid, new_gid)) { uwsgi_error("chown()"); exit(1); } } char *uwsgi_get_binary_path(char *argvzero) { #if defined(__linux__) || defined(__CYGWIN__) char *buf = uwsgi_calloc(PATH_MAX + 1); ssize_t len = readlink("/proc/self/exe", buf, PATH_MAX); if (len > 0) { return buf; } free(buf); #elif defined(_WIN32) char *buf = uwsgi_calloc(PATH_MAX + 1); if (GetModuleFileName(NULL, buf, PATH_MAX) > 0) { return buf; } free(buf); #elif defined(__NetBSD__) char *buf = uwsgi_calloc(PATH_MAX + 1); ssize_t len = readlink("/proc/curproc/exe", buf, PATH_MAX); if (len > 0) { return buf; } if (realpath(argvzero, buf)) { return buf; } free(buf); #elif defined(__APPLE__) char *buf = uwsgi_malloc(uwsgi.page_size); uint32_t len = uwsgi.page_size; if (_NSGetExecutablePath(buf, &len) == 0) { // return only absolute path #ifndef OLD_REALPATH char *newbuf = realpath(buf, NULL); if (newbuf) { free(buf); return newbuf; } #endif } free(buf); #elif defined(__sun__) // do not free this value !!! char *buf = (char *) getexecname(); if (buf) { // return only absolute path if (buf[0] == '/') { return buf; } char *newbuf = uwsgi_malloc(PATH_MAX + 1); if (realpath(buf, newbuf)) { return newbuf; } } #elif defined(__FreeBSD__) || defined(__GNU_kFreeBSD__) char *buf = uwsgi_malloc(uwsgi.page_size); size_t len = uwsgi.page_size; int mib[4]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PATHNAME; mib[3] = -1; if (sysctl(mib, 4, buf, &len, NULL, 0) == 0) { return buf; } free(buf); #endif return argvzero; } char *uwsgi_get_line(char *ptr, char *watermark, int *size) { char *p = ptr; int count = 0; while (p < watermark) { if (*p == '\n') { *size = count; return ptr + count; } count++; p++; } return NULL; } void uwsgi_build_mime_dict(char *filename) { size_t size = 0; char *buf = uwsgi_open_and_read(filename, &size, 1, NULL); char *watermark = buf + size; int linesize = 0; char *line = buf; int i; int type_size = 0; int ext_start = 0; int found; int entries = 0; uwsgi_log("building mime-types dictionary from file %s...", filename); while (uwsgi_get_line(line, watermark, &linesize) != NULL) { found = 0; if (isalnum((int) line[0])) { // get the type size for (i = 0; i < linesize; i++) { if (isblank((int) line[i])) { type_size = i; found = 1; break; } } if (!found) { line += linesize + 1; continue; } found = 0; for (i = type_size; i < linesize; i++) { if (!isblank((int) line[i])) { ext_start = i; found = 1; break; } } if (!found) { line += linesize + 1; continue; } char *current = line + ext_start; int ext_size = 0; for (i = ext_start; i < linesize; i++) { if (isblank((int) line[i])) { #ifdef UWSGI_DEBUG uwsgi_log("%.*s %.*s\n", ext_size, current, type_size, line); #endif uwsgi_dyn_dict_new(&uwsgi.mimetypes, current, ext_size, line, type_size); entries++; ext_size = 0; current = NULL; continue; } else if (current == NULL) { current = line + i; } ext_size++; } if (current && ext_size > 1) { #ifdef UWSGI_DEBUG uwsgi_log("%.*s %.*s\n", ext_size, current, type_size, line); #endif uwsgi_dyn_dict_new(&uwsgi.mimetypes, current, ext_size, line, type_size); entries++; } } line += linesize + 1; } uwsgi_log("%d entry found\n", entries); } #ifdef __linux__ struct uwsgi_unshare_id { char *name; int value; }; static struct uwsgi_unshare_id uwsgi_unshare_list[] = { #ifdef CLONE_FILES {"files", CLONE_FILES}, #endif #ifdef CLONE_NEWIPC {"ipc", CLONE_NEWIPC}, #endif #ifdef CLONE_NEWNET {"net", CLONE_NEWNET}, #endif #ifdef CLONE_IO {"io", CLONE_IO}, #endif #ifdef CLONE_PARENT {"parent", CLONE_PARENT}, #endif #ifdef CLONE_NEWPID {"pid", CLONE_NEWPID}, #endif #ifdef CLONE_NEWNS {"ns", CLONE_NEWNS}, {"fs", CLONE_NEWNS}, {"mount", CLONE_NEWNS}, {"mnt", CLONE_NEWNS}, #endif #ifdef CLONE_SYSVSEM {"sysvsem", CLONE_SYSVSEM}, #endif #ifdef CLONE_NEWUTS {"uts", CLONE_NEWUTS}, #endif #ifdef CLONE_NEWUSER {"user", CLONE_NEWUSER}, #endif {NULL, -1} }; static int uwsgi_get_unshare_id(char *name) { struct uwsgi_unshare_id *uui = uwsgi_unshare_list; while (uui->name) { if (!strcmp(uui->name, name)) return uui->value; uui++; } return -1; } void uwsgi_build_unshare(char *what, int *mask) { char *list = uwsgi_str(what); char *p, *ctx = NULL; uwsgi_foreach_token(list, ",", p, ctx) { int u_id = uwsgi_get_unshare_id(p); if (u_id != -1) { *mask |= u_id; } else { uwsgi_log("unknown namespace subsystem: %s\n", p); exit(1); } } free(list); } #endif #ifdef UWSGI_CAP struct uwsgi_cap { char *name; cap_value_t value; }; static struct uwsgi_cap uwsgi_cap_list[] = { {"chown", CAP_CHOWN}, {"dac_override", CAP_DAC_OVERRIDE}, {"dac_read_search", CAP_DAC_READ_SEARCH}, {"fowner", CAP_FOWNER}, {"fsetid", CAP_FSETID}, {"kill", CAP_KILL}, {"setgid", CAP_SETGID}, {"setuid", CAP_SETUID}, {"setpcap", CAP_SETPCAP}, {"linux_immutable", CAP_LINUX_IMMUTABLE}, {"net_bind_service", CAP_NET_BIND_SERVICE}, {"net_broadcast", CAP_NET_BROADCAST}, {"net_admin", CAP_NET_ADMIN}, {"net_raw", CAP_NET_RAW}, {"ipc_lock", CAP_IPC_LOCK}, {"ipc_owner", CAP_IPC_OWNER}, {"sys_module", CAP_SYS_MODULE}, {"sys_rawio", CAP_SYS_RAWIO}, {"sys_chroot", CAP_SYS_CHROOT}, {"sys_ptrace", CAP_SYS_PTRACE}, {"sys_pacct", CAP_SYS_PACCT}, {"sys_admin", CAP_SYS_ADMIN}, {"sys_boot", CAP_SYS_BOOT}, {"sys_nice", CAP_SYS_NICE}, {"sys_resource", CAP_SYS_RESOURCE}, {"sys_time", CAP_SYS_TIME}, {"sys_tty_config", CAP_SYS_TTY_CONFIG}, {"mknod", CAP_MKNOD}, #ifdef CAP_LEASE {"lease", CAP_LEASE}, #endif #ifdef CAP_AUDIT_WRITE {"audit_write", CAP_AUDIT_WRITE}, #endif #ifdef CAP_AUDIT_CONTROL {"audit_control", CAP_AUDIT_CONTROL}, #endif #ifdef CAP_SETFCAP {"setfcap", CAP_SETFCAP}, #endif #ifdef CAP_MAC_OVERRIDE {"mac_override", CAP_MAC_OVERRIDE}, #endif #ifdef CAP_MAC_ADMIN {"mac_admin", CAP_MAC_ADMIN}, #endif #ifdef CAP_SYSLOG {"syslog", CAP_SYSLOG}, #endif #ifdef CAP_WAKE_ALARM {"wake_alarm", CAP_WAKE_ALARM}, #endif {NULL, -1} }; static int uwsgi_get_cap_id(char *name) { struct uwsgi_cap *ucl = uwsgi_cap_list; while (ucl->name) { if (!strcmp(ucl->name, name)) return ucl->value; ucl++; } return -1; } int uwsgi_build_cap(char *what, cap_value_t ** cap) { int cap_id; char *caps = uwsgi_str(what); int pos = 0; int count = 0; char *p, *ctx = NULL; uwsgi_foreach_token(caps, ",", p, ctx) { if (is_a_number(p)) { count++; } else { cap_id = uwsgi_get_cap_id(p); if (cap_id != -1) { count++; } else { uwsgi_log("[security] unknown capability: %s\n", p); } } } free(caps); *cap = uwsgi_malloc(sizeof(cap_value_t) * count); caps = uwsgi_str(what); ctx = NULL; uwsgi_foreach_token(caps, ",", p, ctx) { if (is_a_number(p)) { cap_id = atoi(p); } else { cap_id = uwsgi_get_cap_id(p); } if (cap_id != -1) { (*cap)[pos] = cap_id; uwsgi_log("setting capability %s [%d]\n", p, cap_id); pos++; } else { uwsgi_log("[security] unknown capability: %s\n", p); } } free(caps); return count; } #endif void uwsgi_apply_config_pass(char symbol, char *(*hook) (char *)) { int i, j; for (i = 0; i < uwsgi.exported_opts_cnt; i++) { int has_symbol = 0; int depth = 0; char *magic_key = NULL; char *magic_val = NULL; if (uwsgi.exported_opts[i]->value && !uwsgi.exported_opts[i]->configured) { for (j = 0; j < (int) strlen(uwsgi.exported_opts[i]->value); j++) { if (uwsgi.exported_opts[i]->value[j] == symbol) { has_symbol = 1; } else if (uwsgi.exported_opts[i]->value[j] == '(' && has_symbol == 1) { has_symbol = 2; depth = 0; magic_key = uwsgi.exported_opts[i]->value + j + 1; } else if (has_symbol > 1) { if (uwsgi.exported_opts[i]->value[j] == '(') { has_symbol++; depth++; } else if (uwsgi.exported_opts[i]->value[j] == ')') { if (depth > 0) { has_symbol++; depth--; continue; } if (has_symbol <= 2) { magic_key = NULL; has_symbol = 0; continue; } #ifdef UWSGI_DEBUG uwsgi_log("need to interpret the %.*s tag\n", has_symbol - 2, magic_key); #endif char *tmp_magic_key = uwsgi_concat2n(magic_key, has_symbol - 2, "", 0); magic_val = hook(tmp_magic_key); free(tmp_magic_key); if (!magic_val) { magic_key = NULL; has_symbol = 0; continue; } uwsgi.exported_opts[i]->value = uwsgi_concat4n(uwsgi.exported_opts[i]->value, (magic_key - 2) - uwsgi.exported_opts[i]->value, magic_val, strlen(magic_val), magic_key + (has_symbol - 1), strlen(magic_key + (has_symbol - 1)), "", 0); #ifdef UWSGI_DEBUG uwsgi_log("computed new value = %s\n", uwsgi.exported_opts[i]->value); #endif magic_key = NULL; has_symbol = 0; j = 0; } else { has_symbol++; } } else { has_symbol = 0; } } } } } void uwsgi_set_processname(char *name) { #if defined(__linux__) || defined(__sun__) size_t amount = 0; size_t max_procname = uwsgi.argv_len + uwsgi.environ_len; // prepare for strncat *uwsgi.orig_argv[0] = 0; if (uwsgi.procname_prefix) { amount += strlen(uwsgi.procname_prefix); if (amount >= max_procname) return; strncat(uwsgi.orig_argv[0], uwsgi.procname_prefix, max_procname - (amount + 1)); } amount += strlen(name); if (amount >= max_procname) return; strncat(uwsgi.orig_argv[0], name, max_procname - (amount + 1)); if (uwsgi.procname_append) { amount += strlen(uwsgi.procname_append); if (amount >= max_procname) return; strncat(uwsgi.orig_argv[0], uwsgi.procname_append, max_procname - (amount + 1)); } // if we fit into argv, only fill argv with spaces, otherwise use environ as well if (amount < uwsgi.argv_len) { max_procname = uwsgi.argv_len; } // fill with spaces... memset(uwsgi.orig_argv[0] + amount + 1, ' ', max_procname - (amount + 1)); #elif defined(__FreeBSD__) || defined(__GNU_kFreeBSD__) || defined(__NetBSD__) if (uwsgi.procname_prefix) { if (!uwsgi.procname_append) { setproctitle("-%s%s", uwsgi.procname_prefix, name); } else { setproctitle("-%s%s%s", uwsgi.procname_prefix, name, uwsgi.procname_append); } } else if (uwsgi.procname_append) { if (!uwsgi.procname_prefix) { setproctitle("-%s%s", name, uwsgi.procname_append); } else { setproctitle("-%s%s%s", uwsgi.procname_prefix, name, uwsgi.procname_append); } } else { setproctitle("-%s", name); } #endif } // this is a wrapper for fork restoring original argv pid_t uwsgi_fork(char *name) { pid_t pid = fork(); if (pid == 0) { #ifndef __CYGWIN__ if (uwsgi.never_swap) { if (mlockall(MCL_CURRENT | MCL_FUTURE)) { uwsgi_error("mlockall()"); } } #endif #if defined(__linux__) || defined(__sun__) int i; for (i = 0; i < uwsgi.argc; i++) { // stop fixing original argv if the new one is bigger if (!uwsgi.orig_argv[i]) break; strcpy(uwsgi.orig_argv[i], uwsgi.argv[i]); } #endif if (uwsgi.auto_procname && name) { if (uwsgi.procname) { uwsgi_set_processname(uwsgi.procname); } else { uwsgi_set_processname(name); } } } return pid; } void escape_shell_arg(char *src, size_t len, char *dst) { size_t i; char *ptr = dst; for (i = 0; i < len; i++) { if (strchr("&;`'\"|*?~<>^()[]{}$\\\n", src[i])) { *ptr++ = '\\'; } *ptr++ = src[i]; } *ptr++ = 0; } void escape_json(char *src, size_t len, char *dst) { size_t i; char *ptr = dst; for (i = 0; i < len; i++) { if (src[i] == '\t') { *ptr++ = '\\'; *ptr++ = 't'; } else if (src[i] == '\n') { *ptr++ = '\\'; *ptr++ = 'n'; } else if (src[i] == '\r') { *ptr++ = '\\'; *ptr++ = 'r'; } else if (src[i] == '"') { *ptr++ = '\\'; *ptr++ = '"'; } else if (src[i] == '\\') { *ptr++ = '\\'; *ptr++ = '\\'; } else { *ptr++ = src[i]; } } *ptr++ = 0; } /* build PATH_INFO from raw_uri it manages: percent encoding dot_segments removal stop at the first # */ void http_url_decode4(char *buf, uint16_t * len, char *dst, int no_slash_decode) { enum { zero = 0, percent1, percent2, slash, dot, dotdot } status; uint16_t i, current_new_len, new_len = 0; char value[2]; char *ptr = dst; value[0] = '0'; value[1] = '0'; status = zero; int no_slash = 0; if (*len > 0 && buf[0] != '/') { status = slash; no_slash = 1; } for (i = 0; i < *len; i++) { char c = buf[i]; if (c == '#') break; switch (status) { case zero: if (c == '%') { status = percent1; break; } if (c == '/') { status = slash; break; } *ptr++ = c; new_len++; break; case percent1: if (c == '%') { *ptr++ = '%'; new_len++; status = zero; break; } value[0] = c; status = percent2; break; case percent2: value[1] = c; if (no_slash_decode && value[0] == '2' && (value[1] == 'F' || value[1] == 'f')) { *ptr++ = '%'; *ptr++ = value[0]; *ptr++ = value[1]; new_len += 3; } else { *ptr++ = hex2num(value); new_len++; } status = zero; break; case slash: if (c == '.') { status = dot; break; } // we could be at the first round (in non slash) if (i > 0 || !no_slash) { *ptr++ = '/'; new_len++; } if (c == '%') { status = percent1; break; } if (c == '/') { status = slash; break; } *ptr++ = c; new_len++; status = zero; break; case dot: if (c == '.') { status = dotdot; break; } if (c == '/') { status = slash; break; } if (i > 1) { *ptr++ = '/'; new_len++; } *ptr++ = '.'; new_len++; if (c == '%') { status = percent1; break; } *ptr++ = c; new_len++; status = zero; break; case dotdot: // here we need to remove a segment if (c == '/') { current_new_len = new_len; while (current_new_len) { current_new_len--; ptr--; if (dst[current_new_len] == '/') { break; } } new_len = current_new_len; status = slash; break; } if (i > 2) { *ptr++ = '/'; new_len++; } *ptr++ = '.'; new_len++; *ptr++ = '.'; new_len++; if (c == '%') { status = percent1; break; } *ptr++ = c; new_len++; status = zero; break; // over engineering default: *ptr++ = c; new_len++; break; } } switch (status) { case slash: case dot: *ptr++ = '/'; new_len++; break; case dotdot: current_new_len = new_len; while (current_new_len) { if (dst[current_new_len - 1] == '/') { break; } current_new_len--; } new_len = current_new_len; break; default: break; } *len = new_len; } /* we scan the table in reverse, as updated values are at the end */ char *uwsgi_get_var(struct wsgi_request *wsgi_req, char *key, uint16_t keylen, uint16_t * len) { int i; for (i = wsgi_req->var_cnt - 1; i > 0; i -= 2) { if (!uwsgi_strncmp(key, keylen, wsgi_req->hvec[i - 1].iov_base, wsgi_req->hvec[i - 1].iov_len)) { *len = wsgi_req->hvec[i].iov_len; return wsgi_req->hvec[i].iov_base; } } return NULL; } struct uwsgi_app *uwsgi_add_app(int id, uint8_t modifier1, char *mountpoint, int mountpoint_len, void *interpreter, void *callable) { if (id > uwsgi.max_apps) { uwsgi_log("FATAL ERROR: you cannot load more than %d apps in a worker\n", uwsgi.max_apps); exit(1); } struct uwsgi_app *wi = &uwsgi_apps[id]; memset(wi, 0, sizeof(struct uwsgi_app)); wi->modifier1 = modifier1; wi->mountpoint_len = mountpoint_len < 0xff ? mountpoint_len : (0xff - 1); strncpy(wi->mountpoint, mountpoint, wi->mountpoint_len); wi->interpreter = interpreter; wi->callable = callable; uwsgi_apps_cnt++; // check if we need to emulate fork() COW int i; if (uwsgi.mywid == 0) { for (i = 1; i <= uwsgi.numproc; i++) { memcpy(&uwsgi.workers[i].apps[id], &uwsgi.workers[0].apps[id], sizeof(struct uwsgi_app)); uwsgi.workers[i].apps_cnt = uwsgi_apps_cnt; } } if (!uwsgi.no_default_app) { if ((mountpoint_len == 0 || (mountpoint_len == 1 && mountpoint[0] == '/')) && uwsgi.default_app == -1) { uwsgi.default_app = id; } } return wi; } char *uwsgi_check_touches(struct uwsgi_string_list *touch_list) { // touch->value - file path // touch->custom - file timestamp // touch->custom2 - 0 if file exists, 1 if it does not exists struct uwsgi_string_list *touch = touch_list; while (touch) { struct stat tr_st; if (stat(touch->value, &tr_st)) { if (touch->custom && !touch->custom2) { #ifdef UWSGI_DEBUG uwsgi_log("[uwsgi-check-touches] File %s was removed\n", touch->value); #endif touch->custom2 = 1; return touch->custom_ptr ? touch->custom_ptr : touch->value; } else if (!touch->custom && !touch->custom2) { uwsgi_log("unable to stat() %s, events will be triggered as soon as the file is created\n", touch->value); touch->custom2 = 1; } touch->custom = 0; } else { if (!touch->custom && touch->custom2) { #ifdef UWSGI_DEBUG uwsgi_log("[uwsgi-check-touches] File was created: %s\n", touch->value); #endif touch->custom = (uint64_t) tr_st.st_mtime; touch->custom2 = 0; return touch->custom_ptr ? touch->custom_ptr : touch->value; } else if (touch->custom && (uint64_t) tr_st.st_mtime > touch->custom) { #ifdef UWSGI_DEBUG uwsgi_log("[uwsgi-check-touches] modification detected on %s: %llu -> %llu\n", touch->value, (unsigned long long) touch->custom, (unsigned long long) tr_st.st_mtime); #endif touch->custom = (uint64_t) tr_st.st_mtime; return touch->custom_ptr ? touch->custom_ptr : touch->value; } touch->custom = (uint64_t) tr_st.st_mtime; } touch = touch->next; } return NULL; } char *uwsgi_chomp(char *str) { ssize_t slen = (ssize_t) strlen(str), i; if (!slen) return str; slen--; for (i = slen; i >= 0; i--) { if (str[i] == '\r' || str[i] == '\n') { str[i] = 0; } else { return str; } } return str; } char *uwsgi_chomp2(char *str) { ssize_t slen = (ssize_t) strlen(str), i; if (!slen) return str; slen--; for (i = slen; i >= 0; i--) { if (str[i] == '\r' || str[i] == '\n' || str[i] == '\t' || str[i] == ' ') { str[i] = 0; } else { return str; } } return str; } int uwsgi_tmpfd() { int fd = -1; char *tmpdir = getenv("TMPDIR"); if (!tmpdir) { tmpdir = "/tmp"; } #ifdef O_TMPFILE fd = open(tmpdir, O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR); if (fd >= 0) { return fd; } // fallback to old style #endif char *template = uwsgi_concat2(tmpdir, "/uwsgiXXXXXX"); fd = mkstemp(template); unlink(template); free(template); return fd; } FILE *uwsgi_tmpfile() { int fd = uwsgi_tmpfd(); if (fd < 0) return NULL; return fdopen(fd, "w+"); } int uwsgi_file_to_string_list(char *filename, struct uwsgi_string_list **list) { char line[1024]; FILE *fh = fopen(filename, "r"); if (fh) { while (fgets(line, 1024, fh)) { uwsgi_string_new_list(list, uwsgi_chomp(uwsgi_str(line))); } fclose(fh); return 1; } uwsgi_error_open(filename); return 0; } void uwsgi_setup_post_buffering() { if (!uwsgi.post_buffering_bufsize) uwsgi.post_buffering_bufsize = 8192; if (uwsgi.post_buffering_bufsize < uwsgi.post_buffering) { uwsgi.post_buffering_bufsize = uwsgi.post_buffering; uwsgi_log("setting request body buffering size to %lu bytes\n", (unsigned long) uwsgi.post_buffering_bufsize); } } void uwsgi_emulate_cow_for_apps(int id) { int i; // check if we need to emulate fork() COW if (uwsgi.mywid == 0) { for (i = 1; i <= uwsgi.numproc; i++) { memcpy(&uwsgi.workers[i].apps[id], &uwsgi.workers[0].apps[id], sizeof(struct uwsgi_app)); uwsgi.workers[i].apps_cnt = uwsgi_apps_cnt; } } } int uwsgi_write_intfile(char *filename, int n) { FILE *pidfile = fopen(filename, "w"); if (!pidfile) { uwsgi_error_open(filename); exit(1); } if (fprintf(pidfile, "%d\n", n) <= 0 || ferror(pidfile)) { fclose(pidfile); return -1; } if (fclose(pidfile)) { return -1; } return 0; } void uwsgi_write_pidfile(char *pidfile_name) { uwsgi_log("writing pidfile to %s\n", pidfile_name); if (uwsgi_write_intfile(pidfile_name, (int) getpid())) { uwsgi_log("could not write pidfile.\n"); } } void uwsgi_write_pidfile_explicit(char *pidfile_name, pid_t pid) { uwsgi_log("writing pidfile to %s\n", pidfile_name); if (uwsgi_write_intfile(pidfile_name, (int) pid)) { uwsgi_log("could not write pidfile.\n"); } } char *uwsgi_expand_path(char *dir, int dir_len, char *ptr) { if (dir_len > PATH_MAX) { uwsgi_log("invalid path size: %d (max %d)\n", dir_len, PATH_MAX); return NULL; } char *src = uwsgi_concat2n(dir, dir_len, "", 0); char *dst = ptr; if (!dst) dst = uwsgi_malloc(PATH_MAX + 1); if (!realpath(src, dst)) { uwsgi_error_realpath(src); if (!ptr) free(dst); free(src); return NULL; } free(src); return dst; } void uwsgi_set_cpu_affinity() { char buf[4096]; int ret; int pos = 0; if (uwsgi.cpu_affinity) { int base_cpu = (uwsgi.mywid - 1) * uwsgi.cpu_affinity; if (base_cpu >= uwsgi.cpus) { base_cpu = base_cpu % uwsgi.cpus; } ret = snprintf(buf, 4096, "mapping worker %d to CPUs:", uwsgi.mywid); if (ret < 25 || ret >= 4096) { uwsgi_log("unable to initialize cpu affinity !!!\n"); exit(1); } pos += ret; #if defined(__linux__) || defined(__GNU_kFreeBSD__) cpu_set_t cpuset; #elif defined(__FreeBSD__) cpuset_t cpuset; #endif #if defined(__linux__) || defined(__FreeBSD__) || defined(__GNU_kFreeBSD__) CPU_ZERO(&cpuset); int i; for (i = 0; i < uwsgi.cpu_affinity; i++) { if (base_cpu >= uwsgi.cpus) base_cpu = 0; CPU_SET(base_cpu, &cpuset); ret = snprintf(buf + pos, 4096 - pos, " %d", base_cpu); if (ret < 2 || ret >= 4096) { uwsgi_log("unable to initialize cpu affinity !!!\n"); exit(1); } pos += ret; base_cpu++; } #endif #if defined(__linux__) || defined(__GNU_kFreeBSD__) if (sched_setaffinity(0, sizeof(cpu_set_t), &cpuset)) { uwsgi_error("sched_setaffinity()"); } #elif defined(__FreeBSD__) if (cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1, sizeof(cpuset), &cpuset)) { uwsgi_error("cpuset_setaffinity"); } #endif uwsgi_log("%s\n", buf); } } #ifdef UWSGI_ELF #if defined(__linux__) #include <elf.h> #endif char *uwsgi_elf_section(char *filename, char *s, size_t * len) { struct stat st; char *output = NULL; int fd = open(filename, O_RDONLY); if (fd < 0) { uwsgi_error_open(filename); return NULL; } if (fstat(fd, &st)) { uwsgi_error("stat()"); close(fd); return NULL; } if (st.st_size < EI_NIDENT) { uwsgi_log("invalid elf file: %s\n", filename); close(fd); return NULL; } char *addr = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (addr == MAP_FAILED) { uwsgi_error("mmap()"); close(fd); return NULL; } if (addr[0] != ELFMAG0) goto clear; if (addr[1] != ELFMAG1) goto clear; if (addr[2] != ELFMAG2) goto clear; if (addr[3] != ELFMAG3) goto clear; if (addr[4] == ELFCLASS32) { // elf header Elf32_Ehdr *elfh = (Elf32_Ehdr *) addr; // first section Elf32_Shdr *sections = ((Elf32_Shdr *) (addr + elfh->e_shoff)); // number of sections int ns = elfh->e_shnum; // the names table Elf32_Shdr *table = &sections[elfh->e_shstrndx]; // string table session pointer char *names = addr + table->sh_offset; Elf32_Shdr *ss = NULL; int i; for (i = 0; i < ns; i++) { char *name = names + sections[i].sh_name; if (!strcmp(name, s)) { ss = &sections[i]; break; } } if (ss) { *len = ss->sh_size; output = uwsgi_concat2n(addr + ss->sh_offset, ss->sh_size, "", 0); } } else if (addr[4] == ELFCLASS64) { // elf header Elf64_Ehdr *elfh = (Elf64_Ehdr *) addr; // first section Elf64_Shdr *sections = ((Elf64_Shdr *) (addr + elfh->e_shoff)); // number of sections int ns = elfh->e_shnum; // the names table Elf64_Shdr *table = &sections[elfh->e_shstrndx]; // string table session pointer char *names = addr + table->sh_offset; Elf64_Shdr *ss = NULL; int i; for (i = 0; i < ns; i++) { char *name = names + sections[i].sh_name; if (!strcmp(name, s)) { ss = &sections[i]; break; } } if (ss) { *len = ss->sh_size; output = uwsgi_concat2n(addr + ss->sh_offset, ss->sh_size, "", 0); } } clear: close(fd); munmap(addr, st.st_size); return output; } #endif static void *uwsgi_thread_run(void *arg) { struct uwsgi_thread *ut = (struct uwsgi_thread *) arg; // block all signals sigset_t smask; sigfillset(&smask); pthread_sigmask(SIG_BLOCK, &smask, NULL); ut->queue = event_queue_init(); event_queue_add_fd_read(ut->queue, ut->pipe[1]); ut->func(ut); return NULL; } struct uwsgi_thread *uwsgi_thread_new_with_data(void (*func) (struct uwsgi_thread *), void *data) { struct uwsgi_thread *ut = uwsgi_calloc(sizeof(struct uwsgi_thread)); #if defined(SOCK_SEQPACKET) && defined(__linux__) if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, ut->pipe)) { #else if (socketpair(AF_UNIX, SOCK_DGRAM, 0, ut->pipe)) { #endif free(ut); return NULL; } uwsgi_socket_nb(ut->pipe[0]); uwsgi_socket_nb(ut->pipe[1]); ut->func = func; ut->data = data; pthread_attr_init(&ut->tattr); pthread_attr_setdetachstate(&ut->tattr, PTHREAD_CREATE_DETACHED); // 512K should be enough... pthread_attr_setstacksize(&ut->tattr, 512 * 1024); if (pthread_create(&ut->tid, &ut->tattr, uwsgi_thread_run, ut)) { uwsgi_error("pthread_create()"); goto error; } return ut; error: close(ut->pipe[0]); close(ut->pipe[1]); free(ut); return NULL; } struct uwsgi_thread *uwsgi_thread_new(void (*func) (struct uwsgi_thread *)) { return uwsgi_thread_new_with_data(func, NULL); } int uwsgi_kvlist_parse(char *src, size_t len, char list_separator, int kv_separator, ...) { size_t i; va_list ap; struct uwsgi_string_list *itemlist = NULL; char *buf = uwsgi_calloc(len + 1); // ok let's start splitting the string int escaped = 0; char *base = buf; char *ptr = buf; for (i = 0; i < len; i++) { if (src[i] == list_separator && !escaped) { *ptr++ = 0; uwsgi_string_new_list(&itemlist, base); base = ptr; } else if (src[i] == '\\' && !escaped) { escaped = 1; } else if (escaped) { *ptr++ = src[i]; escaped = 0; } else { *ptr++ = src[i]; } } if (ptr > base) { uwsgi_string_new_list(&itemlist, base); } struct uwsgi_string_list *usl = itemlist; while (usl) { len = strlen(usl->value); char *item_buf = uwsgi_calloc(len + 1); base = item_buf; ptr = item_buf; escaped = 0; for (i = 0; i < len; i++) { if (usl->value[i] == kv_separator && !escaped) { *ptr++ = 0; va_start(ap, kv_separator); for (;;) { char *p = va_arg(ap, char *); if (!p) break; char **pp = va_arg(ap, char **); if (!pp) break; if (!strcmp(p, base)) { *pp = uwsgi_str(usl->value + i + 1); } } va_end(ap); break; } else if (usl->value[i] == '\\' && !escaped) { escaped = 1; } else if (escaped) { escaped = 0; } else { *ptr++ = usl->value[i]; } } free(item_buf); usl = usl->next; } // destroy the list (no need to destroy the value as it is a pointer to buf) usl = itemlist; while (usl) { struct uwsgi_string_list *tmp_usl = usl; usl = usl->next; free(tmp_usl); } free(buf); return 0; } int uwsgi_send_http_stats(int fd) { char buf[4096]; int ret = uwsgi_waitfd(fd, uwsgi.socket_timeout); if (ret <= 0) return -1; if (read(fd, buf, 4096) <= 0) return -1; struct uwsgi_buffer *ub = uwsgi_buffer_new(uwsgi.page_size); if (!ub) return -1; if (uwsgi_buffer_append(ub, "HTTP/1.0 200 OK\r\n", 17)) goto error; if (uwsgi_buffer_append(ub, "Connection: close\r\n", 19)) goto error; if (uwsgi_buffer_append(ub, "Access-Control-Allow-Origin: *\r\n", 32)) goto error; if (uwsgi_buffer_append(ub, "Content-Type: application/json\r\n", 32)) goto error; if (uwsgi_buffer_append(ub, "\r\n", 2)) goto error; if (uwsgi_buffer_send(ub, fd)) goto error; uwsgi_buffer_destroy(ub); return 0; error: uwsgi_buffer_destroy(ub); return -1; } int uwsgi_call_symbol(char *symbol) { void (*func) (void) = dlsym(RTLD_DEFAULT, symbol); if (!func) return -1; func(); return 0; } int uwsgi_plugin_modifier1(char *plugin) { int ret = -1; char *symbol_name = uwsgi_concat2(plugin, "_plugin"); struct uwsgi_plugin *up = dlsym(RTLD_DEFAULT, symbol_name); if (!up) goto end; ret = up->modifier1; end: free(symbol_name); return ret; } char *uwsgi_strip(char *src) { char *dst = src; size_t len = strlen(src); int i; for (i = 0; i < (ssize_t) len; i++) { if (src[i] == ' ' || src[i] == '\t') { dst++; } } len -= (dst - src); for (i = len; i >= 0; i--) { if (dst[i] == ' ' || dst[i] == '\t') { dst[i] = 0; } else { break; } } return dst; } void uwsgi_uuid(char *buf) { #ifdef UWSGI_UUID uuid_t uuid_value; uuid_generate(uuid_value); uuid_unparse(uuid_value, buf); #else int i, r[11]; if (!uwsgi_file_exists("/dev/urandom")) goto fallback; int fd = open("/dev/urandom", O_RDONLY); if (fd < 0) goto fallback; for (i = 0; i < 11; i++) { if (read(fd, &r[i], 4) != 4) { close(fd); goto fallback; } } close(fd); goto done; fallback: for (i = 0; i < 11; i++) { r[i] = rand(); } done: snprintf(buf, 37, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10]); #endif } int uwsgi_uuid_cmp(char *x, char *y) { int i; for (i = 0; i < 36; i++) { if (x[i] != y[i]) { if (x[i] > y[i]) { return 1; } return 0; } } return 0; } void uwsgi_additional_header_add(struct wsgi_request *wsgi_req, char *hh, uint16_t hh_len) { // will be freed on request's end char *header = uwsgi_concat2n(hh, hh_len, "", 0); uwsgi_string_new_list(&wsgi_req->additional_headers, header); } void uwsgi_remove_header(struct wsgi_request *wsgi_req, char *hh, uint16_t hh_len) { char *header = uwsgi_concat2n(hh, hh_len, "", 0); uwsgi_string_new_list(&wsgi_req->remove_headers, header); } // based on nginx implementation static uint8_t b64_table64[] = { 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 62, 77, 77, 77, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 77, 77, 77, 77, 77, 77, 77, 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, 77, 77, 77, 77, 77, 77, 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, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77 }; static char b64_table64_2[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; char *uwsgi_base64_decode(char *buf, size_t len, size_t * d_len) { // find the real size and check for invalid values size_t i; for (i = 0; i < len; i++) { if (buf[i] == '=') break; // check for invalid content if (b64_table64[(uint8_t) buf[i]] == 77) { return NULL; } } // check for invalid size if (i % 4 == 1) return NULL; // compute the new size *d_len = (((len + 3) / 4) * 3); char *dst = uwsgi_malloc(*d_len + 1); char *ptr = dst; uint8_t *src = (uint8_t *) buf; while (i > 3) { *ptr++ = (char) (b64_table64[src[0]] << 2 | b64_table64[src[1]] >> 4); *ptr++ = (char) (b64_table64[src[1]] << 4 | b64_table64[src[2]] >> 2); *ptr++ = (char) (b64_table64[src[2]] << 6 | b64_table64[src[3]]); src += 4; i -= 4; } if (i > 1) { *ptr++ = (char) (b64_table64[src[0]] << 2 | b64_table64[src[1]] >> 4); } if (i > 2) { *ptr++ = (char) (b64_table64[src[1]] << 4 | b64_table64[src[2]] >> 2); } *d_len = (ptr - dst); *ptr++ = 0; return dst; } char *uwsgi_base64_encode(char *buf, size_t len, size_t * d_len) { *d_len = ((len * 4) / 3) + 5; uint8_t *src = (uint8_t *) buf; char *dst = uwsgi_malloc(*d_len); char *ptr = dst; while (len >= 3) { *ptr++ = b64_table64_2[src[0] >> 2]; *ptr++ = b64_table64_2[((src[0] << 4) & 0x30) | (src[1] >> 4)]; *ptr++ = b64_table64_2[((src[1] << 2) & 0x3C) | (src[2] >> 6)]; *ptr++ = b64_table64_2[src[2] & 0x3F]; src += 3; len -= 3; } if (len > 0) { *ptr++ = b64_table64_2[src[0] >> 2]; uint8_t tmp = (src[0] << 4) & 0x30; if (len > 1) tmp |= src[1] >> 4; *ptr++ = b64_table64_2[tmp]; if (len < 2) { *ptr++ = '='; } else { *ptr++ = b64_table64_2[(src[1] << 2) & 0x3C]; } *ptr++ = '='; } *ptr = 0; *d_len = ((char *) ptr - dst); return dst; } uint16_t uwsgi_be16(char *buf) { uint16_t *src = (uint16_t *) buf; uint16_t ret = 0; uint8_t *ptr = (uint8_t *) & ret; ptr[0] = (uint8_t) ((*src >> 8) & 0xff); ptr[1] = (uint8_t) (*src & 0xff); return ret; } uint32_t uwsgi_be32(char *buf) { uint32_t *src = (uint32_t *) buf; uint32_t ret = 0; uint8_t *ptr = (uint8_t *) & ret; ptr[0] = (uint8_t) ((*src >> 24) & 0xff); ptr[1] = (uint8_t) ((*src >> 16) & 0xff); ptr[2] = (uint8_t) ((*src >> 8) & 0xff); ptr[3] = (uint8_t) (*src & 0xff); return ret; } uint64_t uwsgi_be64(char *buf) { uint64_t *src = (uint64_t *) buf; uint64_t ret = 0; uint8_t *ptr = (uint8_t *) & ret; ptr[0] = (uint8_t) ((*src >> 56) & 0xff); ptr[1] = (uint8_t) ((*src >> 48) & 0xff); ptr[2] = (uint8_t) ((*src >> 40) & 0xff); ptr[3] = (uint8_t) ((*src >> 32) & 0xff); ptr[4] = (uint8_t) ((*src >> 24) & 0xff); ptr[5] = (uint8_t) ((*src >> 16) & 0xff); ptr[6] = (uint8_t) ((*src >> 8) & 0xff); ptr[7] = (uint8_t) (*src & 0xff); return ret; } char *uwsgi_get_header(struct wsgi_request *wsgi_req, char *hh, uint16_t len, uint16_t * rlen) { char *key = uwsgi_malloc(len + 6); uint16_t key_len = len; char *ptr = key; *rlen = 0; if (uwsgi_strncmp(hh, len, "Content-Length", 14) && uwsgi_strncmp(hh, len, "Content-Type", 12)) { memcpy(ptr, "HTTP_", 5); ptr += 5; key_len += 5; } uint16_t i; for (i = 0; i < len; i++) { if (hh[i] == '-') { *ptr++ = '_'; } else { *ptr++ = toupper((int) hh[i]); } } char *value = uwsgi_get_var(wsgi_req, key, key_len, rlen); free(key); return value; } static char *uwsgi_hex_table[] = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF", }; char *uwsgi_str_to_hex(char *src, size_t slen) { char *dst = uwsgi_malloc(slen * 2); char *ptr = dst; size_t i; for (i = 0; i < slen; i++) { uint8_t pos = (uint8_t) src[i]; memcpy(ptr, uwsgi_hex_table[pos], 2); ptr += 2; } return dst; } // dst has to be 3 times buf size (USE IT ONLY FOR PATH_INFO !!!) void http_url_encode(char *buf, uint16_t * len, char *dst) { uint16_t i; char *ptr = dst; for (i = 0; i < *len; i++) { if ((buf[i] >= 'A' && buf[i] <= 'Z') || (buf[i] >= 'a' && buf[i] <= 'z') || (buf[i] >= '0' && buf[i] <= '9') || buf[i] == '-' || buf[i] == '_' || buf[i] == '.' || buf[i] == '~' || buf[i] == '/') { *ptr++ = buf[i]; } else { char *h = uwsgi_hex_table[(int) buf[i]]; *ptr++ = '%'; *ptr++ = h[0]; *ptr++ = h[1]; } } *len = ptr - dst; } void uwsgi_takeover() { if (uwsgi.i_am_a_spooler) { uwsgi_spooler_run(); } else if (uwsgi.muleid) { uwsgi_mule_run(); } else { uwsgi_worker_run(); } } // create a message pipe void create_msg_pipe(int *fd, int bufsize) { #if defined(SOCK_SEQPACKET) && defined(__linux__) if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fd)) { #else if (socketpair(AF_UNIX, SOCK_DGRAM, 0, fd)) { #endif uwsgi_error("create_msg_pipe()/socketpair()"); exit(1); } uwsgi_socket_nb(fd[0]); uwsgi_socket_nb(fd[1]); if (bufsize) { if (setsockopt(fd[0], SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(int))) { uwsgi_error("create_msg_pipe()/setsockopt()"); } if (setsockopt(fd[0], SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(int))) { uwsgi_error("create_msg_pipe()/setsockopt()"); } if (setsockopt(fd[1], SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(int))) { uwsgi_error("create_msg_pipe()/setsockopt()"); } if (setsockopt(fd[1], SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(int))) { uwsgi_error("create_msg_pipe()/setsockopt()"); } } } char *uwsgi_binary_path() { return uwsgi.binary_path ? uwsgi.binary_path : "uwsgi"; } void uwsgi_envdir(char *edir) { DIR *d = opendir(edir); if (!d) { uwsgi_error("[uwsgi-envdir] opendir()"); exit(1); } struct dirent *de; while ((de = readdir(d)) != NULL) { // skip hidden files if (de->d_name[0] == '.') continue; struct stat st; char *filename = uwsgi_concat3(edir, "/", de->d_name); if (stat(filename, &st)) { uwsgi_log("[uwsgi-envdir] error stating %s\n", filename); uwsgi_error("[uwsgi-envdir] stat()"); exit(1); } if (!S_ISREG(st.st_mode)) { free(filename); continue; } // unsetenv if (st.st_size == 0) { #ifdef UNSETENV_VOID unsetenv(de->d_name); #else if (unsetenv(de->d_name)) { uwsgi_log("[uwsgi-envdir] unable to unset %s\n", de->d_name); uwsgi_error("[uwsgi-envdir] unsetenv"); exit(1); } #endif free(filename); continue; } // read the content of the file size_t size = 0; char *content = uwsgi_open_and_read(filename, &size, 1, NULL); if (!content) { uwsgi_log("[uwsgi-envdir] unable to open %s\n", filename); uwsgi_error_open(filename); exit(1); } free(filename); // HACK, envdir states we only need to strip the end of the string .... uwsgi_chomp2(content); // ... and substitute 0 with \n size_t slen = strlen(content); size_t i; for (i = 0; i < slen; i++) { if (content[i] == 0) { content[i] = '\n'; } } if (setenv(de->d_name, content, 1)) { uwsgi_log("[uwsgi-envdir] unable to set %s\n", de->d_name); uwsgi_error("[uwsgi-envdir] setenv"); exit(1); } free(content); } closedir(d); } void uwsgi_envdirs(struct uwsgi_string_list *envdirs) { struct uwsgi_string_list *usl = envdirs; while (usl) { uwsgi_envdir(usl->value); usl = usl->next; } } void uwsgi_opt_envdir(char *opt, char *value, void *foobar) { uwsgi_envdir(value); } void uwsgi_exit(int status) { uwsgi.last_exit_code = status; // disable macro expansion (exit) (status); } int uwsgi_base128(struct uwsgi_buffer *ub, uint64_t l, int first) { if (l > 127) { if (uwsgi_base128(ub, l / 128, 0)) return -1; } l %= 128; if (first) { if (uwsgi_buffer_u8(ub, (uint8_t) l)) return -1; } else { if (uwsgi_buffer_u8(ub, 0x80 | (uint8_t) l)) return -1; } return 0; } #ifdef __linux__ void uwsgi_setns(char *path) { int (*u_setns) (int, int) = (int (*)(int, int)) dlsym(RTLD_DEFAULT, "setns"); if (!u_setns) { uwsgi_log("your system misses setns() syscall !!!\n"); exit(1); } // count be overwritten int count = 64; uwsgi_log("joining namespaces from %s ...\n", path); for (;;) { int ns_fd = uwsgi_connect(path, 30, 0); if (ns_fd < 0) { uwsgi_error("uwsgi_setns()/uwsgi_connect()"); sleep(1); continue; } int *fds = uwsgi_attach_fd(ns_fd, &count, "uwsgi-setns", 11); if (fds && count > 0) { int i; for (i = 0; i < count; i++) { if (fds[i] > -1) { if (u_setns(fds[i], 0) < 0) { uwsgi_error("uwsgi_setns()/setns()"); exit(1); } close(fds[i]); } } free(fds); close(ns_fd); break; } if (fds) free(fds); close(ns_fd); sleep(1); } } #endif mode_t uwsgi_mode_t(char *value, int *error) { mode_t mode = 0; *error = 0; if (strlen(value) < 3) { *error = 1; return mode; } if (strlen(value) == 3) { mode = (mode << 3) + (value[0] - '0'); mode = (mode << 3) + (value[1] - '0'); mode = (mode << 3) + (value[2] - '0'); } else { mode = (mode << 3) + (value[1] - '0'); mode = (mode << 3) + (value[2] - '0'); mode = (mode << 3) + (value[3] - '0'); } return mode; } int uwsgi_wait_for_socket(char *socket_name) { if (!uwsgi.wait_for_socket_timeout) { uwsgi.wait_for_socket_timeout = 60; } uwsgi_log("waiting for %s (max %d seconds) ...\n", socket_name, uwsgi.wait_for_socket_timeout); int counter = 0; for (;;) { if (counter > uwsgi.wait_for_socket_timeout) { uwsgi_log("%s unavailable after %d seconds\n", socket_name, counter); return -1; } // wait for 1 second to respect uwsgi.wait_for_fs_timeout int fd = uwsgi_connect(socket_name, 1, 0); if (fd < 0) goto retry; close(fd); uwsgi_log_verbose("%s ready\n", socket_name); return 0; retry: sleep(1); counter++; } return -1; } int uwsgi_wait_for_mountpoint(char *mountpoint) { if (!uwsgi.wait_for_fs_timeout) { uwsgi.wait_for_fs_timeout = 60; } uwsgi_log("waiting for %s (max %d seconds) ...\n", mountpoint, uwsgi.wait_for_fs_timeout); int counter = 0; for (;;) { if (counter > uwsgi.wait_for_fs_timeout) { uwsgi_log("%s unavailable after %d seconds\n", mountpoint, counter); return -1; } struct stat st0; struct stat st1; if (stat(mountpoint, &st0)) goto retry; if (!S_ISDIR(st0.st_mode)) goto retry; char *relative = uwsgi_concat2(mountpoint, "/../"); if (stat(relative, &st1)) { free(relative); goto retry; } free(relative); // useless :P if (!S_ISDIR(st1.st_mode)) goto retry; if (st0.st_dev == st1.st_dev) goto retry; uwsgi_log_verbose("%s mounted\n", mountpoint); return 0; retry: sleep(1); counter++; } return -1; } // type -> 1 file, 2 dir, 0 both int uwsgi_wait_for_fs(char *filename, int type) { if (!uwsgi.wait_for_fs_timeout) { uwsgi.wait_for_fs_timeout = 60; } uwsgi_log("waiting for %s (max %d seconds) ...\n", filename, uwsgi.wait_for_fs_timeout); int counter = 0; for (;;) { if (counter > uwsgi.wait_for_fs_timeout) { uwsgi_log("%s unavailable after %d seconds\n", filename, counter); return -1; } struct stat st; if (stat(filename, &st)) goto retry; if (type == 1 && !S_ISREG(st.st_mode)) goto retry; if (type == 2 && !S_ISDIR(st.st_mode)) goto retry; uwsgi_log_verbose("%s found\n", filename); return 0; retry: sleep(1); counter++; } return -1; } #if !defined(_GNU_SOURCE) && !defined(__UCLIBC__) int uwsgi_versionsort(const struct dirent **da, const struct dirent **db) { const char *a = (*da)->d_name; const char *b = (*db)->d_name; long la, lb; char *endptr; // Check if a and b are valid numbers. la = strtol(a, &endptr, 10); if (strcmp(endptr, "\0") || endptr == a) { a = NULL; } lb = strtol(b, &endptr, 10); if (strcmp(endptr, "\0") || endptr == b) { b = NULL; } if (a && b) { return (la < lb ? -1 : la > lb); } else if (a) { return -1; } else if (b) { return 1; } else { return strcmp((*da)->d_name, (*db)->d_name); } } #endif void uwsgi_fix_range_for_size(enum uwsgi_range* parsed, int64_t* from, int64_t* to, int64_t size) { if (*parsed != UWSGI_RANGE_PARSED) { return; } if (*from < 0) { *from = size + *from; } if (*to > size-1) { *to = size-1; } if (*from == 0 && *to == size-1) { /* we have a right to reset to 200 OK answer */ *parsed = UWSGI_RANGE_NOT_PARSED; } else if (*to >= *from) { *parsed = UWSGI_RANGE_VALID; } else { /* case *from > size-1 is also handled here */ *parsed = UWSGI_RANGE_INVALID; *from = 0; *to = 0; } }
./CrossVul/dataset_final_sorted/CWE-119/c/good_614_0
crossvul-cpp_data_good_3020_0
/* * Copyright (c) 2014-2015 Hisilicon Limited. * * 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. */ #include <linux/delay.h> #include <linux/of_mdio.h> #include "hns_dsaf_main.h" #include "hns_dsaf_mac.h" #include "hns_dsaf_gmac.h" static const struct mac_stats_string g_gmac_stats_string[] = { {"gmac_rx_octets_total_ok", MAC_STATS_FIELD_OFF(rx_good_bytes)}, {"gmac_rx_octets_bad", MAC_STATS_FIELD_OFF(rx_bad_bytes)}, {"gmac_rx_uc_pkts", MAC_STATS_FIELD_OFF(rx_uc_pkts)}, {"gmac_rx_mc_pkts", MAC_STATS_FIELD_OFF(rx_mc_pkts)}, {"gmac_rx_bc_pkts", MAC_STATS_FIELD_OFF(rx_bc_pkts)}, {"gmac_rx_pkts_64octets", MAC_STATS_FIELD_OFF(rx_64bytes)}, {"gmac_rx_pkts_65to127", MAC_STATS_FIELD_OFF(rx_65to127)}, {"gmac_rx_pkts_128to255", MAC_STATS_FIELD_OFF(rx_128to255)}, {"gmac_rx_pkts_256to511", MAC_STATS_FIELD_OFF(rx_256to511)}, {"gmac_rx_pkts_512to1023", MAC_STATS_FIELD_OFF(rx_512to1023)}, {"gmac_rx_pkts_1024to1518", MAC_STATS_FIELD_OFF(rx_1024to1518)}, {"gmac_rx_pkts_1519tomax", MAC_STATS_FIELD_OFF(rx_1519tomax)}, {"gmac_rx_fcs_errors", MAC_STATS_FIELD_OFF(rx_fcs_err)}, {"gmac_rx_tagged", MAC_STATS_FIELD_OFF(rx_vlan_pkts)}, {"gmac_rx_data_err", MAC_STATS_FIELD_OFF(rx_data_err)}, {"gmac_rx_align_errors", MAC_STATS_FIELD_OFF(rx_align_err)}, {"gmac_rx_long_errors", MAC_STATS_FIELD_OFF(rx_oversize)}, {"gmac_rx_jabber_errors", MAC_STATS_FIELD_OFF(rx_jabber_err)}, {"gmac_rx_pause_maccontrol", MAC_STATS_FIELD_OFF(rx_pfc_tc0)}, {"gmac_rx_unknown_maccontrol", MAC_STATS_FIELD_OFF(rx_unknown_ctrl)}, {"gmac_rx_very_long_err", MAC_STATS_FIELD_OFF(rx_long_err)}, {"gmac_rx_runt_err", MAC_STATS_FIELD_OFF(rx_minto64)}, {"gmac_rx_short_err", MAC_STATS_FIELD_OFF(rx_under_min)}, {"gmac_rx_filt_pkt", MAC_STATS_FIELD_OFF(rx_filter_pkts)}, {"gmac_rx_octets_total_filt", MAC_STATS_FIELD_OFF(rx_filter_bytes)}, {"gmac_rx_overrun_cnt", MAC_STATS_FIELD_OFF(rx_fifo_overrun_err)}, {"gmac_rx_length_err", MAC_STATS_FIELD_OFF(rx_len_err)}, {"gmac_rx_fail_comma", MAC_STATS_FIELD_OFF(rx_comma_err)}, {"gmac_tx_octets_ok", MAC_STATS_FIELD_OFF(tx_good_bytes)}, {"gmac_tx_octets_bad", MAC_STATS_FIELD_OFF(tx_bad_bytes)}, {"gmac_tx_uc_pkts", MAC_STATS_FIELD_OFF(tx_uc_pkts)}, {"gmac_tx_mc_pkts", MAC_STATS_FIELD_OFF(tx_mc_pkts)}, {"gmac_tx_bc_pkts", MAC_STATS_FIELD_OFF(tx_bc_pkts)}, {"gmac_tx_pkts_64octets", MAC_STATS_FIELD_OFF(tx_64bytes)}, {"gmac_tx_pkts_65to127", MAC_STATS_FIELD_OFF(tx_65to127)}, {"gmac_tx_pkts_128to255", MAC_STATS_FIELD_OFF(tx_128to255)}, {"gmac_tx_pkts_256to511", MAC_STATS_FIELD_OFF(tx_256to511)}, {"gmac_tx_pkts_512to1023", MAC_STATS_FIELD_OFF(tx_512to1023)}, {"gmac_tx_pkts_1024to1518", MAC_STATS_FIELD_OFF(tx_1024to1518)}, {"gmac_tx_pkts_1519tomax", MAC_STATS_FIELD_OFF(tx_1519tomax)}, {"gmac_tx_excessive_length_drop", MAC_STATS_FIELD_OFF(tx_jabber_err)}, {"gmac_tx_underrun", MAC_STATS_FIELD_OFF(tx_underrun_err)}, {"gmac_tx_tagged", MAC_STATS_FIELD_OFF(tx_vlan)}, {"gmac_tx_crc_error", MAC_STATS_FIELD_OFF(tx_crc_err)}, {"gmac_tx_pause_frames", MAC_STATS_FIELD_OFF(tx_pfc_tc0)} }; static void hns_gmac_enable(void *mac_drv, enum mac_commom_mode mode) { struct mac_driver *drv = (struct mac_driver *)mac_drv; /*enable GE rX/tX */ if ((mode == MAC_COMM_MODE_TX) || (mode == MAC_COMM_MODE_RX_AND_TX)) dsaf_set_dev_bit(drv, GMAC_PORT_EN_REG, GMAC_PORT_TX_EN_B, 1); if ((mode == MAC_COMM_MODE_RX) || (mode == MAC_COMM_MODE_RX_AND_TX)) dsaf_set_dev_bit(drv, GMAC_PORT_EN_REG, GMAC_PORT_RX_EN_B, 1); } static void hns_gmac_disable(void *mac_drv, enum mac_commom_mode mode) { struct mac_driver *drv = (struct mac_driver *)mac_drv; /*disable GE rX/tX */ if ((mode == MAC_COMM_MODE_TX) || (mode == MAC_COMM_MODE_RX_AND_TX)) dsaf_set_dev_bit(drv, GMAC_PORT_EN_REG, GMAC_PORT_TX_EN_B, 0); if ((mode == MAC_COMM_MODE_RX) || (mode == MAC_COMM_MODE_RX_AND_TX)) dsaf_set_dev_bit(drv, GMAC_PORT_EN_REG, GMAC_PORT_RX_EN_B, 0); } /* hns_gmac_get_en - get port enable * @mac_drv:mac device * @rx:rx enable * @tx:tx enable */ static void hns_gmac_get_en(void *mac_drv, u32 *rx, u32 *tx) { struct mac_driver *drv = (struct mac_driver *)mac_drv; u32 porten; porten = dsaf_read_dev(drv, GMAC_PORT_EN_REG); *tx = dsaf_get_bit(porten, GMAC_PORT_TX_EN_B); *rx = dsaf_get_bit(porten, GMAC_PORT_RX_EN_B); } static void hns_gmac_free(void *mac_drv) { struct mac_driver *drv = (struct mac_driver *)mac_drv; struct dsaf_device *dsaf_dev = (struct dsaf_device *)dev_get_drvdata(drv->dev); u32 mac_id = drv->mac_id; dsaf_dev->misc_op->ge_srst(dsaf_dev, mac_id, 0); } static void hns_gmac_set_tx_auto_pause_frames(void *mac_drv, u16 newval) { struct mac_driver *drv = (struct mac_driver *)mac_drv; dsaf_set_dev_field(drv, GMAC_FC_TX_TIMER_REG, GMAC_FC_TX_TIMER_M, GMAC_FC_TX_TIMER_S, newval); } static void hns_gmac_get_tx_auto_pause_frames(void *mac_drv, u16 *newval) { struct mac_driver *drv = (struct mac_driver *)mac_drv; *newval = dsaf_get_dev_field(drv, GMAC_FC_TX_TIMER_REG, GMAC_FC_TX_TIMER_M, GMAC_FC_TX_TIMER_S); } static void hns_gmac_set_rx_auto_pause_frames(void *mac_drv, u32 newval) { struct mac_driver *drv = (struct mac_driver *)mac_drv; dsaf_set_dev_bit(drv, GMAC_PAUSE_EN_REG, GMAC_PAUSE_EN_RX_FDFC_B, !!newval); } static void hns_gmac_config_max_frame_length(void *mac_drv, u16 newval) { struct mac_driver *drv = (struct mac_driver *)mac_drv; dsaf_set_dev_field(drv, GMAC_MAX_FRM_SIZE_REG, GMAC_MAX_FRM_SIZE_M, GMAC_MAX_FRM_SIZE_S, newval); dsaf_set_dev_field(drv, GAMC_RX_MAX_FRAME, GMAC_MAX_FRM_SIZE_M, GMAC_MAX_FRM_SIZE_S, newval); } static void hns_gmac_config_pad_and_crc(void *mac_drv, u8 newval) { u32 tx_ctrl; struct mac_driver *drv = (struct mac_driver *)mac_drv; tx_ctrl = dsaf_read_dev(drv, GMAC_TRANSMIT_CONTROL_REG); dsaf_set_bit(tx_ctrl, GMAC_TX_PAD_EN_B, !!newval); dsaf_set_bit(tx_ctrl, GMAC_TX_CRC_ADD_B, !!newval); dsaf_write_dev(drv, GMAC_TRANSMIT_CONTROL_REG, tx_ctrl); } static void hns_gmac_config_an_mode(void *mac_drv, u8 newval) { struct mac_driver *drv = (struct mac_driver *)mac_drv; dsaf_set_dev_bit(drv, GMAC_TRANSMIT_CONTROL_REG, GMAC_TX_AN_EN_B, !!newval); } static void hns_gmac_tx_loop_pkt_dis(void *mac_drv) { u32 tx_loop_pkt_pri; struct mac_driver *drv = (struct mac_driver *)mac_drv; tx_loop_pkt_pri = dsaf_read_dev(drv, GMAC_TX_LOOP_PKT_PRI_REG); dsaf_set_bit(tx_loop_pkt_pri, GMAC_TX_LOOP_PKT_EN_B, 1); dsaf_set_bit(tx_loop_pkt_pri, GMAC_TX_LOOP_PKT_HIG_PRI_B, 0); dsaf_write_dev(drv, GMAC_TX_LOOP_PKT_PRI_REG, tx_loop_pkt_pri); } static void hns_gmac_set_duplex_type(void *mac_drv, u8 newval) { struct mac_driver *drv = (struct mac_driver *)mac_drv; dsaf_set_dev_bit(drv, GMAC_DUPLEX_TYPE_REG, GMAC_DUPLEX_TYPE_B, !!newval); } static void hns_gmac_get_duplex_type(void *mac_drv, enum hns_gmac_duplex_mdoe *duplex_mode) { struct mac_driver *drv = (struct mac_driver *)mac_drv; *duplex_mode = (enum hns_gmac_duplex_mdoe)dsaf_get_dev_bit( drv, GMAC_DUPLEX_TYPE_REG, GMAC_DUPLEX_TYPE_B); } static void hns_gmac_get_port_mode(void *mac_drv, enum hns_port_mode *port_mode) { struct mac_driver *drv = (struct mac_driver *)mac_drv; *port_mode = (enum hns_port_mode)dsaf_get_dev_field( drv, GMAC_PORT_MODE_REG, GMAC_PORT_MODE_M, GMAC_PORT_MODE_S); } static void hns_gmac_port_mode_get(void *mac_drv, struct hns_gmac_port_mode_cfg *port_mode) { u32 tx_ctrl; u32 recv_ctrl; struct mac_driver *drv = (struct mac_driver *)mac_drv; port_mode->port_mode = (enum hns_port_mode)dsaf_get_dev_field( drv, GMAC_PORT_MODE_REG, GMAC_PORT_MODE_M, GMAC_PORT_MODE_S); tx_ctrl = dsaf_read_dev(drv, GMAC_TRANSMIT_CONTROL_REG); recv_ctrl = dsaf_read_dev(drv, GMAC_RECV_CONTROL_REG); port_mode->max_frm_size = dsaf_get_dev_field(drv, GMAC_MAX_FRM_SIZE_REG, GMAC_MAX_FRM_SIZE_M, GMAC_MAX_FRM_SIZE_S); port_mode->short_runts_thr = dsaf_get_dev_field(drv, GMAC_SHORT_RUNTS_THR_REG, GMAC_SHORT_RUNTS_THR_M, GMAC_SHORT_RUNTS_THR_S); port_mode->pad_enable = dsaf_get_bit(tx_ctrl, GMAC_TX_PAD_EN_B); port_mode->crc_add = dsaf_get_bit(tx_ctrl, GMAC_TX_CRC_ADD_B); port_mode->an_enable = dsaf_get_bit(tx_ctrl, GMAC_TX_AN_EN_B); port_mode->runt_pkt_en = dsaf_get_bit(recv_ctrl, GMAC_RECV_CTRL_RUNT_PKT_EN_B); port_mode->strip_pad_en = dsaf_get_bit(recv_ctrl, GMAC_RECV_CTRL_STRIP_PAD_EN_B); } static void hns_gmac_pause_frm_cfg(void *mac_drv, u32 rx_pause_en, u32 tx_pause_en) { u32 pause_en; struct mac_driver *drv = (struct mac_driver *)mac_drv; pause_en = dsaf_read_dev(drv, GMAC_PAUSE_EN_REG); dsaf_set_bit(pause_en, GMAC_PAUSE_EN_RX_FDFC_B, !!rx_pause_en); dsaf_set_bit(pause_en, GMAC_PAUSE_EN_TX_FDFC_B, !!tx_pause_en); dsaf_write_dev(drv, GMAC_PAUSE_EN_REG, pause_en); } static void hns_gmac_get_pausefrm_cfg(void *mac_drv, u32 *rx_pause_en, u32 *tx_pause_en) { u32 pause_en; struct mac_driver *drv = (struct mac_driver *)mac_drv; pause_en = dsaf_read_dev(drv, GMAC_PAUSE_EN_REG); *rx_pause_en = dsaf_get_bit(pause_en, GMAC_PAUSE_EN_RX_FDFC_B); *tx_pause_en = dsaf_get_bit(pause_en, GMAC_PAUSE_EN_TX_FDFC_B); } static int hns_gmac_adjust_link(void *mac_drv, enum mac_speed speed, u32 full_duplex) { struct mac_driver *drv = (struct mac_driver *)mac_drv; dsaf_set_dev_bit(drv, GMAC_DUPLEX_TYPE_REG, GMAC_DUPLEX_TYPE_B, !!full_duplex); switch (speed) { case MAC_SPEED_10: dsaf_set_dev_field( drv, GMAC_PORT_MODE_REG, GMAC_PORT_MODE_M, GMAC_PORT_MODE_S, 0x6); break; case MAC_SPEED_100: dsaf_set_dev_field( drv, GMAC_PORT_MODE_REG, GMAC_PORT_MODE_M, GMAC_PORT_MODE_S, 0x7); break; case MAC_SPEED_1000: dsaf_set_dev_field( drv, GMAC_PORT_MODE_REG, GMAC_PORT_MODE_M, GMAC_PORT_MODE_S, 0x8); break; default: dev_err(drv->dev, "hns_gmac_adjust_link fail, speed%d mac%d\n", speed, drv->mac_id); return -EINVAL; } return 0; } static void hns_gmac_set_uc_match(void *mac_drv, u16 en) { struct mac_driver *drv = mac_drv; dsaf_set_dev_bit(drv, GMAC_REC_FILT_CONTROL_REG, GMAC_UC_MATCH_EN_B, !en); dsaf_set_dev_bit(drv, GMAC_STATION_ADDR_HIGH_2_REG, GMAC_ADDR_EN_B, !en); } static void hns_gmac_set_promisc(void *mac_drv, u8 en) { struct mac_driver *drv = mac_drv; if (drv->mac_cb->mac_type == HNAE_PORT_DEBUG) hns_gmac_set_uc_match(mac_drv, en); } static void hns_gmac_init(void *mac_drv) { u32 port; struct mac_driver *drv = (struct mac_driver *)mac_drv; struct dsaf_device *dsaf_dev = (struct dsaf_device *)dev_get_drvdata(drv->dev); port = drv->mac_id; dsaf_dev->misc_op->ge_srst(dsaf_dev, port, 0); mdelay(10); dsaf_dev->misc_op->ge_srst(dsaf_dev, port, 1); mdelay(10); hns_gmac_disable(mac_drv, MAC_COMM_MODE_RX_AND_TX); hns_gmac_tx_loop_pkt_dis(mac_drv); if (drv->mac_cb->mac_type == HNAE_PORT_DEBUG) hns_gmac_set_uc_match(mac_drv, 0); hns_gmac_config_pad_and_crc(mac_drv, 1); dsaf_set_dev_bit(drv, GMAC_MODE_CHANGE_EN_REG, GMAC_MODE_CHANGE_EB_B, 1); /* reduce gmac tx water line to avoid gmac hang-up * in speed 100M and duplex half. */ dsaf_set_dev_field(drv, GMAC_TX_WATER_LINE_REG, GMAC_TX_WATER_LINE_MASK, GMAC_TX_WATER_LINE_SHIFT, 8); } void hns_gmac_update_stats(void *mac_drv) { struct mac_hw_stats *hw_stats = NULL; struct mac_driver *drv = (struct mac_driver *)mac_drv; hw_stats = &drv->mac_cb->hw_stats; /* RX */ hw_stats->rx_good_bytes += dsaf_read_dev(drv, GMAC_RX_OCTETS_TOTAL_OK_REG); hw_stats->rx_bad_bytes += dsaf_read_dev(drv, GMAC_RX_OCTETS_BAD_REG); hw_stats->rx_uc_pkts += dsaf_read_dev(drv, GMAC_RX_UC_PKTS_REG); hw_stats->rx_mc_pkts += dsaf_read_dev(drv, GMAC_RX_MC_PKTS_REG); hw_stats->rx_bc_pkts += dsaf_read_dev(drv, GMAC_RX_BC_PKTS_REG); hw_stats->rx_64bytes += dsaf_read_dev(drv, GMAC_RX_PKTS_64OCTETS_REG); hw_stats->rx_65to127 += dsaf_read_dev(drv, GMAC_RX_PKTS_65TO127OCTETS_REG); hw_stats->rx_128to255 += dsaf_read_dev(drv, GMAC_RX_PKTS_128TO255OCTETS_REG); hw_stats->rx_256to511 += dsaf_read_dev(drv, GMAC_RX_PKTS_255TO511OCTETS_REG); hw_stats->rx_512to1023 += dsaf_read_dev(drv, GMAC_RX_PKTS_512TO1023OCTETS_REG); hw_stats->rx_1024to1518 += dsaf_read_dev(drv, GMAC_RX_PKTS_1024TO1518OCTETS_REG); hw_stats->rx_1519tomax += dsaf_read_dev(drv, GMAC_RX_PKTS_1519TOMAXOCTETS_REG); hw_stats->rx_fcs_err += dsaf_read_dev(drv, GMAC_RX_FCS_ERRORS_REG); hw_stats->rx_vlan_pkts += dsaf_read_dev(drv, GMAC_RX_TAGGED_REG); hw_stats->rx_data_err += dsaf_read_dev(drv, GMAC_RX_DATA_ERR_REG); hw_stats->rx_align_err += dsaf_read_dev(drv, GMAC_RX_ALIGN_ERRORS_REG); hw_stats->rx_oversize += dsaf_read_dev(drv, GMAC_RX_LONG_ERRORS_REG); hw_stats->rx_jabber_err += dsaf_read_dev(drv, GMAC_RX_JABBER_ERRORS_REG); hw_stats->rx_pfc_tc0 += dsaf_read_dev(drv, GMAC_RX_PAUSE_MACCTRL_FRAM_REG); hw_stats->rx_unknown_ctrl += dsaf_read_dev(drv, GMAC_RX_UNKNOWN_MACCTRL_FRAM_REG); hw_stats->rx_long_err += dsaf_read_dev(drv, GMAC_RX_VERY_LONG_ERR_CNT_REG); hw_stats->rx_minto64 += dsaf_read_dev(drv, GMAC_RX_RUNT_ERR_CNT_REG); hw_stats->rx_under_min += dsaf_read_dev(drv, GMAC_RX_SHORT_ERR_CNT_REG); hw_stats->rx_filter_pkts += dsaf_read_dev(drv, GMAC_RX_FILT_PKT_CNT_REG); hw_stats->rx_filter_bytes += dsaf_read_dev(drv, GMAC_RX_OCTETS_TOTAL_FILT_REG); hw_stats->rx_fifo_overrun_err += dsaf_read_dev(drv, GMAC_RX_OVERRUN_CNT_REG); hw_stats->rx_len_err += dsaf_read_dev(drv, GMAC_RX_LENGTHFIELD_ERR_CNT_REG); hw_stats->rx_comma_err += dsaf_read_dev(drv, GMAC_RX_FAIL_COMMA_CNT_REG); /* TX */ hw_stats->tx_good_bytes += dsaf_read_dev(drv, GMAC_OCTETS_TRANSMITTED_OK_REG); hw_stats->tx_bad_bytes += dsaf_read_dev(drv, GMAC_OCTETS_TRANSMITTED_BAD_REG); hw_stats->tx_uc_pkts += dsaf_read_dev(drv, GMAC_TX_UC_PKTS_REG); hw_stats->tx_mc_pkts += dsaf_read_dev(drv, GMAC_TX_MC_PKTS_REG); hw_stats->tx_bc_pkts += dsaf_read_dev(drv, GMAC_TX_BC_PKTS_REG); hw_stats->tx_64bytes += dsaf_read_dev(drv, GMAC_TX_PKTS_64OCTETS_REG); hw_stats->tx_65to127 += dsaf_read_dev(drv, GMAC_TX_PKTS_65TO127OCTETS_REG); hw_stats->tx_128to255 += dsaf_read_dev(drv, GMAC_TX_PKTS_128TO255OCTETS_REG); hw_stats->tx_256to511 += dsaf_read_dev(drv, GMAC_TX_PKTS_255TO511OCTETS_REG); hw_stats->tx_512to1023 += dsaf_read_dev(drv, GMAC_TX_PKTS_512TO1023OCTETS_REG); hw_stats->tx_1024to1518 += dsaf_read_dev(drv, GMAC_TX_PKTS_1024TO1518OCTETS_REG); hw_stats->tx_1519tomax += dsaf_read_dev(drv, GMAC_TX_PKTS_1519TOMAXOCTETS_REG); hw_stats->tx_jabber_err += dsaf_read_dev(drv, GMAC_TX_EXCESSIVE_LENGTH_DROP_REG); hw_stats->tx_underrun_err += dsaf_read_dev(drv, GMAC_TX_UNDERRUN_REG); hw_stats->tx_vlan += dsaf_read_dev(drv, GMAC_TX_TAGGED_REG); hw_stats->tx_crc_err += dsaf_read_dev(drv, GMAC_TX_CRC_ERROR_REG); hw_stats->tx_pfc_tc0 += dsaf_read_dev(drv, GMAC_TX_PAUSE_FRAMES_REG); } static void hns_gmac_set_mac_addr(void *mac_drv, char *mac_addr) { struct mac_driver *drv = (struct mac_driver *)mac_drv; u32 high_val = mac_addr[1] | (mac_addr[0] << 8); u32 low_val = mac_addr[5] | (mac_addr[4] << 8) | (mac_addr[3] << 16) | (mac_addr[2] << 24); u32 val = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_2_REG); u32 sta_addr_en = dsaf_get_bit(val, GMAC_ADDR_EN_B); dsaf_write_dev(drv, GMAC_STATION_ADDR_LOW_2_REG, low_val); dsaf_write_dev(drv, GMAC_STATION_ADDR_HIGH_2_REG, high_val | (sta_addr_en << GMAC_ADDR_EN_B)); } static int hns_gmac_config_loopback(void *mac_drv, enum hnae_loop loop_mode, u8 enable) { struct mac_driver *drv = (struct mac_driver *)mac_drv; switch (loop_mode) { case MAC_INTERNALLOOP_MAC: dsaf_set_dev_bit(drv, GMAC_LOOP_REG, GMAC_LP_REG_CF2MI_LP_EN_B, !!enable); break; default: dev_err(drv->dev, "loop_mode error\n"); return -EINVAL; } return 0; } static void hns_gmac_get_info(void *mac_drv, struct mac_info *mac_info) { enum hns_gmac_duplex_mdoe duplex; enum hns_port_mode speed; u32 rx_pause; u32 tx_pause; u32 rx; u32 tx; u16 fc_tx_timer; struct hns_gmac_port_mode_cfg port_mode = { GMAC_10M_MII, 0 }; hns_gmac_port_mode_get(mac_drv, &port_mode); mac_info->pad_and_crc_en = port_mode.crc_add && port_mode.pad_enable; mac_info->auto_neg = port_mode.an_enable; hns_gmac_get_tx_auto_pause_frames(mac_drv, &fc_tx_timer); mac_info->tx_pause_time = fc_tx_timer; hns_gmac_get_en(mac_drv, &rx, &tx); mac_info->port_en = rx && tx; hns_gmac_get_duplex_type(mac_drv, &duplex); mac_info->duplex = duplex; hns_gmac_get_port_mode(mac_drv, &speed); switch (speed) { case GMAC_10M_SGMII: mac_info->speed = MAC_SPEED_10; break; case GMAC_100M_SGMII: mac_info->speed = MAC_SPEED_100; break; case GMAC_1000M_SGMII: mac_info->speed = MAC_SPEED_1000; break; default: mac_info->speed = 0; break; } hns_gmac_get_pausefrm_cfg(mac_drv, &rx_pause, &tx_pause); mac_info->rx_pause_en = rx_pause; mac_info->tx_pause_en = tx_pause; } static void hns_gmac_autoneg_stat(void *mac_drv, u32 *enable) { struct mac_driver *drv = (struct mac_driver *)mac_drv; *enable = dsaf_get_dev_bit(drv, GMAC_TRANSMIT_CONTROL_REG, GMAC_TX_AN_EN_B); } static void hns_gmac_get_link_status(void *mac_drv, u32 *link_stat) { struct mac_driver *drv = (struct mac_driver *)mac_drv; *link_stat = dsaf_get_dev_bit(drv, GMAC_AN_NEG_STATE_REG, GMAC_AN_NEG_STAT_RX_SYNC_OK_B); } static void hns_gmac_get_regs(void *mac_drv, void *data) { u32 *regs = data; int i; struct mac_driver *drv = (struct mac_driver *)mac_drv; /* base config registers */ regs[0] = dsaf_read_dev(drv, GMAC_DUPLEX_TYPE_REG); regs[1] = dsaf_read_dev(drv, GMAC_FD_FC_TYPE_REG); regs[2] = dsaf_read_dev(drv, GMAC_FC_TX_TIMER_REG); regs[3] = dsaf_read_dev(drv, GMAC_FD_FC_ADDR_LOW_REG); regs[4] = dsaf_read_dev(drv, GMAC_FD_FC_ADDR_HIGH_REG); regs[5] = dsaf_read_dev(drv, GMAC_IPG_TX_TIMER_REG); regs[6] = dsaf_read_dev(drv, GMAC_PAUSE_THR_REG); regs[7] = dsaf_read_dev(drv, GMAC_MAX_FRM_SIZE_REG); regs[8] = dsaf_read_dev(drv, GMAC_PORT_MODE_REG); regs[9] = dsaf_read_dev(drv, GMAC_PORT_EN_REG); regs[10] = dsaf_read_dev(drv, GMAC_PAUSE_EN_REG); regs[11] = dsaf_read_dev(drv, GMAC_SHORT_RUNTS_THR_REG); regs[12] = dsaf_read_dev(drv, GMAC_AN_NEG_STATE_REG); regs[13] = dsaf_read_dev(drv, GMAC_TX_LOCAL_PAGE_REG); regs[14] = dsaf_read_dev(drv, GMAC_TRANSMIT_CONTROL_REG); regs[15] = dsaf_read_dev(drv, GMAC_REC_FILT_CONTROL_REG); regs[16] = dsaf_read_dev(drv, GMAC_PTP_CONFIG_REG); /* rx static registers */ regs[17] = dsaf_read_dev(drv, GMAC_RX_OCTETS_TOTAL_OK_REG); regs[18] = dsaf_read_dev(drv, GMAC_RX_OCTETS_BAD_REG); regs[19] = dsaf_read_dev(drv, GMAC_RX_UC_PKTS_REG); regs[20] = dsaf_read_dev(drv, GMAC_RX_MC_PKTS_REG); regs[21] = dsaf_read_dev(drv, GMAC_RX_BC_PKTS_REG); regs[22] = dsaf_read_dev(drv, GMAC_RX_PKTS_64OCTETS_REG); regs[23] = dsaf_read_dev(drv, GMAC_RX_PKTS_65TO127OCTETS_REG); regs[24] = dsaf_read_dev(drv, GMAC_RX_PKTS_128TO255OCTETS_REG); regs[25] = dsaf_read_dev(drv, GMAC_RX_PKTS_255TO511OCTETS_REG); regs[26] = dsaf_read_dev(drv, GMAC_RX_PKTS_512TO1023OCTETS_REG); regs[27] = dsaf_read_dev(drv, GMAC_RX_PKTS_1024TO1518OCTETS_REG); regs[28] = dsaf_read_dev(drv, GMAC_RX_PKTS_1519TOMAXOCTETS_REG); regs[29] = dsaf_read_dev(drv, GMAC_RX_FCS_ERRORS_REG); regs[30] = dsaf_read_dev(drv, GMAC_RX_TAGGED_REG); regs[31] = dsaf_read_dev(drv, GMAC_RX_DATA_ERR_REG); regs[32] = dsaf_read_dev(drv, GMAC_RX_ALIGN_ERRORS_REG); regs[33] = dsaf_read_dev(drv, GMAC_RX_LONG_ERRORS_REG); regs[34] = dsaf_read_dev(drv, GMAC_RX_JABBER_ERRORS_REG); regs[35] = dsaf_read_dev(drv, GMAC_RX_PAUSE_MACCTRL_FRAM_REG); regs[36] = dsaf_read_dev(drv, GMAC_RX_UNKNOWN_MACCTRL_FRAM_REG); regs[37] = dsaf_read_dev(drv, GMAC_RX_VERY_LONG_ERR_CNT_REG); regs[38] = dsaf_read_dev(drv, GMAC_RX_RUNT_ERR_CNT_REG); regs[39] = dsaf_read_dev(drv, GMAC_RX_SHORT_ERR_CNT_REG); regs[40] = dsaf_read_dev(drv, GMAC_RX_FILT_PKT_CNT_REG); regs[41] = dsaf_read_dev(drv, GMAC_RX_OCTETS_TOTAL_FILT_REG); /* tx static registers */ regs[42] = dsaf_read_dev(drv, GMAC_OCTETS_TRANSMITTED_OK_REG); regs[43] = dsaf_read_dev(drv, GMAC_OCTETS_TRANSMITTED_BAD_REG); regs[44] = dsaf_read_dev(drv, GMAC_TX_UC_PKTS_REG); regs[45] = dsaf_read_dev(drv, GMAC_TX_MC_PKTS_REG); regs[46] = dsaf_read_dev(drv, GMAC_TX_BC_PKTS_REG); regs[47] = dsaf_read_dev(drv, GMAC_TX_PKTS_64OCTETS_REG); regs[48] = dsaf_read_dev(drv, GMAC_TX_PKTS_65TO127OCTETS_REG); regs[49] = dsaf_read_dev(drv, GMAC_TX_PKTS_128TO255OCTETS_REG); regs[50] = dsaf_read_dev(drv, GMAC_TX_PKTS_255TO511OCTETS_REG); regs[51] = dsaf_read_dev(drv, GMAC_TX_PKTS_512TO1023OCTETS_REG); regs[52] = dsaf_read_dev(drv, GMAC_TX_PKTS_1024TO1518OCTETS_REG); regs[53] = dsaf_read_dev(drv, GMAC_TX_PKTS_1519TOMAXOCTETS_REG); regs[54] = dsaf_read_dev(drv, GMAC_TX_EXCESSIVE_LENGTH_DROP_REG); regs[55] = dsaf_read_dev(drv, GMAC_TX_UNDERRUN_REG); regs[56] = dsaf_read_dev(drv, GMAC_TX_TAGGED_REG); regs[57] = dsaf_read_dev(drv, GMAC_TX_CRC_ERROR_REG); regs[58] = dsaf_read_dev(drv, GMAC_TX_PAUSE_FRAMES_REG); regs[59] = dsaf_read_dev(drv, GAMC_RX_MAX_FRAME); regs[60] = dsaf_read_dev(drv, GMAC_LINE_LOOP_BACK_REG); regs[61] = dsaf_read_dev(drv, GMAC_CF_CRC_STRIP_REG); regs[62] = dsaf_read_dev(drv, GMAC_MODE_CHANGE_EN_REG); regs[63] = dsaf_read_dev(drv, GMAC_SIXTEEN_BIT_CNTR_REG); regs[64] = dsaf_read_dev(drv, GMAC_LD_LINK_COUNTER_REG); regs[65] = dsaf_read_dev(drv, GMAC_LOOP_REG); regs[66] = dsaf_read_dev(drv, GMAC_RECV_CONTROL_REG); regs[67] = dsaf_read_dev(drv, GMAC_VLAN_CODE_REG); regs[68] = dsaf_read_dev(drv, GMAC_RX_OVERRUN_CNT_REG); regs[69] = dsaf_read_dev(drv, GMAC_RX_LENGTHFIELD_ERR_CNT_REG); regs[70] = dsaf_read_dev(drv, GMAC_RX_FAIL_COMMA_CNT_REG); regs[71] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_0_REG); regs[72] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_0_REG); regs[73] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_1_REG); regs[74] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_1_REG); regs[75] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_2_REG); regs[76] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_2_REG); regs[77] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_3_REG); regs[78] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_3_REG); regs[79] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_4_REG); regs[80] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_4_REG); regs[81] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_5_REG); regs[82] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_5_REG); regs[83] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_MSK_0_REG); regs[84] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_MSK_0_REG); regs[85] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_MSK_1_REG); regs[86] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_MSK_1_REG); regs[87] = dsaf_read_dev(drv, GMAC_MAC_SKIP_LEN_REG); regs[88] = dsaf_read_dev(drv, GMAC_TX_LOOP_PKT_PRI_REG); /* mark end of mac regs */ for (i = 89; i < 96; i++) regs[i] = 0xaaaaaaaa; } static void hns_gmac_get_stats(void *mac_drv, u64 *data) { u32 i; u64 *buf = data; struct mac_driver *drv = (struct mac_driver *)mac_drv; struct mac_hw_stats *hw_stats = NULL; hw_stats = &drv->mac_cb->hw_stats; for (i = 0; i < ARRAY_SIZE(g_gmac_stats_string); i++) { buf[i] = DSAF_STATS_READ(hw_stats, g_gmac_stats_string[i].offset); } } static void hns_gmac_get_strings(u32 stringset, u8 *data) { char *buff = (char *)data; u32 i; if (stringset != ETH_SS_STATS) return; for (i = 0; i < ARRAY_SIZE(g_gmac_stats_string); i++) { snprintf(buff, ETH_GSTRING_LEN, "%s", g_gmac_stats_string[i].desc); buff = buff + ETH_GSTRING_LEN; } } static int hns_gmac_get_sset_count(int stringset) { if (stringset == ETH_SS_STATS || stringset == ETH_SS_PRIV_FLAGS) return ARRAY_SIZE(g_gmac_stats_string); return 0; } static int hns_gmac_get_regs_count(void) { return ETH_GMAC_DUMP_NUM; } void *hns_gmac_config(struct hns_mac_cb *mac_cb, struct mac_params *mac_param) { struct mac_driver *mac_drv; mac_drv = devm_kzalloc(mac_cb->dev, sizeof(*mac_drv), GFP_KERNEL); if (!mac_drv) return NULL; mac_drv->mac_init = hns_gmac_init; mac_drv->mac_enable = hns_gmac_enable; mac_drv->mac_disable = hns_gmac_disable; mac_drv->mac_free = hns_gmac_free; mac_drv->adjust_link = hns_gmac_adjust_link; mac_drv->set_tx_auto_pause_frames = hns_gmac_set_tx_auto_pause_frames; mac_drv->config_max_frame_length = hns_gmac_config_max_frame_length; mac_drv->mac_pausefrm_cfg = hns_gmac_pause_frm_cfg; mac_drv->mac_id = mac_param->mac_id; mac_drv->mac_mode = mac_param->mac_mode; mac_drv->io_base = mac_param->vaddr; mac_drv->dev = mac_param->dev; mac_drv->mac_cb = mac_cb; mac_drv->set_mac_addr = hns_gmac_set_mac_addr; mac_drv->set_an_mode = hns_gmac_config_an_mode; mac_drv->config_loopback = hns_gmac_config_loopback; mac_drv->config_pad_and_crc = hns_gmac_config_pad_and_crc; mac_drv->config_half_duplex = hns_gmac_set_duplex_type; mac_drv->set_rx_ignore_pause_frames = hns_gmac_set_rx_auto_pause_frames; mac_drv->get_info = hns_gmac_get_info; mac_drv->autoneg_stat = hns_gmac_autoneg_stat; mac_drv->get_pause_enable = hns_gmac_get_pausefrm_cfg; mac_drv->get_link_status = hns_gmac_get_link_status; mac_drv->get_regs = hns_gmac_get_regs; mac_drv->get_regs_count = hns_gmac_get_regs_count; mac_drv->get_ethtool_stats = hns_gmac_get_stats; mac_drv->get_sset_count = hns_gmac_get_sset_count; mac_drv->get_strings = hns_gmac_get_strings; mac_drv->update_stats = hns_gmac_update_stats; mac_drv->set_promiscuous = hns_gmac_set_promisc; return (void *)mac_drv; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_3020_0
crossvul-cpp_data_bad_634_2
/********************************************************************* * * This is based on code created by Peter Harvey, * (pharvey@codebydesign.com). * * Modified and extended by Nick Gorham * (nick@lurcher.org). * * Any bugs or problems should be considered the fault of Nick and not * Peter. * * copyright (c) 1999 Nick Gorham * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ********************************************************************** * * $Id: SQLSetDescField.c,v 1.7 2009/02/18 17:59:08 lurcher Exp $ * * $Log: SQLSetDescField.c,v $ * Revision 1.7 2009/02/18 17:59:08 lurcher * Shift to using config.h, the compile lines were making it hard to spot warnings * * Revision 1.6 2007/05/25 16:42:32 lurcher * Sync up * * Revision 1.5 2005/11/21 17:25:43 lurcher * A few DM fixes for Oracle's ODBC driver * * Revision 1.4 2003/10/30 18:20:46 lurcher * * Fix broken thread protection * Remove SQLNumResultCols after execute, lease S4/S% to driver * Fix string overrun in SQLDriverConnect * Add initial support for Interix * * Revision 1.3 2003/02/27 12:19:40 lurcher * * Add the A functions as well as the W * * Revision 1.2 2002/12/05 17:44:31 lurcher * * Display unknown return values in return logging * * Revision 1.1.1.1 2001/10/17 16:40:07 lurcher * * First upload to SourceForge * * Revision 1.4 2001/07/03 09:30:41 nick * * Add ability to alter size of displayed message in the log * * Revision 1.3 2001/04/17 16:29:39 nick * * More checks and autotest fixes * * Revision 1.2 2001/04/12 17:43:36 nick * * Change logging and added autotest to odbctest * * Revision 1.1.1.1 2000/09/04 16:42:52 nick * Imported Sources * * Revision 1.7 1999/11/13 23:41:00 ngorham * * Alter the way DM logging works * Upgrade the Postgres driver to 6.4.6 * * Revision 1.6 1999/10/24 23:54:19 ngorham * * First part of the changes to the error reporting * * Revision 1.5 1999/09/21 22:34:25 ngorham * * Improve performance by removing unneeded logging calls when logging is * disabled * * Revision 1.4 1999/07/10 21:10:17 ngorham * * Adjust error sqlstate from driver manager, depending on requested * version (ODBC2/3) * * Revision 1.3 1999/07/04 21:05:08 ngorham * * Add LGPL Headers to code * * Revision 1.2 1999/06/30 23:56:55 ngorham * * Add initial thread safety code * * Revision 1.1.1.1 1999/05/29 13:41:08 sShandyb * first go at it * * Revision 1.1.1.1 1999/05/27 18:23:18 pharvey * Imported sources * * Revision 1.2 1999/05/04 22:41:12 nick * and another night ends * * Revision 1.1 1999/04/25 23:06:11 nick * Initial revision * * **********************************************************************/ #include <config.h> #include "drivermanager.h" static char const rcsid[]= "$RCSfile: SQLSetDescField.c,v $ $Revision: 1.7 $"; SQLRETURN SQLSetDescFieldA( SQLHDESC descriptor_handle, SQLSMALLINT rec_number, SQLSMALLINT field_identifier, SQLPOINTER value, SQLINTEGER buffer_length ) { return SQLSetDescField( descriptor_handle, rec_number, field_identifier, value, buffer_length ); } SQLRETURN SQLSetDescField( SQLHDESC descriptor_handle, SQLSMALLINT rec_number, SQLSMALLINT field_identifier, SQLPOINTER value, SQLINTEGER buffer_length ) { /* * not quite sure how the descriptor can be * allocated to a statement, all the documentation talks * about state transitions on statement states, but the * descriptor may be allocated with more than one statement * at one time. Which one should I check ? */ DMHDESC descriptor = (DMHDESC) descriptor_handle; SQLRETURN ret; SQLCHAR s1[ 100 + LOG_MESSAGE_LEN ]; int isStrField = 0; /* * check descriptor */ if ( !__validate_desc( descriptor )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: SQL_INVALID_HANDLE" ); return SQL_INVALID_HANDLE; } function_entry( descriptor ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tEntry:\ \n\t\t\tDescriptor = %p\ \n\t\t\tRec Number = %d\ \n\t\t\tField Ident = %s\ \n\t\t\tValue = %p\ \n\t\t\tBuffer Length = %d", descriptor, rec_number, __desc_attr_as_string( s1, field_identifier ), value, (int)buffer_length ); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } thread_protect( SQL_HANDLE_DESC, descriptor ); if ( descriptor -> connection -> state < STATE_C4 ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * check status of statements associated with this descriptor */ if( __check_stmt_from_desc( descriptor, STATE_S8 ) || __check_stmt_from_desc( descriptor, STATE_S9 ) || __check_stmt_from_desc( descriptor, STATE_S10 ) || __check_stmt_from_desc( descriptor, STATE_S11 ) || __check_stmt_from_desc( descriptor, STATE_S12 ) || __check_stmt_from_desc( descriptor, STATE_S13 ) || __check_stmt_from_desc( descriptor, STATE_S14 ) || __check_stmt_from_desc( descriptor, STATE_S15 )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( rec_number < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } switch ( field_identifier ) { /* Fixed-length fields: buffer_length is ignored */ case SQL_DESC_ALLOC_TYPE: case SQL_DESC_ARRAY_SIZE: case SQL_DESC_ARRAY_STATUS_PTR: case SQL_DESC_BIND_OFFSET_PTR: case SQL_DESC_BIND_TYPE: case SQL_DESC_COUNT: case SQL_DESC_ROWS_PROCESSED_PTR: case SQL_DESC_AUTO_UNIQUE_VALUE: case SQL_DESC_CASE_SENSITIVE: case SQL_DESC_CONCISE_TYPE: case SQL_DESC_DATA_PTR: case SQL_DESC_DATETIME_INTERVAL_CODE: case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_DISPLAY_SIZE: case SQL_DESC_FIXED_PREC_SCALE: case SQL_DESC_INDICATOR_PTR: case SQL_DESC_LENGTH: case SQL_DESC_NULLABLE: case SQL_DESC_NUM_PREC_RADIX: case SQL_DESC_OCTET_LENGTH: case SQL_DESC_OCTET_LENGTH_PTR: case SQL_DESC_PARAMETER_TYPE: case SQL_DESC_PRECISION: case SQL_DESC_ROWVER: case SQL_DESC_SCALE: case SQL_DESC_SEARCHABLE: case SQL_DESC_TYPE: case SQL_DESC_UNNAMED: case SQL_DESC_UNSIGNED: case SQL_DESC_UPDATABLE: isStrField = 0; break; /* Pointer to data: buffer_length must be valid */ case SQL_DESC_BASE_COLUMN_NAME: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_CATALOG_NAME: case SQL_DESC_LABEL: case SQL_DESC_LITERAL_PREFIX: case SQL_DESC_LITERAL_SUFFIX: case SQL_DESC_LOCAL_TYPE_NAME: case SQL_DESC_NAME: case SQL_DESC_SCHEMA_NAME: case SQL_DESC_TABLE_NAME: case SQL_DESC_TYPE_NAME: isStrField = 1; break; default: isStrField = buffer_length != SQL_IS_POINTER && buffer_length != SQL_IS_INTEGER && buffer_length != SQL_IS_UINTEGER && buffer_length != SQL_IS_SMALLINT && buffer_length != SQL_IS_USMALLINT; } if ( isStrField && buffer_length < 0 && buffer_length != SQL_NTS) { __post_internal_error( &descriptor -> error, ERROR_HY090, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_COUNT && (SQLINTEGER)value < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_PARAMETER_TYPE && value != SQL_PARAM_INPUT && value != SQL_PARAM_OUTPUT && value != SQL_PARAM_INPUT_OUTPUT && value != SQL_PARAM_INPUT_OUTPUT_STREAM && value != SQL_PARAM_OUTPUT_STREAM ) { __post_internal_error( &descriptor -> error, ERROR_HY105, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( CHECK_SQLSETDESCFIELD( descriptor -> connection )) { ret = SQLSETDESCFIELD( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); } else if ( CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { SQLWCHAR *s1 = NULL; if (isStrField) { s1 = ansi_to_unicode_alloc( value, buffer_length, descriptor -> connection, NULL ); if (SQL_NTS != buffer_length) { buffer_length *= sizeof(SQLWCHAR); } } else { s1 = value; } ret = SQLSETDESCFIELDW( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, s1, buffer_length ); if (isStrField) { if (s1) free(s1); } } else { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: IM001" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tExit:[%s]", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } return function_return( SQL_HANDLE_DESC, descriptor, ret ); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_634_2
crossvul-cpp_data_good_1528_0
/* * Intel CPU microcode early update for Linux * * Copyright (C) 2012 Fenghua Yu <fenghua.yu@intel.com> * H Peter Anvin" <hpa@zytor.com> * * This allows to early upgrade microcode on Intel processors * belonging to IA-32 family - PentiumPro, Pentium II, * Pentium III, Xeon, Pentium 4, etc. * * Reference: Section 9.11 of Volume 3, IA-32 Intel Architecture * Software Developer's Manual. * * 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. */ #include <linux/module.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/earlycpio.h> #include <linux/initrd.h> #include <linux/cpu.h> #include <asm/msr.h> #include <asm/microcode_intel.h> #include <asm/processor.h> #include <asm/tlbflush.h> #include <asm/setup.h> static unsigned long mc_saved_in_initrd[MAX_UCODE_COUNT]; static struct mc_saved_data { unsigned int mc_saved_count; struct microcode_intel **mc_saved; } mc_saved_data; static enum ucode_state generic_load_microcode_early(struct microcode_intel **mc_saved_p, unsigned int mc_saved_count, struct ucode_cpu_info *uci) { struct microcode_intel *ucode_ptr, *new_mc = NULL; int new_rev = uci->cpu_sig.rev; enum ucode_state state = UCODE_OK; unsigned int mc_size; struct microcode_header_intel *mc_header; unsigned int csig = uci->cpu_sig.sig; unsigned int cpf = uci->cpu_sig.pf; int i; for (i = 0; i < mc_saved_count; i++) { ucode_ptr = mc_saved_p[i]; mc_header = (struct microcode_header_intel *)ucode_ptr; mc_size = get_totalsize(mc_header); if (get_matching_microcode(csig, cpf, ucode_ptr, new_rev)) { new_rev = mc_header->rev; new_mc = ucode_ptr; } } if (!new_mc) { state = UCODE_NFOUND; goto out; } uci->mc = (struct microcode_intel *)new_mc; out: return state; } static void microcode_pointer(struct microcode_intel **mc_saved, unsigned long *mc_saved_in_initrd, unsigned long initrd_start, int mc_saved_count) { int i; for (i = 0; i < mc_saved_count; i++) mc_saved[i] = (struct microcode_intel *) (mc_saved_in_initrd[i] + initrd_start); } #ifdef CONFIG_X86_32 static void microcode_phys(struct microcode_intel **mc_saved_tmp, struct mc_saved_data *mc_saved_data) { int i; struct microcode_intel ***mc_saved; mc_saved = (struct microcode_intel ***) __pa_nodebug(&mc_saved_data->mc_saved); for (i = 0; i < mc_saved_data->mc_saved_count; i++) { struct microcode_intel *p; p = *(struct microcode_intel **) __pa_nodebug(mc_saved_data->mc_saved + i); mc_saved_tmp[i] = (struct microcode_intel *)__pa_nodebug(p); } } #endif static enum ucode_state load_microcode(struct mc_saved_data *mc_saved_data, unsigned long *mc_saved_in_initrd, unsigned long initrd_start, struct ucode_cpu_info *uci) { struct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT]; unsigned int count = mc_saved_data->mc_saved_count; if (!mc_saved_data->mc_saved) { microcode_pointer(mc_saved_tmp, mc_saved_in_initrd, initrd_start, count); return generic_load_microcode_early(mc_saved_tmp, count, uci); } else { #ifdef CONFIG_X86_32 microcode_phys(mc_saved_tmp, mc_saved_data); return generic_load_microcode_early(mc_saved_tmp, count, uci); #else return generic_load_microcode_early(mc_saved_data->mc_saved, count, uci); #endif } } static u8 get_x86_family(unsigned long sig) { u8 x86; x86 = (sig >> 8) & 0xf; if (x86 == 0xf) x86 += (sig >> 20) & 0xff; return x86; } static u8 get_x86_model(unsigned long sig) { u8 x86, x86_model; x86 = get_x86_family(sig); x86_model = (sig >> 4) & 0xf; if (x86 == 0x6 || x86 == 0xf) x86_model += ((sig >> 16) & 0xf) << 4; return x86_model; } /* * Given CPU signature and a microcode patch, this function finds if the * microcode patch has matching family and model with the CPU. */ static enum ucode_state matching_model_microcode(struct microcode_header_intel *mc_header, unsigned long sig) { u8 x86, x86_model; u8 x86_ucode, x86_model_ucode; struct extended_sigtable *ext_header; unsigned long total_size = get_totalsize(mc_header); unsigned long data_size = get_datasize(mc_header); int ext_sigcount, i; struct extended_signature *ext_sig; x86 = get_x86_family(sig); x86_model = get_x86_model(sig); x86_ucode = get_x86_family(mc_header->sig); x86_model_ucode = get_x86_model(mc_header->sig); if (x86 == x86_ucode && x86_model == x86_model_ucode) return UCODE_OK; /* Look for ext. headers: */ if (total_size <= data_size + MC_HEADER_SIZE) return UCODE_NFOUND; ext_header = (struct extended_sigtable *) mc_header + data_size + MC_HEADER_SIZE; ext_sigcount = ext_header->count; ext_sig = (void *)ext_header + EXT_HEADER_SIZE; for (i = 0; i < ext_sigcount; i++) { x86_ucode = get_x86_family(ext_sig->sig); x86_model_ucode = get_x86_model(ext_sig->sig); if (x86 == x86_ucode && x86_model == x86_model_ucode) return UCODE_OK; ext_sig++; } return UCODE_NFOUND; } static int save_microcode(struct mc_saved_data *mc_saved_data, struct microcode_intel **mc_saved_src, unsigned int mc_saved_count) { int i, j; struct microcode_intel **mc_saved_p; int ret; if (!mc_saved_count) return -EINVAL; /* * Copy new microcode data. */ mc_saved_p = kmalloc(mc_saved_count*sizeof(struct microcode_intel *), GFP_KERNEL); if (!mc_saved_p) return -ENOMEM; for (i = 0; i < mc_saved_count; i++) { struct microcode_intel *mc = mc_saved_src[i]; struct microcode_header_intel *mc_header = &mc->hdr; unsigned long mc_size = get_totalsize(mc_header); mc_saved_p[i] = kmalloc(mc_size, GFP_KERNEL); if (!mc_saved_p[i]) { ret = -ENOMEM; goto err; } if (!mc_saved_src[i]) { ret = -EINVAL; goto err; } memcpy(mc_saved_p[i], mc, mc_size); } /* * Point to newly saved microcode. */ mc_saved_data->mc_saved = mc_saved_p; mc_saved_data->mc_saved_count = mc_saved_count; return 0; err: for (j = 0; j <= i; j++) kfree(mc_saved_p[j]); kfree(mc_saved_p); return ret; } /* * A microcode patch in ucode_ptr is saved into mc_saved * - if it has matching signature and newer revision compared to an existing * patch mc_saved. * - or if it is a newly discovered microcode patch. * * The microcode patch should have matching model with CPU. */ static void _save_mc(struct microcode_intel **mc_saved, u8 *ucode_ptr, unsigned int *mc_saved_count_p) { int i; int found = 0; unsigned int mc_saved_count = *mc_saved_count_p; struct microcode_header_intel *mc_header; mc_header = (struct microcode_header_intel *)ucode_ptr; for (i = 0; i < mc_saved_count; i++) { unsigned int sig, pf; unsigned int new_rev; struct microcode_header_intel *mc_saved_header = (struct microcode_header_intel *)mc_saved[i]; sig = mc_saved_header->sig; pf = mc_saved_header->pf; new_rev = mc_header->rev; if (get_matching_sig(sig, pf, ucode_ptr, new_rev)) { found = 1; if (update_match_revision(mc_header, new_rev)) { /* * Found an older ucode saved before. * Replace the older one with this newer * one. */ mc_saved[i] = (struct microcode_intel *)ucode_ptr; break; } } } if (i >= mc_saved_count && !found) /* * This ucode is first time discovered in ucode file. * Save it to memory. */ mc_saved[mc_saved_count++] = (struct microcode_intel *)ucode_ptr; *mc_saved_count_p = mc_saved_count; } /* * Get microcode matching with BSP's model. Only CPUs with the same model as * BSP can stay in the platform. */ static enum ucode_state __init get_matching_model_microcode(int cpu, unsigned long start, void *data, size_t size, struct mc_saved_data *mc_saved_data, unsigned long *mc_saved_in_initrd, struct ucode_cpu_info *uci) { u8 *ucode_ptr = data; unsigned int leftover = size; enum ucode_state state = UCODE_OK; unsigned int mc_size; struct microcode_header_intel *mc_header; struct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT]; unsigned int mc_saved_count = mc_saved_data->mc_saved_count; int i; while (leftover && mc_saved_count < ARRAY_SIZE(mc_saved_tmp)) { mc_header = (struct microcode_header_intel *)ucode_ptr; mc_size = get_totalsize(mc_header); if (!mc_size || mc_size > leftover || microcode_sanity_check(ucode_ptr, 0) < 0) break; leftover -= mc_size; /* * Since APs with same family and model as the BSP may boot in * the platform, we need to find and save microcode patches * with the same family and model as the BSP. */ if (matching_model_microcode(mc_header, uci->cpu_sig.sig) != UCODE_OK) { ucode_ptr += mc_size; continue; } _save_mc(mc_saved_tmp, ucode_ptr, &mc_saved_count); ucode_ptr += mc_size; } if (leftover) { state = UCODE_ERROR; goto out; } if (mc_saved_count == 0) { state = UCODE_NFOUND; goto out; } for (i = 0; i < mc_saved_count; i++) mc_saved_in_initrd[i] = (unsigned long)mc_saved_tmp[i] - start; mc_saved_data->mc_saved_count = mc_saved_count; out: return state; } static int collect_cpu_info_early(struct ucode_cpu_info *uci) { unsigned int val[2]; u8 x86, x86_model; struct cpu_signature csig; unsigned int eax, ebx, ecx, edx; csig.sig = 0; csig.pf = 0; csig.rev = 0; memset(uci, 0, sizeof(*uci)); eax = 0x00000001; ecx = 0; native_cpuid(&eax, &ebx, &ecx, &edx); csig.sig = eax; x86 = get_x86_family(csig.sig); x86_model = get_x86_model(csig.sig); if ((x86_model >= 5) || (x86 > 6)) { /* get processor flags from MSR 0x17 */ native_rdmsr(MSR_IA32_PLATFORM_ID, val[0], val[1]); csig.pf = 1 << ((val[1] >> 18) & 7); } native_wrmsr(MSR_IA32_UCODE_REV, 0, 0); /* As documented in the SDM: Do a CPUID 1 here */ sync_core(); /* get the current revision from MSR 0x8B */ native_rdmsr(MSR_IA32_UCODE_REV, val[0], val[1]); csig.rev = val[1]; uci->cpu_sig = csig; uci->valid = 1; return 0; } #ifdef DEBUG static void __ref show_saved_mc(void) { int i, j; unsigned int sig, pf, rev, total_size, data_size, date; struct ucode_cpu_info uci; if (mc_saved_data.mc_saved_count == 0) { pr_debug("no microcode data saved.\n"); return; } pr_debug("Total microcode saved: %d\n", mc_saved_data.mc_saved_count); collect_cpu_info_early(&uci); sig = uci.cpu_sig.sig; pf = uci.cpu_sig.pf; rev = uci.cpu_sig.rev; pr_debug("CPU%d: sig=0x%x, pf=0x%x, rev=0x%x\n", smp_processor_id(), sig, pf, rev); for (i = 0; i < mc_saved_data.mc_saved_count; i++) { struct microcode_header_intel *mc_saved_header; struct extended_sigtable *ext_header; int ext_sigcount; struct extended_signature *ext_sig; mc_saved_header = (struct microcode_header_intel *) mc_saved_data.mc_saved[i]; sig = mc_saved_header->sig; pf = mc_saved_header->pf; rev = mc_saved_header->rev; total_size = get_totalsize(mc_saved_header); data_size = get_datasize(mc_saved_header); date = mc_saved_header->date; pr_debug("mc_saved[%d]: sig=0x%x, pf=0x%x, rev=0x%x, toal size=0x%x, date = %04x-%02x-%02x\n", i, sig, pf, rev, total_size, date & 0xffff, date >> 24, (date >> 16) & 0xff); /* Look for ext. headers: */ if (total_size <= data_size + MC_HEADER_SIZE) continue; ext_header = (struct extended_sigtable *) mc_saved_header + data_size + MC_HEADER_SIZE; ext_sigcount = ext_header->count; ext_sig = (void *)ext_header + EXT_HEADER_SIZE; for (j = 0; j < ext_sigcount; j++) { sig = ext_sig->sig; pf = ext_sig->pf; pr_debug("\tExtended[%d]: sig=0x%x, pf=0x%x\n", j, sig, pf); ext_sig++; } } } #else static inline void show_saved_mc(void) { } #endif #if defined(CONFIG_MICROCODE_INTEL_EARLY) && defined(CONFIG_HOTPLUG_CPU) static DEFINE_MUTEX(x86_cpu_microcode_mutex); /* * Save this mc into mc_saved_data. So it will be loaded early when a CPU is * hot added or resumes. * * Please make sure this mc should be a valid microcode patch before calling * this function. */ int save_mc_for_early(u8 *mc) { struct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT]; unsigned int mc_saved_count_init; unsigned int mc_saved_count; struct microcode_intel **mc_saved; int ret = 0; int i; /* * Hold hotplug lock so mc_saved_data is not accessed by a CPU in * hotplug. */ mutex_lock(&x86_cpu_microcode_mutex); mc_saved_count_init = mc_saved_data.mc_saved_count; mc_saved_count = mc_saved_data.mc_saved_count; mc_saved = mc_saved_data.mc_saved; if (mc_saved && mc_saved_count) memcpy(mc_saved_tmp, mc_saved, mc_saved_count * sizeof(struct microcode_intel *)); /* * Save the microcode patch mc in mc_save_tmp structure if it's a newer * version. */ _save_mc(mc_saved_tmp, mc, &mc_saved_count); /* * Save the mc_save_tmp in global mc_saved_data. */ ret = save_microcode(&mc_saved_data, mc_saved_tmp, mc_saved_count); if (ret) { pr_err("Cannot save microcode patch.\n"); goto out; } show_saved_mc(); /* * Free old saved microcode data. */ if (mc_saved) { for (i = 0; i < mc_saved_count_init; i++) kfree(mc_saved[i]); kfree(mc_saved); } out: mutex_unlock(&x86_cpu_microcode_mutex); return ret; } EXPORT_SYMBOL_GPL(save_mc_for_early); #endif static __initdata char ucode_name[] = "kernel/x86/microcode/GenuineIntel.bin"; static __init enum ucode_state scan_microcode(unsigned long start, unsigned long end, struct mc_saved_data *mc_saved_data, unsigned long *mc_saved_in_initrd, struct ucode_cpu_info *uci) { unsigned int size = end - start + 1; struct cpio_data cd; long offset = 0; #ifdef CONFIG_X86_32 char *p = (char *)__pa_nodebug(ucode_name); #else char *p = ucode_name; #endif cd.data = NULL; cd.size = 0; cd = find_cpio_data(p, (void *)start, size, &offset); if (!cd.data) return UCODE_ERROR; return get_matching_model_microcode(0, start, cd.data, cd.size, mc_saved_data, mc_saved_in_initrd, uci); } /* * Print ucode update info. */ static void print_ucode_info(struct ucode_cpu_info *uci, unsigned int date) { int cpu = smp_processor_id(); pr_info("CPU%d microcode updated early to revision 0x%x, date = %04x-%02x-%02x\n", cpu, uci->cpu_sig.rev, date & 0xffff, date >> 24, (date >> 16) & 0xff); } #ifdef CONFIG_X86_32 static int delay_ucode_info; static int current_mc_date; /* * Print early updated ucode info after printk works. This is delayed info dump. */ void show_ucode_info_early(void) { struct ucode_cpu_info uci; if (delay_ucode_info) { collect_cpu_info_early(&uci); print_ucode_info(&uci, current_mc_date); delay_ucode_info = 0; } } /* * At this point, we can not call printk() yet. Keep microcode patch number in * mc_saved_data.mc_saved and delay printing microcode info in * show_ucode_info_early() until printk() works. */ static void print_ucode(struct ucode_cpu_info *uci) { struct microcode_intel *mc_intel; int *delay_ucode_info_p; int *current_mc_date_p; mc_intel = uci->mc; if (mc_intel == NULL) return; delay_ucode_info_p = (int *)__pa_nodebug(&delay_ucode_info); current_mc_date_p = (int *)__pa_nodebug(&current_mc_date); *delay_ucode_info_p = 1; *current_mc_date_p = mc_intel->hdr.date; } #else /* * Flush global tlb. We only do this in x86_64 where paging has been enabled * already and PGE should be enabled as well. */ static inline void flush_tlb_early(void) { __native_flush_tlb_global_irq_disabled(); } static inline void print_ucode(struct ucode_cpu_info *uci) { struct microcode_intel *mc_intel; mc_intel = uci->mc; if (mc_intel == NULL) return; print_ucode_info(uci, mc_intel->hdr.date); } #endif static int apply_microcode_early(struct ucode_cpu_info *uci, bool early) { struct microcode_intel *mc_intel; unsigned int val[2]; mc_intel = uci->mc; if (mc_intel == NULL) return 0; /* write microcode via MSR 0x79 */ native_wrmsr(MSR_IA32_UCODE_WRITE, (unsigned long) mc_intel->bits, (unsigned long) mc_intel->bits >> 16 >> 16); native_wrmsr(MSR_IA32_UCODE_REV, 0, 0); /* As documented in the SDM: Do a CPUID 1 here */ sync_core(); /* get the current revision from MSR 0x8B */ native_rdmsr(MSR_IA32_UCODE_REV, val[0], val[1]); if (val[1] != mc_intel->hdr.rev) return -1; #ifdef CONFIG_X86_64 /* Flush global tlb. This is precaution. */ flush_tlb_early(); #endif uci->cpu_sig.rev = val[1]; if (early) print_ucode(uci); else print_ucode_info(uci, mc_intel->hdr.date); return 0; } /* * This function converts microcode patch offsets previously stored in * mc_saved_in_initrd to pointers and stores the pointers in mc_saved_data. */ int __init save_microcode_in_initrd_intel(void) { unsigned int count = mc_saved_data.mc_saved_count; struct microcode_intel *mc_saved[MAX_UCODE_COUNT]; int ret = 0; if (count == 0) return ret; microcode_pointer(mc_saved, mc_saved_in_initrd, initrd_start, count); ret = save_microcode(&mc_saved_data, mc_saved, count); if (ret) pr_err("Cannot save microcode patches from initrd.\n"); show_saved_mc(); return ret; } static void __init _load_ucode_intel_bsp(struct mc_saved_data *mc_saved_data, unsigned long *mc_saved_in_initrd, unsigned long initrd_start_early, unsigned long initrd_end_early, struct ucode_cpu_info *uci) { enum ucode_state ret; collect_cpu_info_early(uci); scan_microcode(initrd_start_early, initrd_end_early, mc_saved_data, mc_saved_in_initrd, uci); ret = load_microcode(mc_saved_data, mc_saved_in_initrd, initrd_start_early, uci); if (ret == UCODE_OK) apply_microcode_early(uci, true); } void __init load_ucode_intel_bsp(void) { u64 ramdisk_image, ramdisk_size; unsigned long initrd_start_early, initrd_end_early; struct ucode_cpu_info uci; #ifdef CONFIG_X86_32 struct boot_params *boot_params_p; boot_params_p = (struct boot_params *)__pa_nodebug(&boot_params); ramdisk_image = boot_params_p->hdr.ramdisk_image; ramdisk_size = boot_params_p->hdr.ramdisk_size; initrd_start_early = ramdisk_image; initrd_end_early = initrd_start_early + ramdisk_size; _load_ucode_intel_bsp( (struct mc_saved_data *)__pa_nodebug(&mc_saved_data), (unsigned long *)__pa_nodebug(&mc_saved_in_initrd), initrd_start_early, initrd_end_early, &uci); #else ramdisk_image = boot_params.hdr.ramdisk_image; ramdisk_size = boot_params.hdr.ramdisk_size; initrd_start_early = ramdisk_image + PAGE_OFFSET; initrd_end_early = initrd_start_early + ramdisk_size; _load_ucode_intel_bsp(&mc_saved_data, mc_saved_in_initrd, initrd_start_early, initrd_end_early, &uci); #endif } void load_ucode_intel_ap(void) { struct mc_saved_data *mc_saved_data_p; struct ucode_cpu_info uci; unsigned long *mc_saved_in_initrd_p; unsigned long initrd_start_addr; #ifdef CONFIG_X86_32 unsigned long *initrd_start_p; mc_saved_in_initrd_p = (unsigned long *)__pa_nodebug(mc_saved_in_initrd); mc_saved_data_p = (struct mc_saved_data *)__pa_nodebug(&mc_saved_data); initrd_start_p = (unsigned long *)__pa_nodebug(&initrd_start); initrd_start_addr = (unsigned long)__pa_nodebug(*initrd_start_p); #else mc_saved_data_p = &mc_saved_data; mc_saved_in_initrd_p = mc_saved_in_initrd; initrd_start_addr = initrd_start; #endif /* * If there is no valid ucode previously saved in memory, no need to * update ucode on this AP. */ if (mc_saved_data_p->mc_saved_count == 0) return; collect_cpu_info_early(&uci); load_microcode(mc_saved_data_p, mc_saved_in_initrd_p, initrd_start_addr, &uci); apply_microcode_early(&uci, true); } void reload_ucode_intel(void) { struct ucode_cpu_info uci; enum ucode_state ret; if (!mc_saved_data.mc_saved_count) return; collect_cpu_info_early(&uci); ret = generic_load_microcode_early(mc_saved_data.mc_saved, mc_saved_data.mc_saved_count, &uci); if (ret != UCODE_OK) return; apply_microcode_early(&uci, false); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1528_0
crossvul-cpp_data_bad_2988_0
/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com * Copyright (c) 2016 Facebook * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * 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. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/bpf.h> #include <linux/bpf_verifier.h> #include <linux/filter.h> #include <net/netlink.h> #include <linux/file.h> #include <linux/vmalloc.h> #include <linux/stringify.h> #include "disasm.h" static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { #define BPF_PROG_TYPE(_id, _name) \ [_id] = & _name ## _verifier_ops, #define BPF_MAP_TYPE(_id, _ops) #include <linux/bpf_types.h> #undef BPF_PROG_TYPE #undef BPF_MAP_TYPE }; /* bpf_check() is a static code analyzer that walks eBPF program * instruction by instruction and updates register/stack state. * All paths of conditional branches are analyzed until 'bpf_exit' insn. * * The first pass is depth-first-search to check that the program is a DAG. * It rejects the following programs: * - larger than BPF_MAXINSNS insns * - if loop is present (detected via back-edge) * - unreachable insns exist (shouldn't be a forest. program = one function) * - out of bounds or malformed jumps * The second pass is all possible path descent from the 1st insn. * Since it's analyzing all pathes through the program, the length of the * analysis is limited to 64k insn, which may be hit even if total number of * insn is less then 4K, but there are too many branches that change stack/regs. * Number of 'branches to be analyzed' is limited to 1k * * On entry to each instruction, each register has a type, and the instruction * changes the types of the registers depending on instruction semantics. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is * copied to R1. * * All registers are 64-bit. * R0 - return register * R1-R5 argument passing registers * R6-R9 callee saved registers * R10 - frame pointer read-only * * At the start of BPF program the register R1 contains a pointer to bpf_context * and has type PTR_TO_CTX. * * Verifier tracks arithmetic operations on pointers in case: * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), * 1st insn copies R10 (which has FRAME_PTR) type into R1 * and 2nd arithmetic instruction is pattern matched to recognize * that it wants to construct a pointer to some element within stack. * So after 2nd insn, the register R1 has type PTR_TO_STACK * (and -20 constant is saved for further stack bounds checking). * Meaning that this reg is a pointer to stack plus known immediate constant. * * Most of the time the registers have SCALAR_VALUE type, which * means the register has some value, but it's not a valid pointer. * (like pointer plus pointer becomes SCALAR_VALUE type) * * When verifier sees load or store instructions the type of base register * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer * types recognized by check_mem_access() function. * * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' * and the range of [ptr, ptr + map's value_size) is accessible. * * registers used to pass values to function calls are checked against * function argument constraints. * * ARG_PTR_TO_MAP_KEY is one of such argument constraints. * It means that the register type passed to this function must be * PTR_TO_STACK and it will be used inside the function as * 'pointer to map element key' * * For example the argument constraints for bpf_map_lookup_elem(): * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, * .arg1_type = ARG_CONST_MAP_PTR, * .arg2_type = ARG_PTR_TO_MAP_KEY, * * ret_type says that this function returns 'pointer to map elem value or null' * function expects 1st argument to be a const pointer to 'struct bpf_map' and * 2nd argument should be a pointer to stack, which will be used inside * the helper function as a pointer to map element key. * * On the kernel side the helper function looks like: * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) * { * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; * void *key = (void *) (unsigned long) r2; * void *value; * * here kernel can access 'key' and 'map' pointers safely, knowing that * [key, key + map->key_size) bytes are valid and were initialized on * the stack of eBPF program. * } * * Corresponding eBPF program may look like: * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), * here verifier looks at prototype of map_lookup_elem() and sees: * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, * Now verifier knows that this map has key of R1->map_ptr->key_size bytes * * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, * Now verifier checks that [R2, R2 + map's key_size) are within stack limits * and were initialized prior to this call. * If it's ok, then verifier allows this BPF_CALL insn and looks at * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function * returns ether pointer to map value or NULL. * * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' * insn, the register holding that pointer in the true branch changes state to * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false * branch. See check_cond_jmp_op(). * * After the call R0 is set to return type of the function and registers R1-R5 * are set to NOT_INIT to indicate that they are no longer readable. */ /* verifier_state + insn_idx are pushed to stack when branch is encountered */ struct bpf_verifier_stack_elem { /* verifer state is 'st' * before processing instruction 'insn_idx' * and after processing instruction 'prev_insn_idx' */ struct bpf_verifier_state st; int insn_idx; int prev_insn_idx; struct bpf_verifier_stack_elem *next; }; #define BPF_COMPLEXITY_LIMIT_INSNS 131072 #define BPF_COMPLEXITY_LIMIT_STACK 1024 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA) struct bpf_call_arg_meta { struct bpf_map *map_ptr; bool raw_mode; bool pkt_access; int regno; int access_size; }; static DEFINE_MUTEX(bpf_verifier_lock); /* log_level controls verbosity level of eBPF verifier. * verbose() is used to dump the verification trace to the log, so the user * can figure out what's wrong with the program */ static __printf(2, 3) void verbose(struct bpf_verifier_env *env, const char *fmt, ...) { struct bpf_verifer_log *log = &env->log; unsigned int n; va_list args; if (!log->level || !log->ubuf || bpf_verifier_log_full(log)) return; va_start(args, fmt); n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); va_end(args); WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, "verifier log line truncated - local buffer too short\n"); n = min(log->len_total - log->len_used - 1, n); log->kbuf[n] = '\0'; if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) log->len_used += n; else log->ubuf = NULL; } static bool type_is_pkt_pointer(enum bpf_reg_type type) { return type == PTR_TO_PACKET || type == PTR_TO_PACKET_META; } /* string representation of 'enum bpf_reg_type' */ static const char * const reg_type_str[] = { [NOT_INIT] = "?", [SCALAR_VALUE] = "inv", [PTR_TO_CTX] = "ctx", [CONST_PTR_TO_MAP] = "map_ptr", [PTR_TO_MAP_VALUE] = "map_value", [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null", [PTR_TO_STACK] = "fp", [PTR_TO_PACKET] = "pkt", [PTR_TO_PACKET_META] = "pkt_meta", [PTR_TO_PACKET_END] = "pkt_end", }; static void print_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *state) { struct bpf_reg_state *reg; enum bpf_reg_type t; int i; for (i = 0; i < MAX_BPF_REG; i++) { reg = &state->regs[i]; t = reg->type; if (t == NOT_INIT) continue; verbose(env, " R%d=%s", i, reg_type_str[t]); if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && tnum_is_const(reg->var_off)) { /* reg->off should be 0 for SCALAR_VALUE */ verbose(env, "%lld", reg->var_off.value + reg->off); } else { verbose(env, "(id=%d", reg->id); if (t != SCALAR_VALUE) verbose(env, ",off=%d", reg->off); if (type_is_pkt_pointer(t)) verbose(env, ",r=%d", reg->range); else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE || t == PTR_TO_MAP_VALUE_OR_NULL) verbose(env, ",ks=%d,vs=%d", reg->map_ptr->key_size, reg->map_ptr->value_size); if (tnum_is_const(reg->var_off)) { /* Typically an immediate SCALAR_VALUE, but * could be a pointer whose offset is too big * for reg->off */ verbose(env, ",imm=%llx", reg->var_off.value); } else { if (reg->smin_value != reg->umin_value && reg->smin_value != S64_MIN) verbose(env, ",smin_value=%lld", (long long)reg->smin_value); if (reg->smax_value != reg->umax_value && reg->smax_value != S64_MAX) verbose(env, ",smax_value=%lld", (long long)reg->smax_value); if (reg->umin_value != 0) verbose(env, ",umin_value=%llu", (unsigned long long)reg->umin_value); if (reg->umax_value != U64_MAX) verbose(env, ",umax_value=%llu", (unsigned long long)reg->umax_value); if (!tnum_is_unknown(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, ",var_off=%s", tn_buf); } } verbose(env, ")"); } } for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] == STACK_SPILL) verbose(env, " fp%d=%s", -MAX_BPF_STACK + i * BPF_REG_SIZE, reg_type_str[state->stack[i].spilled_ptr.type]); } verbose(env, "\n"); } static int copy_stack_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) { if (!src->stack) return 0; if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) { /* internal bug, make state invalid to reject the program */ memset(dst, 0, sizeof(*dst)); return -EFAULT; } memcpy(dst->stack, src->stack, sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE)); return 0; } /* do_check() starts with zero-sized stack in struct bpf_verifier_state to * make it consume minimal amount of memory. check_stack_write() access from * the program calls into realloc_verifier_state() to grow the stack size. * Note there is a non-zero 'parent' pointer inside bpf_verifier_state * which this function copies over. It points to previous bpf_verifier_state * which is never reallocated */ static int realloc_verifier_state(struct bpf_verifier_state *state, int size, bool copy_old) { u32 old_size = state->allocated_stack; struct bpf_stack_state *new_stack; int slot = size / BPF_REG_SIZE; if (size <= old_size || !size) { if (copy_old) return 0; state->allocated_stack = slot * BPF_REG_SIZE; if (!size && old_size) { kfree(state->stack); state->stack = NULL; } return 0; } new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state), GFP_KERNEL); if (!new_stack) return -ENOMEM; if (copy_old) { if (state->stack) memcpy(new_stack, state->stack, sizeof(*new_stack) * (old_size / BPF_REG_SIZE)); memset(new_stack + old_size / BPF_REG_SIZE, 0, sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE); } state->allocated_stack = slot * BPF_REG_SIZE; kfree(state->stack); state->stack = new_stack; return 0; } static void free_verifier_state(struct bpf_verifier_state *state, bool free_self) { kfree(state->stack); if (free_self) kfree(state); } /* copy verifier state from src to dst growing dst stack space * when necessary to accommodate larger src stack */ static int copy_verifier_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) { int err; err = realloc_verifier_state(dst, src->allocated_stack, false); if (err) return err; memcpy(dst, src, offsetof(struct bpf_verifier_state, allocated_stack)); return copy_stack_state(dst, src); } static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, int *insn_idx) { struct bpf_verifier_state *cur = env->cur_state; struct bpf_verifier_stack_elem *elem, *head = env->head; int err; if (env->head == NULL) return -ENOENT; if (cur) { err = copy_verifier_state(cur, &head->st); if (err) return err; } if (insn_idx) *insn_idx = head->insn_idx; if (prev_insn_idx) *prev_insn_idx = head->prev_insn_idx; elem = head->next; free_verifier_state(&head->st, false); kfree(head); env->head = elem; env->stack_size--; return 0; } static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { struct bpf_verifier_state *cur = env->cur_state; struct bpf_verifier_stack_elem *elem; int err; elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); if (!elem) goto err; elem->insn_idx = insn_idx; elem->prev_insn_idx = prev_insn_idx; elem->next = env->head; env->head = elem; env->stack_size++; err = copy_verifier_state(&elem->st, cur); if (err) goto err; if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) { verbose(env, "BPF program is too complex\n"); goto err; } return &elem->st; err: /* pop all elements and return */ while (!pop_stack(env, NULL, NULL)); return NULL; } #define CALLER_SAVED_REGS 6 static const int caller_saved[CALLER_SAVED_REGS] = { BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 }; static void __mark_reg_not_init(struct bpf_reg_state *reg); /* Mark the unknown part of a register (variable offset or scalar value) as * known to have the value @imm. */ static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) { reg->id = 0; reg->var_off = tnum_const(imm); reg->smin_value = (s64)imm; reg->smax_value = (s64)imm; reg->umin_value = imm; reg->umax_value = imm; } /* Mark the 'variable offset' part of a register as zero. This should be * used only on registers holding a pointer type. */ static void __mark_reg_known_zero(struct bpf_reg_state *reg) { __mark_reg_known(reg, 0); } static void mark_reg_known_zero(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_known_zero(regs + regno); } static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) { return type_is_pkt_pointer(reg->type); } static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) { return reg_is_pkt_pointer(reg) || reg->type == PTR_TO_PACKET_END; } /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, enum bpf_reg_type which) { /* The register can already have a range from prior markings. * This is fine as long as it hasn't been advanced from its * origin. */ return reg->type == which && reg->id == 0 && reg->off == 0 && tnum_equals_const(reg->var_off, 0); } /* Attempts to improve min/max values based on var_off information */ static void __update_reg_bounds(struct bpf_reg_state *reg) { /* min signed is max(sign bit) | min(other bits) */ reg->smin_value = max_t(s64, reg->smin_value, reg->var_off.value | (reg->var_off.mask & S64_MIN)); /* max signed is min(sign bit) | max(other bits) */ reg->smax_value = min_t(s64, reg->smax_value, reg->var_off.value | (reg->var_off.mask & S64_MAX)); reg->umin_value = max(reg->umin_value, reg->var_off.value); reg->umax_value = min(reg->umax_value, reg->var_off.value | reg->var_off.mask); } /* Uses signed min/max values to inform unsigned, and vice-versa */ static void __reg_deduce_bounds(struct bpf_reg_state *reg) { /* Learn sign from signed bounds. * If we cannot cross the sign boundary, then signed and unsigned bounds * are the same, so combine. This works even in the negative case, e.g. * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. */ if (reg->smin_value >= 0 || reg->smax_value < 0) { reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); return; } /* Learn sign from unsigned bounds. Signed bounds cross the sign * boundary, so we must be careful. */ if ((s64)reg->umax_value >= 0) { /* Positive. We can't learn anything from the smin, but smax * is positive, hence safe. */ reg->smin_value = reg->umin_value; reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); } else if ((s64)reg->umin_value < 0) { /* Negative. We can't learn anything from the smax, but smin * is negative, hence safe. */ reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); reg->smax_value = reg->umax_value; } } /* Attempts to improve var_off based on unsigned min/max information */ static void __reg_bound_offset(struct bpf_reg_state *reg) { reg->var_off = tnum_intersect(reg->var_off, tnum_range(reg->umin_value, reg->umax_value)); } /* Reset the min/max bounds of a register */ static void __mark_reg_unbounded(struct bpf_reg_state *reg) { reg->smin_value = S64_MIN; reg->smax_value = S64_MAX; reg->umin_value = 0; reg->umax_value = U64_MAX; } /* Mark a register as having a completely unknown (scalar) value. */ static void __mark_reg_unknown(struct bpf_reg_state *reg) { reg->type = SCALAR_VALUE; reg->id = 0; reg->off = 0; reg->var_off = tnum_unknown; __mark_reg_unbounded(reg); } static void mark_reg_unknown(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_unknown(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_unknown(regs + regno); } static void __mark_reg_not_init(struct bpf_reg_state *reg) { __mark_reg_unknown(reg); reg->type = NOT_INIT; } static void mark_reg_not_init(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_not_init(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_not_init(regs + regno); } static void init_reg_state(struct bpf_verifier_env *env, struct bpf_reg_state *regs) { int i; for (i = 0; i < MAX_BPF_REG; i++) { mark_reg_not_init(env, regs, i); regs[i].live = REG_LIVE_NONE; } /* frame pointer */ regs[BPF_REG_FP].type = PTR_TO_STACK; mark_reg_known_zero(env, regs, BPF_REG_FP); /* 1st arg to a function */ regs[BPF_REG_1].type = PTR_TO_CTX; mark_reg_known_zero(env, regs, BPF_REG_1); } enum reg_arg_type { SRC_OP, /* register is used as source operand */ DST_OP, /* register is used as destination operand */ DST_OP_NO_MARK /* same as above, check only, don't mark */ }; static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno) { struct bpf_verifier_state *parent = state->parent; if (regno == BPF_REG_FP) /* We don't need to worry about FP liveness because it's read-only */ return; while (parent) { /* if read wasn't screened by an earlier write ... */ if (state->regs[regno].live & REG_LIVE_WRITTEN) break; /* ... then we depend on parent's value */ parent->regs[regno].live |= REG_LIVE_READ; state = parent; parent = state->parent; } } static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, enum reg_arg_type t) { struct bpf_reg_state *regs = env->cur_state->regs; if (regno >= MAX_BPF_REG) { verbose(env, "R%d is invalid\n", regno); return -EINVAL; } if (t == SRC_OP) { /* check whether register used as source operand can be read */ if (regs[regno].type == NOT_INIT) { verbose(env, "R%d !read_ok\n", regno); return -EACCES; } mark_reg_read(env->cur_state, regno); } else { /* check whether register used as dest operand can be written to */ if (regno == BPF_REG_FP) { verbose(env, "frame pointer is read only\n"); return -EACCES; } regs[regno].live |= REG_LIVE_WRITTEN; if (t == DST_OP) mark_reg_unknown(env, regs, regno); } return 0; } static bool is_spillable_regtype(enum bpf_reg_type type) { switch (type) { case PTR_TO_MAP_VALUE: case PTR_TO_MAP_VALUE_OR_NULL: case PTR_TO_STACK: case PTR_TO_CTX: case PTR_TO_PACKET: case PTR_TO_PACKET_META: case PTR_TO_PACKET_END: case CONST_PTR_TO_MAP: return true; default: return false; } } /* check_stack_read/write functions track spill/fill of registers, * stack boundary and alignment are checked in check_mem_access() */ static int check_stack_write(struct bpf_verifier_env *env, struct bpf_verifier_state *state, int off, int size, int value_regno) { int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; err = realloc_verifier_state(state, round_up(slot + 1, BPF_REG_SIZE), true); if (err) return err; /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, * so it's aligned access and [off, off + size) are within stack limits */ if (!env->allow_ptr_leaks && state->stack[spi].slot_type[0] == STACK_SPILL && size != BPF_REG_SIZE) { verbose(env, "attempt to corrupt spilled pointer on stack\n"); return -EACCES; } if (value_regno >= 0 && is_spillable_regtype(state->regs[value_regno].type)) { /* register containing pointer is being spilled into stack */ if (size != BPF_REG_SIZE) { verbose(env, "invalid size of register spill\n"); return -EACCES; } /* save register state */ state->stack[spi].spilled_ptr = state->regs[value_regno]; state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; for (i = 0; i < BPF_REG_SIZE; i++) state->stack[spi].slot_type[i] = STACK_SPILL; } else { /* regular write of data into stack */ state->stack[spi].spilled_ptr = (struct bpf_reg_state) {}; for (i = 0; i < size; i++) state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = STACK_MISC; } return 0; } static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot) { struct bpf_verifier_state *parent = state->parent; while (parent) { /* if read wasn't screened by an earlier write ... */ if (state->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN) break; /* ... then we depend on parent's value */ parent->stack[slot].spilled_ptr.live |= REG_LIVE_READ; state = parent; parent = state->parent; } } static int check_stack_read(struct bpf_verifier_env *env, struct bpf_verifier_state *state, int off, int size, int value_regno) { int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; u8 *stype; if (state->allocated_stack <= slot) { verbose(env, "invalid read from stack off %d+0 size %d\n", off, size); return -EACCES; } stype = state->stack[spi].slot_type; if (stype[0] == STACK_SPILL) { if (size != BPF_REG_SIZE) { verbose(env, "invalid size of register spill\n"); return -EACCES; } for (i = 1; i < BPF_REG_SIZE; i++) { if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) { verbose(env, "corrupted spill memory\n"); return -EACCES; } } if (value_regno >= 0) { /* restore register state from stack */ state->regs[value_regno] = state->stack[spi].spilled_ptr; mark_stack_slot_read(state, spi); } return 0; } else { for (i = 0; i < size; i++) { if (stype[(slot - i) % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid read from stack off %d+%d size %d\n", off, i, size); return -EACCES; } } if (value_regno >= 0) /* have read misc data from the stack */ mark_reg_unknown(env, state->regs, value_regno); return 0; } } /* check read/write into map element returned by bpf_map_lookup_elem() */ static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_map *map = regs[regno].map_ptr; if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || off + size > map->value_size) { verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", map->value_size, off, size); return -EACCES; } return 0; } /* check read/write into a map element with possible variable offset */ static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *reg = &state->regs[regno]; int err; /* We may have adjusted the register to this map value, so we * need to try adding each of min_value and max_value to off * to make sure our theoretical access will be safe. */ if (env->log.level) print_verifier_state(env, state); /* The minimum value is only important with signed * comparisons where we can't assume the floor of a * value is 0. If we are using signed variables for our * index'es we need to make sure that whatever we use * will have a set floor within our range. */ if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", regno); return -EACCES; } err = __check_map_access(env, regno, reg->smin_value + off, size, zero_size_allowed); if (err) { verbose(env, "R%d min value is outside of the array range\n", regno); return err; } /* If we haven't set a max value then we need to bail since we can't be * sure we won't do bad things. * If reg->umax_value + off could overflow, treat that as unbounded too. */ if (reg->umax_value >= BPF_MAX_VAR_OFF) { verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n", regno); return -EACCES; } err = __check_map_access(env, regno, reg->umax_value + off, size, zero_size_allowed); if (err) verbose(env, "R%d max value is outside of the array range\n", regno); return err; } #define MAX_PACKET_OFF 0xffff static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, const struct bpf_call_arg_meta *meta, enum bpf_access_type t) { switch (env->prog->type) { case BPF_PROG_TYPE_LWT_IN: case BPF_PROG_TYPE_LWT_OUT: /* dst_input() and dst_output() can't write for now */ if (t == BPF_WRITE) return false; /* fallthrough */ case BPF_PROG_TYPE_SCHED_CLS: case BPF_PROG_TYPE_SCHED_ACT: case BPF_PROG_TYPE_XDP: case BPF_PROG_TYPE_LWT_XMIT: case BPF_PROG_TYPE_SK_SKB: if (meta) return meta->pkt_access; env->seen_direct_write = true; return true; default: return false; } } static int __check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = &regs[regno]; if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || (u64)off + size > reg->range) { verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", off, size, regno, reg->id, reg->off, reg->range); return -EACCES; } return 0; } static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = &regs[regno]; int err; /* We may have added a variable offset to the packet pointer; but any * reg->range we have comes after that. We are only checking the fixed * offset. */ /* We don't allow negative numbers, because we aren't tracking enough * detail to prove they're safe. */ if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", regno); return -EACCES; } err = __check_packet_access(env, regno, off, size, zero_size_allowed); if (err) { verbose(env, "R%d offset is outside of the packet\n", regno); return err; } return err; } /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, enum bpf_access_type t, enum bpf_reg_type *reg_type) { struct bpf_insn_access_aux info = { .reg_type = *reg_type, }; if (env->ops->is_valid_access && env->ops->is_valid_access(off, size, t, &info)) { /* A non zero info.ctx_field_size indicates that this field is a * candidate for later verifier transformation to load the whole * field and then apply a mask when accessed with a narrower * access than actual ctx access size. A zero info.ctx_field_size * will only allow for whole field access and rejects any other * type of narrower access. */ *reg_type = info.reg_type; env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; /* remember the offset of last byte accessed in ctx */ if (env->prog->aux->max_ctx_offset < off + size) env->prog->aux->max_ctx_offset = off + size; return 0; } verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); return -EACCES; } static bool __is_pointer_value(bool allow_ptr_leaks, const struct bpf_reg_state *reg) { if (allow_ptr_leaks) return false; return reg->type != SCALAR_VALUE; } static bool is_pointer_value(struct bpf_verifier_env *env, int regno) { return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno); } static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size, bool strict) { struct tnum reg_off; int ip_align; /* Byte size accesses are always allowed. */ if (!strict || size == 1) return 0; /* For platforms that do not have a Kconfig enabling * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of * NET_IP_ALIGN is universally set to '2'. And on platforms * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get * to this code only in strict mode where we want to emulate * the NET_IP_ALIGN==2 checking. Therefore use an * unconditional IP align value of '2'. */ ip_align = 2; reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); if (!tnum_is_aligned(reg_off, size)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "misaligned packet access off %d+%s+%d+%d size %d\n", ip_align, tn_buf, reg->off, off, size); return -EACCES; } return 0; } static int check_generic_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, const char *pointer_desc, int off, int size, bool strict) { struct tnum reg_off; /* Byte size accesses are always allowed. */ if (!strict || size == 1) return 0; reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); if (!tnum_is_aligned(reg_off, size)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", pointer_desc, tn_buf, reg->off, off, size); return -EACCES; } return 0; } static int check_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size) { bool strict = env->strict_alignment; const char *pointer_desc = ""; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: /* Special case, because of NET_IP_ALIGN. Given metadata sits * right in front, treat it the very same way. */ return check_pkt_ptr_alignment(env, reg, off, size, strict); case PTR_TO_MAP_VALUE: pointer_desc = "value "; break; case PTR_TO_CTX: pointer_desc = "context "; break; case PTR_TO_STACK: pointer_desc = "stack "; break; default: break; } return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, strict); } /* truncate register to smaller size (in bytes) * must be called with size < BPF_REG_SIZE */ static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) { u64 mask; /* clear high bits in bit representation */ reg->var_off = tnum_cast(reg->var_off, size); /* fix arithmetic bounds */ mask = ((u64)1 << (size * 8)) - 1; if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { reg->umin_value &= mask; reg->umax_value &= mask; } else { reg->umin_value = 0; reg->umax_value = mask; } reg->smin_value = reg->umin_value; reg->smax_value = reg->umax_value; } /* check whether memory at (regno + off) is accessible for t = (read | write) * if t==write, value_regno is a register which value is stored into memory * if t==read, value_regno is a register which will receive the value from memory * if t==write && value_regno==-1, some unknown value is stored into memory * if t==read && value_regno==-1, don't care what we read from memory */ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off, int bpf_size, enum bpf_access_type t, int value_regno) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = regs + regno; int size, err = 0; size = bpf_size_to_bytes(bpf_size); if (size < 0) return size; /* alignment checks will add in reg->off themselves */ err = check_ptr_alignment(env, reg, off, size); if (err) return err; /* for access checks, reg->off is just part of off */ off += reg->off; if (reg->type == PTR_TO_MAP_VALUE) { if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into map\n", value_regno); return -EACCES; } err = check_map_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else if (reg->type == PTR_TO_CTX) { enum bpf_reg_type reg_type = SCALAR_VALUE; if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into ctx\n", value_regno); return -EACCES; } /* ctx accesses must be at a fixed offset, so that we can * determine what type of data were returned. */ if (reg->off) { verbose(env, "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n", regno, reg->off, off - reg->off); return -EACCES; } if (!tnum_is_const(reg->var_off) || reg->var_off.value) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable ctx access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } err = check_ctx_access(env, insn_idx, off, size, t, &reg_type); if (!err && t == BPF_READ && value_regno >= 0) { /* ctx access returns either a scalar, or a * PTR_TO_PACKET[_META,_END]. In the latter * case, we know the offset is zero. */ if (reg_type == SCALAR_VALUE) mark_reg_unknown(env, regs, value_regno); else mark_reg_known_zero(env, regs, value_regno); regs[value_regno].id = 0; regs[value_regno].off = 0; regs[value_regno].range = 0; regs[value_regno].type = reg_type; } } else if (reg->type == PTR_TO_STACK) { /* stack accesses must be at a fixed offset, so that we can * determine what type of data were returned. * See check_stack_read(). */ if (!tnum_is_const(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable stack access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } off += reg->var_off.value; if (off >= 0 || off < -MAX_BPF_STACK) { verbose(env, "invalid stack off=%d size=%d\n", off, size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (t == BPF_WRITE) err = check_stack_write(env, state, off, size, value_regno); else err = check_stack_read(env, state, off, size, value_regno); } else if (reg_is_pkt_pointer(reg)) { if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { verbose(env, "cannot write into packet\n"); return -EACCES; } if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into packet\n", value_regno); return -EACCES; } err = check_packet_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else { verbose(env, "R%d invalid mem access '%s'\n", regno, reg_type_str[reg->type]); return -EACCES; } if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && regs[value_regno].type == SCALAR_VALUE) { /* b/h/w load zero-extends, mark upper bits as known 0 */ coerce_reg_to_size(&regs[value_regno], size); } return err; } static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) { int err; if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) || insn->imm != 0) { verbose(env, "BPF_XADD uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d leaks addr into mem\n", insn->src_reg); return -EACCES; } /* check whether atomic_add can read the memory */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, -1); if (err) return err; /* check whether atomic_add can write into the same memory */ return check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); } /* Does this register contain a constant zero? */ static bool register_is_null(struct bpf_reg_state reg) { return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0); } /* when register 'regno' is passed into function that will read 'access_size' * bytes from that pointer, make sure that it's within stack boundary * and all elements of stack are initialized. * Unlike most pointer bounds-checking functions, this one doesn't take an * 'off' argument, so it has to add in reg->off itself. */ static int check_stack_boundary(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs; int off, i, slot, spi; if (regs[regno].type != PTR_TO_STACK) { /* Allow zero-byte read from NULL, regardless of pointer type */ if (zero_size_allowed && access_size == 0 && register_is_null(regs[regno])) return 0; verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[regs[regno].type], reg_type_str[PTR_TO_STACK]); return -EACCES; } /* Only allow fixed-offset stack reads */ if (!tnum_is_const(regs[regno].var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off); verbose(env, "invalid variable stack read R%d var_off=%s\n", regno, tn_buf); } off = regs[regno].off + regs[regno].var_off.value; if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || access_size < 0 || (access_size == 0 && !zero_size_allowed)) { verbose(env, "invalid stack type R%d off=%d access_size=%d\n", regno, off, access_size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (meta && meta->raw_mode) { meta->access_size = access_size; meta->regno = regno; return 0; } for (i = 0; i < access_size; i++) { slot = -(off + i) - 1; spi = slot / BPF_REG_SIZE; if (state->allocated_stack <= slot || state->stack[spi].slot_type[slot % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid indirect read from stack off %d+%d size %d\n", off, i, access_size); return -EACCES; } } return 0; } static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno]; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: return check_packet_access(env, regno, reg->off, access_size, zero_size_allowed); case PTR_TO_MAP_VALUE: return check_map_access(env, regno, reg->off, access_size, zero_size_allowed); default: /* scalar_value|ptr_to_stack or invalid ptr */ return check_stack_boundary(env, regno, access_size, zero_size_allowed, meta); } } static int check_func_arg(struct bpf_verifier_env *env, u32 regno, enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta) { struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno]; enum bpf_reg_type expected_type, type = reg->type; int err = 0; if (arg_type == ARG_DONTCARE) return 0; err = check_reg_arg(env, regno, SRC_OP); if (err) return err; if (arg_type == ARG_ANYTHING) { if (is_pointer_value(env, regno)) { verbose(env, "R%d leaks addr into helper function\n", regno); return -EACCES; } return 0; } if (type_is_pkt_pointer(type) && !may_access_direct_pkt_data(env, meta, BPF_READ)) { verbose(env, "helper access to the packet is not allowed\n"); return -EACCES; } if (arg_type == ARG_PTR_TO_MAP_KEY || arg_type == ARG_PTR_TO_MAP_VALUE) { expected_type = PTR_TO_STACK; if (!type_is_pkt_pointer(type) && type != expected_type) goto err_type; } else if (arg_type == ARG_CONST_SIZE || arg_type == ARG_CONST_SIZE_OR_ZERO) { expected_type = SCALAR_VALUE; if (type != expected_type) goto err_type; } else if (arg_type == ARG_CONST_MAP_PTR) { expected_type = CONST_PTR_TO_MAP; if (type != expected_type) goto err_type; } else if (arg_type == ARG_PTR_TO_CTX) { expected_type = PTR_TO_CTX; if (type != expected_type) goto err_type; } else if (arg_type == ARG_PTR_TO_MEM || arg_type == ARG_PTR_TO_MEM_OR_NULL || arg_type == ARG_PTR_TO_UNINIT_MEM) { expected_type = PTR_TO_STACK; /* One exception here. In case function allows for NULL to be * passed in as argument, it's a SCALAR_VALUE type. Final test * happens during stack boundary checking. */ if (register_is_null(*reg) && arg_type == ARG_PTR_TO_MEM_OR_NULL) /* final test in check_stack_boundary() */; else if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE && type != expected_type) goto err_type; meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM; } else { verbose(env, "unsupported arg_type %d\n", arg_type); return -EFAULT; } if (arg_type == ARG_CONST_MAP_PTR) { /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ meta->map_ptr = reg->map_ptr; } else if (arg_type == ARG_PTR_TO_MAP_KEY) { /* bpf_map_xxx(..., map_ptr, ..., key) call: * check that [key, key + map->key_size) are within * stack limits and initialized */ if (!meta->map_ptr) { /* in function declaration map_ptr must come before * map_key, so that it's verified and known before * we have to check map_key here. Otherwise it means * that kernel subsystem misconfigured verifier */ verbose(env, "invalid map_ptr to access map->key\n"); return -EACCES; } if (type_is_pkt_pointer(type)) err = check_packet_access(env, regno, reg->off, meta->map_ptr->key_size, false); else err = check_stack_boundary(env, regno, meta->map_ptr->key_size, false, NULL); } else if (arg_type == ARG_PTR_TO_MAP_VALUE) { /* bpf_map_xxx(..., map_ptr, ..., value) call: * check [value, value + map->value_size) validity */ if (!meta->map_ptr) { /* kernel subsystem misconfigured verifier */ verbose(env, "invalid map_ptr to access map->value\n"); return -EACCES; } if (type_is_pkt_pointer(type)) err = check_packet_access(env, regno, reg->off, meta->map_ptr->value_size, false); else err = check_stack_boundary(env, regno, meta->map_ptr->value_size, false, NULL); } else if (arg_type == ARG_CONST_SIZE || arg_type == ARG_CONST_SIZE_OR_ZERO) { bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); /* bpf_xxx(..., buf, len) call will access 'len' bytes * from stack pointer 'buf'. Check it * note: regno == len, regno - 1 == buf */ if (regno == 0) { /* kernel subsystem misconfigured verifier */ verbose(env, "ARG_CONST_SIZE cannot be first argument\n"); return -EACCES; } /* The register is SCALAR_VALUE; the access check * happens using its boundaries. */ if (!tnum_is_const(reg->var_off)) /* For unprivileged variable accesses, disable raw * mode so that the program is required to * initialize all the memory that the helper could * just partially fill up. */ meta = NULL; if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", regno); return -EACCES; } if (reg->umin_value == 0) { err = check_helper_mem_access(env, regno - 1, 0, zero_size_allowed, meta); if (err) return err; } if (reg->umax_value >= BPF_MAX_VAR_SIZ) { verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", regno); return -EACCES; } err = check_helper_mem_access(env, regno - 1, reg->umax_value, zero_size_allowed, meta); } return err; err_type: verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[type], reg_type_str[expected_type]); return -EACCES; } static int check_map_func_compatibility(struct bpf_verifier_env *env, struct bpf_map *map, int func_id) { if (!map) return 0; /* We need a two way check, first is from map perspective ... */ switch (map->map_type) { case BPF_MAP_TYPE_PROG_ARRAY: if (func_id != BPF_FUNC_tail_call) goto error; break; case BPF_MAP_TYPE_PERF_EVENT_ARRAY: if (func_id != BPF_FUNC_perf_event_read && func_id != BPF_FUNC_perf_event_output && func_id != BPF_FUNC_perf_event_read_value) goto error; break; case BPF_MAP_TYPE_STACK_TRACE: if (func_id != BPF_FUNC_get_stackid) goto error; break; case BPF_MAP_TYPE_CGROUP_ARRAY: if (func_id != BPF_FUNC_skb_under_cgroup && func_id != BPF_FUNC_current_task_under_cgroup) goto error; break; /* devmap returns a pointer to a live net_device ifindex that we cannot * allow to be modified from bpf side. So do not allow lookup elements * for now. */ case BPF_MAP_TYPE_DEVMAP: if (func_id != BPF_FUNC_redirect_map) goto error; break; /* Restrict bpf side of cpumap, open when use-cases appear */ case BPF_MAP_TYPE_CPUMAP: if (func_id != BPF_FUNC_redirect_map) goto error; break; case BPF_MAP_TYPE_ARRAY_OF_MAPS: case BPF_MAP_TYPE_HASH_OF_MAPS: if (func_id != BPF_FUNC_map_lookup_elem) goto error; break; case BPF_MAP_TYPE_SOCKMAP: if (func_id != BPF_FUNC_sk_redirect_map && func_id != BPF_FUNC_sock_map_update && func_id != BPF_FUNC_map_delete_elem) goto error; break; default: break; } /* ... and second from the function itself. */ switch (func_id) { case BPF_FUNC_tail_call: if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) goto error; break; case BPF_FUNC_perf_event_read: case BPF_FUNC_perf_event_output: case BPF_FUNC_perf_event_read_value: if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) goto error; break; case BPF_FUNC_get_stackid: if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) goto error; break; case BPF_FUNC_current_task_under_cgroup: case BPF_FUNC_skb_under_cgroup: if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) goto error; break; case BPF_FUNC_redirect_map: if (map->map_type != BPF_MAP_TYPE_DEVMAP && map->map_type != BPF_MAP_TYPE_CPUMAP) goto error; break; case BPF_FUNC_sk_redirect_map: if (map->map_type != BPF_MAP_TYPE_SOCKMAP) goto error; break; case BPF_FUNC_sock_map_update: if (map->map_type != BPF_MAP_TYPE_SOCKMAP) goto error; break; default: break; } return 0; error: verbose(env, "cannot pass map_type %d into func %s#%d\n", map->map_type, func_id_name(func_id), func_id); return -EINVAL; } static int check_raw_mode(const struct bpf_func_proto *fn) { int count = 0; if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) count++; return count > 1 ? -EINVAL : 0; } /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] * are now invalid, so turn them into unknown SCALAR_VALUE. */ static void clear_all_pkt_pointers(struct bpf_verifier_env *env) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs, *reg; int i; for (i = 0; i < MAX_BPF_REG; i++) if (reg_is_pkt_pointer_any(&regs[i])) mark_reg_unknown(env, regs, i); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; reg = &state->stack[i].spilled_ptr; if (reg_is_pkt_pointer_any(reg)) __mark_reg_unknown(reg); } } static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx) { const struct bpf_func_proto *fn = NULL; struct bpf_reg_state *regs; struct bpf_call_arg_meta meta; bool changes_data; int i, err; /* find function prototype */ if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } if (env->ops->get_func_proto) fn = env->ops->get_func_proto(func_id); if (!fn) { verbose(env, "unknown func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } /* eBPF programs must be GPL compatible to use GPL-ed functions */ if (!env->prog->gpl_compatible && fn->gpl_only) { verbose(env, "cannot call GPL only function from proprietary program\n"); return -EINVAL; } /* With LD_ABS/IND some JITs save/restore skb from r1. */ changes_data = bpf_helper_changes_pkt_data(fn->func); if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", func_id_name(func_id), func_id); return -EINVAL; } memset(&meta, 0, sizeof(meta)); meta.pkt_access = fn->pkt_access; /* We only support one arg being in raw mode at the moment, which * is sufficient for the helper functions we have right now. */ err = check_raw_mode(fn); if (err) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(func_id), func_id); return err; } /* check args */ err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta); if (err) return err; /* Mark slots with STACK_MISC in case of raw mode, stack offset * is inferred from register state. */ for (i = 0; i < meta.access_size; i++) { err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1); if (err) return err; } regs = cur_regs(env); /* reset caller saved regs */ for (i = 0; i < CALLER_SAVED_REGS; i++) { mark_reg_not_init(env, regs, caller_saved[i]); check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); } /* update return register (already marked as written above) */ if (fn->ret_type == RET_INTEGER) { /* sets type to SCALAR_VALUE */ mark_reg_unknown(env, regs, BPF_REG_0); } else if (fn->ret_type == RET_VOID) { regs[BPF_REG_0].type = NOT_INIT; } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) { struct bpf_insn_aux_data *insn_aux; regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; /* There is no offset yet applied, variable or fixed */ mark_reg_known_zero(env, regs, BPF_REG_0); regs[BPF_REG_0].off = 0; /* remember map_ptr, so that check_map_access() * can check 'value_size' boundary of memory access * to map element returned from bpf_map_lookup_elem() */ if (meta.map_ptr == NULL) { verbose(env, "kernel subsystem misconfigured verifier\n"); return -EINVAL; } regs[BPF_REG_0].map_ptr = meta.map_ptr; regs[BPF_REG_0].id = ++env->id_gen; insn_aux = &env->insn_aux_data[insn_idx]; if (!insn_aux->map_ptr) insn_aux->map_ptr = meta.map_ptr; else if (insn_aux->map_ptr != meta.map_ptr) insn_aux->map_ptr = BPF_MAP_PTR_POISON; } else { verbose(env, "unknown return type %d of func %s#%d\n", fn->ret_type, func_id_name(func_id), func_id); return -EINVAL; } err = check_map_func_compatibility(env, meta.map_ptr, func_id); if (err) return err; if (changes_data) clear_all_pkt_pointers(env); return 0; } static bool signed_add_overflows(s64 a, s64 b) { /* Do the add in u64, where overflow is well-defined */ s64 res = (s64)((u64)a + (u64)b); if (b < 0) return res > a; return res < a; } static bool signed_sub_overflows(s64 a, s64 b) { /* Do the sub in u64, where overflow is well-defined */ s64 res = (s64)((u64)a - (u64)b); if (b < 0) return res < a; return res > a; } /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. * Caller should also handle BPF_MOV case separately. * If we return -EACCES, caller may want to try again treating pointer as a * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. */ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg) { struct bpf_reg_state *regs = cur_regs(env), *dst_reg; bool known = tnum_is_const(off_reg->var_off); s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; u8 opcode = BPF_OP(insn->code); u32 dst = insn->dst_reg; dst_reg = &regs[dst]; if (WARN_ON_ONCE(known && (smin_val != smax_val))) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: known but bad sbounds\n"); return -EINVAL; } if (WARN_ON_ONCE(known && (umin_val != umax_val))) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: known but bad ubounds\n"); return -EINVAL; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops on pointers produce (meaningless) scalars */ if (!env->allow_ptr_leaks) verbose(env, "R%d 32-bit pointer arithmetic prohibited\n", dst); return -EACCES; } if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n", dst); return -EACCES; } if (ptr_reg->type == CONST_PTR_TO_MAP) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n", dst); return -EACCES; } if (ptr_reg->type == PTR_TO_PACKET_END) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n", dst); return -EACCES; } /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. * The id may be overwritten later if we create a new variable offset. */ dst_reg->type = ptr_reg->type; dst_reg->id = ptr_reg->id; switch (opcode) { case BPF_ADD: /* We can take a fixed offset as long as it doesn't overflow * the s32 'off' field */ if (known && (ptr_reg->off + smin_val == (s64)(s32)(ptr_reg->off + smin_val))) { /* pointer += K. Accumulate it into fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->off = ptr_reg->off + smin_val; dst_reg->range = ptr_reg->range; break; } /* A new variable offset is created. Note that off_reg->off * == 0, since it's a scalar. * dst_reg gets the pointer type and since some positive * integer value was added to the pointer, give it a new 'id' * if it's a PTR_TO_PACKET. * this creates a new 'base' pointer, off_reg (variable) gets * added into the variable offset, and we copy the fixed offset * from ptr_reg. */ if (signed_add_overflows(smin_ptr, smin_val) || signed_add_overflows(smax_ptr, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr + smin_val; dst_reg->smax_value = smax_ptr + smax_val; } if (umin_ptr + umin_val < umin_ptr || umax_ptr + umax_val < umax_ptr) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value = umin_ptr + umin_val; dst_reg->umax_value = umax_ptr + umax_val; } dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ dst_reg->range = 0; } break; case BPF_SUB: if (dst_reg == off_reg) { /* scalar -= pointer. Creates an unknown scalar */ if (!env->allow_ptr_leaks) verbose(env, "R%d tried to subtract pointer from scalar\n", dst); return -EACCES; } /* We don't allow subtraction from FP, because (according to * test_verifier.c test "invalid fp arithmetic", JITs might not * be able to deal with it. */ if (ptr_reg->type == PTR_TO_STACK) { if (!env->allow_ptr_leaks) verbose(env, "R%d subtraction from stack pointer prohibited\n", dst); return -EACCES; } if (known && (ptr_reg->off - smin_val == (s64)(s32)(ptr_reg->off - smin_val))) { /* pointer -= K. Subtract it from fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->id = ptr_reg->id; dst_reg->off = ptr_reg->off - smin_val; dst_reg->range = ptr_reg->range; break; } /* A new variable offset is created. If the subtrahend is known * nonnegative, then any reg->range we had before is still good. */ if (signed_sub_overflows(smin_ptr, smax_val) || signed_sub_overflows(smax_ptr, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr - smax_val; dst_reg->smax_value = smax_ptr - smin_val; } if (umin_ptr < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value = umin_ptr - umax_val; dst_reg->umax_value = umax_ptr - umin_val; } dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ if (smin_val < 0) dst_reg->range = 0; } break; case BPF_AND: case BPF_OR: case BPF_XOR: /* bitwise ops on pointers are troublesome, prohibit for now. * (However, in principle we could allow some cases, e.g. * ptr &= ~3 which would reduce min_value by 3.) */ if (!env->allow_ptr_leaks) verbose(env, "R%d bitwise operator %s on pointer prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; default: /* other operators (e.g. MUL,LSH) produce non-pointer results */ if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; } __update_reg_bounds(dst_reg); __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } /* WARNING: This function does calculations on 64-bit values, but the actual * execution may occur on 32-bit values. Therefore, things like bitshifts * need extra checks in the 32-bit case. */ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } if (src_known) dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; if (src_known) dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->32 */ coerce_reg_to_size(dst_reg, 4); coerce_reg_to_size(&src_reg, 4); } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max * and var_off. */ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg; struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; u8 opcode = BPF_OP(insn->code); int rc; dst_reg = &regs[insn->dst_reg]; src_reg = NULL; if (dst_reg->type != SCALAR_VALUE) ptr_reg = dst_reg; if (BPF_SRC(insn->code) == BPF_X) { src_reg = &regs[insn->src_reg]; if (src_reg->type != SCALAR_VALUE) { if (dst_reg->type != SCALAR_VALUE) { /* Combining two pointers by any ALU op yields * an arbitrary scalar. */ if (!env->allow_ptr_leaks) { verbose(env, "R%d pointer %s pointer prohibited\n", insn->dst_reg, bpf_alu_string[opcode >> 4]); return -EACCES; } mark_reg_unknown(env, regs, insn->dst_reg); return 0; } else { /* scalar += pointer * This is legal, but we have to reverse our * src/dest handling in computing the range */ rc = adjust_ptr_min_max_vals(env, insn, src_reg, dst_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* scalar += unknown scalar */ __mark_reg_unknown(&off_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, off_reg); } return rc; } } else if (ptr_reg) { /* pointer += scalar */ rc = adjust_ptr_min_max_vals(env, insn, dst_reg, src_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* unknown scalar += scalar */ __mark_reg_unknown(dst_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, *src_reg); } return rc; } } else { /* Pretend the src is a reg with a known value, since we only * need to be able to read from this state. */ off_reg.type = SCALAR_VALUE; __mark_reg_known(&off_reg, insn->imm); src_reg = &off_reg; if (ptr_reg) { /* pointer += K */ rc = adjust_ptr_min_max_vals(env, insn, ptr_reg, src_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* unknown scalar += K */ __mark_reg_unknown(dst_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, off_reg); } return rc; } } /* Got here implies adding two SCALAR_VALUEs */ if (WARN_ON_ONCE(ptr_reg)) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: unexpected ptr_reg\n"); return -EINVAL; } if (WARN_ON(!src_reg)) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: no src_reg\n"); return -EINVAL; } return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); } /* check validity of 32-bit and 64-bit arithmetic operations */ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); int err; if (opcode == BPF_END || opcode == BPF_NEG) { if (opcode == BPF_NEG) { if (BPF_SRC(insn->code) != 0 || insn->src_reg != BPF_REG_0 || insn->off != 0 || insn->imm != 0) { verbose(env, "BPF_NEG uses reserved fields\n"); return -EINVAL; } } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0 || (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || BPF_CLASS(insn->code) == BPF_ALU64) { verbose(env, "BPF_END uses reserved fields\n"); return -EINVAL; } } /* check src operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer arithmetic prohibited\n", insn->dst_reg); return -EACCES; } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; } else if (opcode == BPF_MOV) { if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose(env, "BPF_MOV uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose(env, "BPF_MOV uses reserved fields\n"); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; if (BPF_SRC(insn->code) == BPF_X) { if (BPF_CLASS(insn->code) == BPF_ALU64) { /* case: R1 = R2 * copy register state to dest reg */ regs[insn->dst_reg] = regs[insn->src_reg]; regs[insn->dst_reg].live |= REG_LIVE_WRITTEN; } else { /* R1 = (u32) R2 */ if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d partial copy of pointer\n", insn->src_reg); return -EACCES; } mark_reg_unknown(env, regs, insn->dst_reg); coerce_reg_to_size(&regs[insn->dst_reg], 4); } } else { /* case: R = imm * remember the value we stored into this reg */ regs[insn->dst_reg].type = SCALAR_VALUE; if (BPF_CLASS(insn->code) == BPF_ALU64) { __mark_reg_known(regs + insn->dst_reg, insn->imm); } else { __mark_reg_known(regs + insn->dst_reg, (u32)insn->imm); } } } else if (opcode > BPF_END) { verbose(env, "invalid BPF_ALU opcode %x\n", opcode); return -EINVAL; } else { /* all other ALU ops: and, sub, xor, add, ... */ if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose(env, "BPF_ALU uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose(env, "BPF_ALU uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if ((opcode == BPF_MOD || opcode == BPF_DIV) && BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { verbose(env, "div by zero\n"); return -EINVAL; } if ((opcode == BPF_LSH || opcode == BPF_RSH || opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; if (insn->imm < 0 || insn->imm >= size) { verbose(env, "invalid shift %d\n", insn->imm); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; return adjust_reg_min_max_vals(env, insn); } return 0; } static void find_good_pkt_pointers(struct bpf_verifier_state *state, struct bpf_reg_state *dst_reg, enum bpf_reg_type type, bool range_right_open) { struct bpf_reg_state *regs = state->regs, *reg; u16 new_range; int i; if (dst_reg->off < 0 || (dst_reg->off == 0 && range_right_open)) /* This doesn't give us any range */ return; if (dst_reg->umax_value > MAX_PACKET_OFF || dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) /* Risk of overflow. For instance, ptr + (1<<63) may be less * than pkt_end, but that's because it's also less than pkt. */ return; new_range = dst_reg->off; if (range_right_open) new_range--; /* Examples for register markings: * * pkt_data in dst register: * * r2 = r3; * r2 += 8; * if (r2 > pkt_end) goto <handle exception> * <access okay> * * r2 = r3; * r2 += 8; * if (r2 < pkt_end) goto <access okay> * <handle exception> * * Where: * r2 == dst_reg, pkt_end == src_reg * r2=pkt(id=n,off=8,r=0) * r3=pkt(id=n,off=0,r=0) * * pkt_data in src register: * * r2 = r3; * r2 += 8; * if (pkt_end >= r2) goto <access okay> * <handle exception> * * r2 = r3; * r2 += 8; * if (pkt_end <= r2) goto <handle exception> * <access okay> * * Where: * pkt_end == dst_reg, r2 == src_reg * r2=pkt(id=n,off=8,r=0) * r3=pkt(id=n,off=0,r=0) * * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) * and [r3, r3 + 8-1) respectively is safe to access depending on * the check. */ /* If our ids match, then we must have the same max_value. And we * don't care about the other reg's fixed offset, since if it's too big * the range won't allow anything. * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. */ for (i = 0; i < MAX_BPF_REG; i++) if (regs[i].type == type && regs[i].id == dst_reg->id) /* keep the maximum range already checked */ regs[i].range = max(regs[i].range, new_range); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; reg = &state->stack[i].spilled_ptr; if (reg->type == type && reg->id == dst_reg->id) reg->range = max(reg->range, new_range); } } /* Adjusts the register min/max values in the case that the dst_reg is the * variable register that we are working on, and src_reg is a constant or we're * simply doing a BPF_K check. * In JEQ/JNE cases we also adjust the var_off values. */ static void reg_set_min_max(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { /* If the dst_reg is a pointer, we can't learn anything about its * variable offset from the compare (unless src_reg were a pointer into * the same object, but we don't bother with that. * Since false_reg and true_reg have the same type by construction, we * only need to check one of them for pointerness. */ if (__is_pointer_value(false, false_reg)) return; switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ __mark_reg_known(true_reg, val); break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ __mark_reg_known(false_reg, val); break; case BPF_JGT: false_reg->umax_value = min(false_reg->umax_value, val); true_reg->umin_value = max(true_reg->umin_value, val + 1); break; case BPF_JSGT: false_reg->smax_value = min_t(s64, false_reg->smax_value, val); true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); break; case BPF_JLT: false_reg->umin_value = max(false_reg->umin_value, val); true_reg->umax_value = min(true_reg->umax_value, val - 1); break; case BPF_JSLT: false_reg->smin_value = max_t(s64, false_reg->smin_value, val); true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); break; case BPF_JGE: false_reg->umax_value = min(false_reg->umax_value, val - 1); true_reg->umin_value = max(true_reg->umin_value, val); break; case BPF_JSGE: false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); true_reg->smin_value = max_t(s64, true_reg->smin_value, val); break; case BPF_JLE: false_reg->umin_value = max(false_reg->umin_value, val + 1); true_reg->umax_value = min(true_reg->umax_value, val); break; case BPF_JSLE: false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); true_reg->smax_value = min_t(s64, true_reg->smax_value, val); break; default: break; } __reg_deduce_bounds(false_reg); __reg_deduce_bounds(true_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(false_reg); __reg_bound_offset(true_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(false_reg); __update_reg_bounds(true_reg); } /* Same as above, but for the case that dst_reg holds a constant and src_reg is * the variable reg. */ static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { if (__is_pointer_value(false, false_reg)) return; switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ __mark_reg_known(true_reg, val); break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ __mark_reg_known(false_reg, val); break; case BPF_JGT: true_reg->umax_value = min(true_reg->umax_value, val - 1); false_reg->umin_value = max(false_reg->umin_value, val); break; case BPF_JSGT: true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); false_reg->smin_value = max_t(s64, false_reg->smin_value, val); break; case BPF_JLT: true_reg->umin_value = max(true_reg->umin_value, val + 1); false_reg->umax_value = min(false_reg->umax_value, val); break; case BPF_JSLT: true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); false_reg->smax_value = min_t(s64, false_reg->smax_value, val); break; case BPF_JGE: true_reg->umax_value = min(true_reg->umax_value, val); false_reg->umin_value = max(false_reg->umin_value, val + 1); break; case BPF_JSGE: true_reg->smax_value = min_t(s64, true_reg->smax_value, val); false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); break; case BPF_JLE: true_reg->umin_value = max(true_reg->umin_value, val); false_reg->umax_value = min(false_reg->umax_value, val - 1); break; case BPF_JSLE: true_reg->smin_value = max_t(s64, true_reg->smin_value, val); false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); break; default: break; } __reg_deduce_bounds(false_reg); __reg_deduce_bounds(true_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(false_reg); __reg_bound_offset(true_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(false_reg); __update_reg_bounds(true_reg); } /* Regs are known to be equal, so intersect their min/max/var_off */ static void __reg_combine_min_max(struct bpf_reg_state *src_reg, struct bpf_reg_state *dst_reg) { src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, dst_reg->umin_value); src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, dst_reg->umax_value); src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, dst_reg->smin_value); src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, dst_reg->smax_value); src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, dst_reg->var_off); /* We might have learned new bounds from the var_off. */ __update_reg_bounds(src_reg); __update_reg_bounds(dst_reg); /* We might have learned something about the sign bit. */ __reg_deduce_bounds(src_reg); __reg_deduce_bounds(dst_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(src_reg); __reg_bound_offset(dst_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(src_reg); __update_reg_bounds(dst_reg); } static void reg_combine_min_max(struct bpf_reg_state *true_src, struct bpf_reg_state *true_dst, struct bpf_reg_state *false_src, struct bpf_reg_state *false_dst, u8 opcode) { switch (opcode) { case BPF_JEQ: __reg_combine_min_max(true_src, true_dst); break; case BPF_JNE: __reg_combine_min_max(false_src, false_dst); break; } } static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id, bool is_null) { struct bpf_reg_state *reg = &regs[regno]; if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) { /* Old offset (both fixed and variable parts) should * have been known-zero, because we don't allow pointer * arithmetic on pointers that might be NULL. */ if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0) || reg->off)) { __mark_reg_known_zero(reg); reg->off = 0; } if (is_null) { reg->type = SCALAR_VALUE; } else if (reg->map_ptr->inner_map_meta) { reg->type = CONST_PTR_TO_MAP; reg->map_ptr = reg->map_ptr->inner_map_meta; } else { reg->type = PTR_TO_MAP_VALUE; } /* We don't need id from this point onwards anymore, thus we * should better reset it, so that state pruning has chances * to take effect. */ reg->id = 0; } } /* The logic is similar to find_good_pkt_pointers(), both could eventually * be folded together at some point. */ static void mark_map_regs(struct bpf_verifier_state *state, u32 regno, bool is_null) { struct bpf_reg_state *regs = state->regs; u32 id = regs[regno].id; int i; for (i = 0; i < MAX_BPF_REG; i++) mark_map_reg(regs, i, id, is_null); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null); } } static bool try_match_pkt_pointers(const struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg, struct bpf_verifier_state *this_branch, struct bpf_verifier_state *other_branch) { if (BPF_SRC(insn->code) != BPF_X) return false; switch (BPF_OP(insn->code)) { case BPF_JGT: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ find_good_pkt_pointers(this_branch, dst_reg, dst_reg->type, false); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end > pkt_data', pkt_data > pkt_meta' */ find_good_pkt_pointers(other_branch, src_reg, src_reg->type, true); } else { return false; } break; case BPF_JLT: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ find_good_pkt_pointers(other_branch, dst_reg, dst_reg->type, true); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end < pkt_data', pkt_data > pkt_meta' */ find_good_pkt_pointers(this_branch, src_reg, src_reg->type, false); } else { return false; } break; case BPF_JGE: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ find_good_pkt_pointers(this_branch, dst_reg, dst_reg->type, true); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ find_good_pkt_pointers(other_branch, src_reg, src_reg->type, false); } else { return false; } break; case BPF_JLE: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ find_good_pkt_pointers(other_branch, dst_reg, dst_reg->type, false); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ find_good_pkt_pointers(this_branch, src_reg, src_reg->type, true); } else { return false; } break; default: return false; } return true; } static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct bpf_verifier_state *other_branch, *this_branch = env->cur_state; struct bpf_reg_state *regs = this_branch->regs, *dst_reg; u8 opcode = BPF_OP(insn->code); int err; if (opcode > BPF_JSLE) { verbose(env, "invalid BPF_JMP opcode %x\n", opcode); return -EINVAL; } if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->src_reg); return -EACCES; } } else { if (insn->src_reg != BPF_REG_0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg = &regs[insn->dst_reg]; /* detect if R == 0 where R was initialized to zero earlier */ if (BPF_SRC(insn->code) == BPF_K && (opcode == BPF_JEQ || opcode == BPF_JNE) && dst_reg->type == SCALAR_VALUE && tnum_equals_const(dst_reg->var_off, insn->imm)) { if (opcode == BPF_JEQ) { /* if (imm == imm) goto pc+off; * only follow the goto, ignore fall-through */ *insn_idx += insn->off; return 0; } else { /* if (imm != imm) goto pc+off; * only follow fall-through branch, since * that's where the program will go */ return 0; } } other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx); if (!other_branch) return -EFAULT; /* detect if we are comparing against a constant value so we can adjust * our min/max values for our dst register. * this is only legit if both are scalars (or pointers to the same * object, I suppose, but we don't support that right now), because * otherwise the different base pointers mean the offsets aren't * comparable. */ if (BPF_SRC(insn->code) == BPF_X) { if (dst_reg->type == SCALAR_VALUE && regs[insn->src_reg].type == SCALAR_VALUE) { if (tnum_is_const(regs[insn->src_reg].var_off)) reg_set_min_max(&other_branch->regs[insn->dst_reg], dst_reg, regs[insn->src_reg].var_off.value, opcode); else if (tnum_is_const(dst_reg->var_off)) reg_set_min_max_inv(&other_branch->regs[insn->src_reg], &regs[insn->src_reg], dst_reg->var_off.value, opcode); else if (opcode == BPF_JEQ || opcode == BPF_JNE) /* Comparing for equality, we can combine knowledge */ reg_combine_min_max(&other_branch->regs[insn->src_reg], &other_branch->regs[insn->dst_reg], &regs[insn->src_reg], &regs[insn->dst_reg], opcode); } } else if (dst_reg->type == SCALAR_VALUE) { reg_set_min_max(&other_branch->regs[insn->dst_reg], dst_reg, insn->imm, opcode); } /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ if (BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { /* Mark all identical map registers in each branch as either * safe or unknown depending R == 0 or R != 0 conditional. */ mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg], this_branch, other_branch) && is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->dst_reg); return -EACCES; } if (env->log.level) print_verifier_state(env, this_branch); return 0; } /* return the map pointer stored inside BPF_LD_IMM64 instruction */ static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn) { u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32; return (struct bpf_map *) (unsigned long) imm64; } /* verify BPF_LD_IMM64 instruction */ static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); int err; if (BPF_SIZE(insn->code) != BPF_DW) { verbose(env, "invalid BPF_LD_IMM insn\n"); return -EINVAL; } if (insn->off != 0) { verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); return -EINVAL; } err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; if (insn->src_reg == 0) { u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; regs[insn->dst_reg].type = SCALAR_VALUE; __mark_reg_known(&regs[insn->dst_reg], imm); return 0; } /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */ BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD); regs[insn->dst_reg].type = CONST_PTR_TO_MAP; regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn); return 0; } static bool may_access_skb(enum bpf_prog_type type) { switch (type) { case BPF_PROG_TYPE_SOCKET_FILTER: case BPF_PROG_TYPE_SCHED_CLS: case BPF_PROG_TYPE_SCHED_ACT: return true; default: return false; } } /* verify safety of LD_ABS|LD_IND instructions: * - they can only appear in the programs where ctx == skb * - since they are wrappers of function calls, they scratch R1-R5 registers, * preserve R6-R9, and store return value into R0 * * Implicit input: * ctx == skb == R6 == CTX * * Explicit input: * SRC == any register * IMM == 32-bit immediate * * Output: * R0 - 8/16/32-bit skb data converted to cpu endianness */ static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); u8 mode = BPF_MODE(insn->code); int i, err; if (!may_access_skb(env->prog->type)) { verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); return -EINVAL; } if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || BPF_SIZE(insn->code) == BPF_DW || (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); return -EINVAL; } /* check whether implicit source operand (register R6) is readable */ err = check_reg_arg(env, BPF_REG_6, SRC_OP); if (err) return err; if (regs[BPF_REG_6].type != PTR_TO_CTX) { verbose(env, "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); return -EINVAL; } if (mode == BPF_IND) { /* check explicit source operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } /* reset caller saved regs to unreadable */ for (i = 0; i < CALLER_SAVED_REGS; i++) { mark_reg_not_init(env, regs, caller_saved[i]); check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); } /* mark destination R0 register as readable, since it contains * the value fetched from the packet. * Already marked as written above. */ mark_reg_unknown(env, regs, BPF_REG_0); return 0; } static int check_return_code(struct bpf_verifier_env *env) { struct bpf_reg_state *reg; struct tnum range = tnum_range(0, 1); switch (env->prog->type) { case BPF_PROG_TYPE_CGROUP_SKB: case BPF_PROG_TYPE_CGROUP_SOCK: case BPF_PROG_TYPE_SOCK_OPS: case BPF_PROG_TYPE_CGROUP_DEVICE: break; default: return 0; } reg = cur_regs(env) + BPF_REG_0; if (reg->type != SCALAR_VALUE) { verbose(env, "At program exit the register R0 is not a known value (%s)\n", reg_type_str[reg->type]); return -EINVAL; } if (!tnum_in(range, reg->var_off)) { verbose(env, "At program exit the register R0 "); if (!tnum_is_unknown(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "has value %s", tn_buf); } else { verbose(env, "has unknown scalar value"); } verbose(env, " should have been 0 or 1\n"); return -EINVAL; } return 0; } /* non-recursive DFS pseudo code * 1 procedure DFS-iterative(G,v): * 2 label v as discovered * 3 let S be a stack * 4 S.push(v) * 5 while S is not empty * 6 t <- S.pop() * 7 if t is what we're looking for: * 8 return t * 9 for all edges e in G.adjacentEdges(t) do * 10 if edge e is already labelled * 11 continue with the next edge * 12 w <- G.adjacentVertex(t,e) * 13 if vertex w is not discovered and not explored * 14 label e as tree-edge * 15 label w as discovered * 16 S.push(w) * 17 continue at 5 * 18 else if vertex w is discovered * 19 label e as back-edge * 20 else * 21 // vertex w is explored * 22 label e as forward- or cross-edge * 23 label t as explored * 24 S.pop() * * convention: * 0x10 - discovered * 0x11 - discovered and fall-through edge labelled * 0x12 - discovered and fall-through and branch edges labelled * 0x20 - explored */ enum { DISCOVERED = 0x10, EXPLORED = 0x20, FALLTHROUGH = 1, BRANCH = 2, }; #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L) static int *insn_stack; /* stack of insns to process */ static int cur_stack; /* current stack index */ static int *insn_state; /* t, w, e - match pseudo-code above: * t - index of current instruction * w - next instruction * e - edge */ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) { if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) return 0; if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) return 0; if (w < 0 || w >= env->prog->len) { verbose(env, "jump out of range from insn %d to %d\n", t, w); return -EINVAL; } if (e == BRANCH) /* mark branch target for state pruning */ env->explored_states[w] = STATE_LIST_MARK; if (insn_state[w] == 0) { /* tree-edge */ insn_state[t] = DISCOVERED | e; insn_state[w] = DISCOVERED; if (cur_stack >= env->prog->len) return -E2BIG; insn_stack[cur_stack++] = w; return 1; } else if ((insn_state[w] & 0xF0) == DISCOVERED) { verbose(env, "back-edge from insn %d to %d\n", t, w); return -EINVAL; } else if (insn_state[w] == EXPLORED) { /* forward- or cross-edge */ insn_state[t] = DISCOVERED | e; } else { verbose(env, "insn state internal bug\n"); return -EFAULT; } return 0; } /* non-recursive depth-first-search to detect loops in BPF program * loop == back-edge in directed graph */ static int check_cfg(struct bpf_verifier_env *env) { struct bpf_insn *insns = env->prog->insnsi; int insn_cnt = env->prog->len; int ret = 0; int i, t; insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); if (!insn_state) return -ENOMEM; insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); if (!insn_stack) { kfree(insn_state); return -ENOMEM; } insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ insn_stack[0] = 0; /* 0 is the first instruction */ cur_stack = 1; peek_stack: if (cur_stack == 0) goto check_state; t = insn_stack[cur_stack - 1]; if (BPF_CLASS(insns[t].code) == BPF_JMP) { u8 opcode = BPF_OP(insns[t].code); if (opcode == BPF_EXIT) { goto mark_explored; } else if (opcode == BPF_CALL) { ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; if (t + 1 < insn_cnt) env->explored_states[t + 1] = STATE_LIST_MARK; } else if (opcode == BPF_JA) { if (BPF_SRC(insns[t].code) != BPF_K) { ret = -EINVAL; goto err_free; } /* unconditional jump with single edge */ ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; /* tell verifier to check for equivalent states * after every call and jump */ if (t + 1 < insn_cnt) env->explored_states[t + 1] = STATE_LIST_MARK; } else { /* conditional jump with two edges */ env->explored_states[t] = STATE_LIST_MARK; ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; ret = push_insn(t, t + insns[t].off + 1, BRANCH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; } } else { /* all other non-branch instructions with single * fall-through edge */ ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; } mark_explored: insn_state[t] = EXPLORED; if (cur_stack-- <= 0) { verbose(env, "pop stack internal bug\n"); ret = -EFAULT; goto err_free; } goto peek_stack; check_state: for (i = 0; i < insn_cnt; i++) { if (insn_state[i] != EXPLORED) { verbose(env, "unreachable insn %d\n", i); ret = -EINVAL; goto err_free; } } ret = 0; /* cfg looks good */ err_free: kfree(insn_state); kfree(insn_stack); return ret; } /* check %cur's range satisfies %old's */ static bool range_within(struct bpf_reg_state *old, struct bpf_reg_state *cur) { return old->umin_value <= cur->umin_value && old->umax_value >= cur->umax_value && old->smin_value <= cur->smin_value && old->smax_value >= cur->smax_value; } /* Maximum number of register states that can exist at once */ #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) struct idpair { u32 old; u32 cur; }; /* If in the old state two registers had the same id, then they need to have * the same id in the new state as well. But that id could be different from * the old state, so we need to track the mapping from old to new ids. * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent * regs with old id 5 must also have new id 9 for the new state to be safe. But * regs with a different old id could still have new id 9, we don't care about * that. * So we look through our idmap to see if this old id has been seen before. If * so, we require the new id to match; otherwise, we add the id pair to the map. */ static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap) { unsigned int i; for (i = 0; i < ID_MAP_SIZE; i++) { if (!idmap[i].old) { /* Reached an empty slot; haven't seen this id before */ idmap[i].old = old_id; idmap[i].cur = cur_id; return true; } if (idmap[i].old == old_id) return idmap[i].cur == cur_id; } /* We ran out of idmap slots, which should be impossible */ WARN_ON_ONCE(1); return false; } /* Returns true if (rold safe implies rcur safe) */ static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, struct idpair *idmap) { if (!(rold->live & REG_LIVE_READ)) /* explored state didn't use this */ return true; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0) return true; if (rold->type == NOT_INIT) /* explored state can't have used this */ return true; if (rcur->type == NOT_INIT) return false; switch (rold->type) { case SCALAR_VALUE: if (rcur->type == SCALAR_VALUE) { /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); } else { /* if we knew anything about the old value, we're not * equal, because we can't know anything about the * scalar value of the pointer in the new value. */ return rold->umin_value == 0 && rold->umax_value == U64_MAX && rold->smin_value == S64_MIN && rold->smax_value == S64_MAX && tnum_is_unknown(rold->var_off); } case PTR_TO_MAP_VALUE: /* If the new min/max/var_off satisfy the old ones and * everything else matches, we are OK. * We don't care about the 'id' value, because nothing * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) */ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_MAP_VALUE_OR_NULL: /* a PTR_TO_MAP_VALUE could be safe to use as a * PTR_TO_MAP_VALUE_OR_NULL into the same map. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- * checked, doing so could have affected others with the same * id, and we can't check for that because we lost the id when * we converted to a PTR_TO_MAP_VALUE. */ if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) return false; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) return false; /* Check our ids match any regs they're supposed to */ return check_ids(rold->id, rcur->id, idmap); case PTR_TO_PACKET_META: case PTR_TO_PACKET: if (rcur->type != rold->type) return false; /* We must have at least as much range as the old ptr * did, so that any accesses which were safe before are * still safe. This is true even if old range < old off, * since someone could have accessed through (ptr - k), or * even done ptr -= k in a register, to get a safe access. */ if (rold->range > rcur->range) return false; /* If the offsets don't match, we can't trust our alignment; * nor can we be sure that we won't fall out of range. */ if (rold->off != rcur->off) return false; /* id relations must be preserved */ if (rold->id && !check_ids(rold->id, rcur->id, idmap)) return false; /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_CTX: case CONST_PTR_TO_MAP: case PTR_TO_STACK: case PTR_TO_PACKET_END: /* Only valid matches are exact, which memcmp() above * would have accepted */ default: /* Don't know what's going on, just say it's not safe */ return false; } /* Shouldn't get here; if we do, say it's not safe */ WARN_ON_ONCE(1); return false; } static bool stacksafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur, struct idpair *idmap) { int i, spi; /* if explored stack has more populated slots than current stack * such stacks are not equivalent */ if (old->allocated_stack > cur->allocated_stack) return false; /* walk slots of the explored stack and ignore any additional * slots in the current stack, since explored(safe) state * didn't use them */ for (i = 0; i < old->allocated_stack; i++) { spi = i / BPF_REG_SIZE; if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) continue; if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != cur->stack[spi].slot_type[i % BPF_REG_SIZE]) /* Ex: old explored (safe) state has STACK_SPILL in * this stack slot, but current has has STACK_MISC -> * this verifier states are not equivalent, * return false to continue verification of this path */ return false; if (i % BPF_REG_SIZE) continue; if (old->stack[spi].slot_type[0] != STACK_SPILL) continue; if (!regsafe(&old->stack[spi].spilled_ptr, &cur->stack[spi].spilled_ptr, idmap)) /* when explored and current stack slot are both storing * spilled registers, check that stored pointers types * are the same as well. * Ex: explored safe path could have stored * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} * but current path has stored: * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} * such verifier states are not equivalent. * return false to continue verification of this path */ return false; } return true; } /* compare two verifier states * * all states stored in state_list are known to be valid, since * verifier reached 'bpf_exit' instruction through them * * this function is called when verifier exploring different branches of * execution popped from the state stack. If it sees an old state that has * more strict register state and more strict stack state then this execution * branch doesn't need to be explored further, since verifier already * concluded that more strict state leads to valid finish. * * Therefore two states are equivalent if register state is more conservative * and explored stack state is more conservative than the current one. * Example: * explored current * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) * * In other words if current stack state (one being explored) has more * valid slots than old one that already passed validation, it means * the verifier can stop exploring and conclude that current state is valid too * * Similarly with registers. If explored state has register type as invalid * whereas register type in current state is meaningful, it means that * the current state will reach 'bpf_exit' instruction safely */ static bool states_equal(struct bpf_verifier_env *env, struct bpf_verifier_state *old, struct bpf_verifier_state *cur) { struct idpair *idmap; bool ret = false; int i; idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL); /* If we failed to allocate the idmap, just say it's not safe */ if (!idmap) return false; for (i = 0; i < MAX_BPF_REG; i++) { if (!regsafe(&old->regs[i], &cur->regs[i], idmap)) goto out_free; } if (!stacksafe(old, cur, idmap)) goto out_free; ret = true; out_free: kfree(idmap); return ret; } /* A write screens off any subsequent reads; but write marks come from the * straight-line code between a state and its parent. When we arrive at a * jump target (in the first iteration of the propagate_liveness() loop), * we didn't arrive by the straight-line code, so read marks in state must * propagate to parent regardless of state's write marks. */ static bool do_propagate_liveness(const struct bpf_verifier_state *state, struct bpf_verifier_state *parent) { bool writes = parent == state->parent; /* Observe write marks */ bool touched = false; /* any changes made? */ int i; if (!parent) return touched; /* Propagate read liveness of registers... */ BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); /* We don't need to worry about FP liveness because it's read-only */ for (i = 0; i < BPF_REG_FP; i++) { if (parent->regs[i].live & REG_LIVE_READ) continue; if (writes && (state->regs[i].live & REG_LIVE_WRITTEN)) continue; if (state->regs[i].live & REG_LIVE_READ) { parent->regs[i].live |= REG_LIVE_READ; touched = true; } } /* ... and stack slots */ for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && i < parent->allocated_stack / BPF_REG_SIZE; i++) { if (parent->stack[i].slot_type[0] != STACK_SPILL) continue; if (state->stack[i].slot_type[0] != STACK_SPILL) continue; if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ) continue; if (writes && (state->stack[i].spilled_ptr.live & REG_LIVE_WRITTEN)) continue; if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) { parent->stack[i].spilled_ptr.live |= REG_LIVE_READ; touched = true; } } return touched; } /* "parent" is "a state from which we reach the current state", but initially * it is not the state->parent (i.e. "the state whose straight-line code leads * to the current state"), instead it is the state that happened to arrive at * a (prunable) equivalent of the current state. See comment above * do_propagate_liveness() for consequences of this. * This function is just a more efficient way of calling mark_reg_read() or * mark_stack_slot_read() on each reg in "parent" that is read in "state", * though it requires that parent != state->parent in the call arguments. */ static void propagate_liveness(const struct bpf_verifier_state *state, struct bpf_verifier_state *parent) { while (do_propagate_liveness(state, parent)) { /* Something changed, so we need to feed those changes onward */ state = parent; parent = state->parent; } } static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) { struct bpf_verifier_state_list *new_sl; struct bpf_verifier_state_list *sl; struct bpf_verifier_state *cur = env->cur_state; int i, err; sl = env->explored_states[insn_idx]; if (!sl) /* this 'insn_idx' instruction wasn't marked, so we will not * be doing state search here */ return 0; while (sl != STATE_LIST_MARK) { if (states_equal(env, &sl->state, cur)) { /* reached equivalent register/stack state, * prune the search. * Registers read by the continuation are read by us. * If we have any write marks in env->cur_state, they * will prevent corresponding reads in the continuation * from reaching our parent (an explored_state). Our * own state will get the read marks recorded, but * they'll be immediately forgotten as we're pruning * this state and will pop a new one. */ propagate_liveness(&sl->state, cur); return 1; } sl = sl->next; } /* there were no equivalent states, remember current one. * technically the current state is not proven to be safe yet, * but it will either reach bpf_exit (which means it's safe) or * it will be rejected. Since there are no loops, we won't be * seeing this 'insn_idx' instruction again on the way to bpf_exit */ new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); if (!new_sl) return -ENOMEM; /* add new state to the head of linked list */ err = copy_verifier_state(&new_sl->state, cur); if (err) { free_verifier_state(&new_sl->state, false); kfree(new_sl); return err; } new_sl->next = env->explored_states[insn_idx]; env->explored_states[insn_idx] = new_sl; /* connect new state to parentage chain */ cur->parent = &new_sl->state; /* clear write marks in current state: the writes we did are not writes * our child did, so they don't screen off its reads from us. * (There are no read marks in current state, because reads always mark * their parent and current state never has children yet. Only * explored_states can get read marks.) */ for (i = 0; i < BPF_REG_FP; i++) cur->regs[i].live = REG_LIVE_NONE; for (i = 0; i < cur->allocated_stack / BPF_REG_SIZE; i++) if (cur->stack[i].slot_type[0] == STACK_SPILL) cur->stack[i].spilled_ptr.live = REG_LIVE_NONE; return 0; } static int ext_analyzer_insn_hook(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { if (env->dev_ops && env->dev_ops->insn_hook) return env->dev_ops->insn_hook(env, insn_idx, prev_insn_idx); return 0; } static int do_check(struct bpf_verifier_env *env) { struct bpf_verifier_state *state; struct bpf_insn *insns = env->prog->insnsi; struct bpf_reg_state *regs; int insn_cnt = env->prog->len; int insn_idx, prev_insn_idx = 0; int insn_processed = 0; bool do_print_state = false; state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); if (!state) return -ENOMEM; env->cur_state = state; init_reg_state(env, state->regs); state->parent = NULL; insn_idx = 0; for (;;) { struct bpf_insn *insn; u8 class; int err; if (insn_idx >= insn_cnt) { verbose(env, "invalid insn idx %d insn_cnt %d\n", insn_idx, insn_cnt); return -EFAULT; } insn = &insns[insn_idx]; class = BPF_CLASS(insn->code); if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { verbose(env, "BPF program is too large. Processed %d insn\n", insn_processed); return -E2BIG; } err = is_state_visited(env, insn_idx); if (err < 0) return err; if (err == 1) { /* found equivalent state, can prune the search */ if (env->log.level) { if (do_print_state) verbose(env, "\nfrom %d to %d: safe\n", prev_insn_idx, insn_idx); else verbose(env, "%d: safe\n", insn_idx); } goto process_bpf_exit; } if (need_resched()) cond_resched(); if (env->log.level > 1 || (env->log.level && do_print_state)) { if (env->log.level > 1) verbose(env, "%d:", insn_idx); else verbose(env, "\nfrom %d to %d:", prev_insn_idx, insn_idx); print_verifier_state(env, state); do_print_state = false; } if (env->log.level) { verbose(env, "%d: ", insn_idx); print_bpf_insn(verbose, env, insn, env->allow_ptr_leaks); } err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx); if (err) return err; regs = cur_regs(env); env->insn_aux_data[insn_idx].seen = true; if (class == BPF_ALU || class == BPF_ALU64) { err = check_alu_op(env, insn); if (err) return err; } else if (class == BPF_LDX) { enum bpf_reg_type *prev_src_type, src_reg_type; /* check for reserved fields is already done */ /* check src operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; src_reg_type = regs[insn->src_reg].type; /* check that memory (src_reg + off) is readable, * the state of dst_reg will be updated by this func */ err = check_mem_access(env, insn_idx, insn->src_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, insn->dst_reg); if (err) return err; prev_src_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_src_type == NOT_INIT) { /* saw a valid insn * dst_reg = *(u32 *)(src_reg + off) * save type to validate intersecting paths */ *prev_src_type = src_reg_type; } else if (src_reg_type != *prev_src_type && (src_reg_type == PTR_TO_CTX || *prev_src_type == PTR_TO_CTX)) { /* ABuser program is trying to use the same insn * dst_reg = *(u32*) (src_reg + off) * with different pointer types: * src_reg == ctx in one branch and * src_reg == stack|map in some other branch. * Reject it. */ verbose(env, "same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_STX) { enum bpf_reg_type *prev_dst_type, dst_reg_type; if (BPF_MODE(insn->code) == BPF_XADD) { err = check_xadd(env, insn_idx, insn); if (err) return err; insn_idx++; continue; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg_type = regs[insn->dst_reg].type; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg); if (err) return err; prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_dst_type == NOT_INIT) { *prev_dst_type = dst_reg_type; } else if (dst_reg_type != *prev_dst_type && (dst_reg_type == PTR_TO_CTX || *prev_dst_type == PTR_TO_CTX)) { verbose(env, "same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_ST) { if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { verbose(env, "BPF_ST uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); if (err) return err; } else if (class == BPF_JMP) { u8 opcode = BPF_OP(insn->code); if (opcode == BPF_CALL) { if (BPF_SRC(insn->code) != BPF_K || insn->off != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_CALL uses reserved fields\n"); return -EINVAL; } err = check_call(env, insn->imm, insn_idx); if (err) return err; } else if (opcode == BPF_JA) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_JA uses reserved fields\n"); return -EINVAL; } insn_idx += insn->off + 1; continue; } else if (opcode == BPF_EXIT) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_EXIT uses reserved fields\n"); return -EINVAL; } /* eBPF calling convetion is such that R0 is used * to return the value from eBPF program. * Make sure that it's readable at this time * of bpf_exit, which means that program wrote * something into it earlier */ err = check_reg_arg(env, BPF_REG_0, SRC_OP); if (err) return err; if (is_pointer_value(env, BPF_REG_0)) { verbose(env, "R0 leaks addr as return value\n"); return -EACCES; } err = check_return_code(env); if (err) return err; process_bpf_exit: err = pop_stack(env, &prev_insn_idx, &insn_idx); if (err < 0) { if (err != -ENOENT) return err; break; } else { do_print_state = true; continue; } } else { err = check_cond_jmp_op(env, insn, &insn_idx); if (err) return err; } } else if (class == BPF_LD) { u8 mode = BPF_MODE(insn->code); if (mode == BPF_ABS || mode == BPF_IND) { err = check_ld_abs(env, insn); if (err) return err; } else if (mode == BPF_IMM) { err = check_ld_imm(env, insn); if (err) return err; insn_idx++; env->insn_aux_data[insn_idx].seen = true; } else { verbose(env, "invalid BPF_LD mode\n"); return -EINVAL; } } else { verbose(env, "unknown insn class %d\n", class); return -EINVAL; } insn_idx++; } verbose(env, "processed %d insns, stack depth %d\n", insn_processed, env->prog->aux->stack_depth); return 0; } static int check_map_prealloc(struct bpf_map *map) { return (map->map_type != BPF_MAP_TYPE_HASH && map->map_type != BPF_MAP_TYPE_PERCPU_HASH && map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || !(map->map_flags & BPF_F_NO_PREALLOC); } static int check_map_prog_compatibility(struct bpf_verifier_env *env, struct bpf_map *map, struct bpf_prog *prog) { /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use * preallocated hash maps, since doing memory allocation * in overflow_handler can crash depending on where nmi got * triggered. */ if (prog->type == BPF_PROG_TYPE_PERF_EVENT) { if (!check_map_prealloc(map)) { verbose(env, "perf_event programs can only use preallocated hash map\n"); return -EINVAL; } if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta)) { verbose(env, "perf_event programs can only use preallocated inner hash map\n"); return -EINVAL; } } return 0; } /* look for pseudo eBPF instructions that access map FDs and * replace them with actual map pointers */ static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i, j, err; err = bpf_prog_calc_tag(env->prog); if (err) return err; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) == BPF_LDX && (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { verbose(env, "BPF_LDX uses reserved fields\n"); return -EINVAL; } if (BPF_CLASS(insn->code) == BPF_STX && ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { verbose(env, "BPF_STX uses reserved fields\n"); return -EINVAL; } if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { struct bpf_map *map; struct fd f; if (i == insn_cnt - 1 || insn[1].code != 0 || insn[1].dst_reg != 0 || insn[1].src_reg != 0 || insn[1].off != 0) { verbose(env, "invalid bpf_ld_imm64 insn\n"); return -EINVAL; } if (insn->src_reg == 0) /* valid generic load 64-bit imm */ goto next_insn; if (insn->src_reg != BPF_PSEUDO_MAP_FD) { verbose(env, "unrecognized bpf_ld_imm64 insn\n"); return -EINVAL; } f = fdget(insn->imm); map = __bpf_map_get(f); if (IS_ERR(map)) { verbose(env, "fd %d is not pointing to valid bpf_map\n", insn->imm); return PTR_ERR(map); } err = check_map_prog_compatibility(env, map, env->prog); if (err) { fdput(f); return err; } /* store map pointer inside BPF_LD_IMM64 instruction */ insn[0].imm = (u32) (unsigned long) map; insn[1].imm = ((u64) (unsigned long) map) >> 32; /* check whether we recorded this map already */ for (j = 0; j < env->used_map_cnt; j++) if (env->used_maps[j] == map) { fdput(f); goto next_insn; } if (env->used_map_cnt >= MAX_USED_MAPS) { fdput(f); return -E2BIG; } /* hold the map. If the program is rejected by verifier, * the map will be released by release_maps() or it * will be used by the valid program until it's unloaded * and all maps are released in free_bpf_prog_info() */ map = bpf_map_inc(map, false); if (IS_ERR(map)) { fdput(f); return PTR_ERR(map); } env->used_maps[env->used_map_cnt++] = map; fdput(f); next_insn: insn++; i++; } } /* now all pseudo BPF_LD_IMM64 instructions load valid * 'struct bpf_map *' into a register instead of user map_fd. * These pointers will be used later by verifier to validate map access. */ return 0; } /* drop refcnt of maps used by the rejected program */ static void release_maps(struct bpf_verifier_env *env) { int i; for (i = 0; i < env->used_map_cnt; i++) bpf_map_put(env->used_maps[i]); } /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i; for (i = 0; i < insn_cnt; i++, insn++) if (insn->code == (BPF_LD | BPF_IMM | BPF_DW)) insn->src_reg = 0; } /* single env->prog->insni[off] instruction was replaced with the range * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying * [0, off) and [off, end) to new locations, so the patched range stays zero */ static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; int i; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); for (i = off; i < off + cnt - 1; i++) new_data[i].seen = true; env->insn_aux_data = new_data; vfree(old_data); return 0; } static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, const struct bpf_insn *patch, u32 len) { struct bpf_prog *new_prog; new_prog = bpf_patch_insn_single(env->prog, off, patch, len); if (!new_prog) return NULL; if (adjust_insn_aux_data(env, new_prog->len, off, len)) return NULL; return new_prog; } /* The verifier does more data flow analysis than llvm and will not explore * branches that are dead at run time. Malicious programs can have dead code * too. Therefore replace all dead at-run-time code with nops. */ static void sanitize_dead_code(struct bpf_verifier_env *env) { struct bpf_insn_aux_data *aux_data = env->insn_aux_data; struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0); struct bpf_insn *insn = env->prog->insnsi; const int insn_cnt = env->prog->len; int i; for (i = 0; i < insn_cnt; i++) { if (aux_data[i].seen) continue; memcpy(insn + i, &nop, sizeof(nop)); } } /* convert load instructions that access fields of 'struct __sk_buff' * into sequence of instructions that access fields of 'struct sk_buff' */ static int convert_ctx_accesses(struct bpf_verifier_env *env) { const struct bpf_verifier_ops *ops = env->ops; int i, cnt, size, ctx_field_size, delta = 0; const int insn_cnt = env->prog->len; struct bpf_insn insn_buf[16], *insn; struct bpf_prog *new_prog; enum bpf_access_type type; bool is_narrower_load; u32 target_size; if (ops->gen_prologue) { cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, env->prog); if (cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } else if (cnt) { new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); if (!new_prog) return -ENOMEM; env->prog = new_prog; delta += cnt - 1; } } if (!ops->convert_ctx_access) return 0; insn = env->prog->insnsi + delta; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || insn->code == (BPF_LDX | BPF_MEM | BPF_H) || insn->code == (BPF_LDX | BPF_MEM | BPF_W) || insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) type = BPF_READ; else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || insn->code == (BPF_STX | BPF_MEM | BPF_H) || insn->code == (BPF_STX | BPF_MEM | BPF_W) || insn->code == (BPF_STX | BPF_MEM | BPF_DW)) type = BPF_WRITE; else continue; if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX) continue; ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; size = BPF_LDST_BYTES(insn); /* If the read access is a narrower load of the field, * convert to a 4/8-byte load, to minimum program type specific * convert_ctx_access changes. If conversion is successful, * we will apply proper mask to the result. */ is_narrower_load = size < ctx_field_size; if (is_narrower_load) { u32 off = insn->off; u8 size_code; if (type == BPF_WRITE) { verbose(env, "bpf verifier narrow ctx access misconfigured\n"); return -EINVAL; } size_code = BPF_H; if (ctx_field_size == 4) size_code = BPF_W; else if (ctx_field_size == 8) size_code = BPF_DW; insn->off = off & ~(ctx_field_size - 1); insn->code = BPF_LDX | BPF_MEM | size_code; } target_size = 0; cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog, &target_size); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || (ctx_field_size && !target_size)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } if (is_narrower_load && size < target_size) { if (ctx_field_size <= 4) insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, (1 << size * 8) - 1); else insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, (1 << size * 8) - 1); } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; /* keep walking new program and skip insns we just inserted */ env->prog = new_prog; insn = new_prog->insnsi + i + delta; } return 0; } /* fixup insn->imm field of bpf_call instructions * and inline eligible helpers as explicit sequence of BPF instructions * * this function is called after eBPF program passed verification */ static int fixup_bpf_calls(struct bpf_verifier_env *env) { struct bpf_prog *prog = env->prog; struct bpf_insn *insn = prog->insnsi; const struct bpf_func_proto *fn; const int insn_cnt = prog->len; struct bpf_insn insn_buf[16]; struct bpf_prog *new_prog; struct bpf_map *map_ptr; int i, cnt, delta = 0; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code != (BPF_JMP | BPF_CALL)) continue; if (insn->imm == BPF_FUNC_get_route_realm) prog->dst_needed = 1; if (insn->imm == BPF_FUNC_get_prandom_u32) bpf_user_rnd_init_once(); if (insn->imm == BPF_FUNC_tail_call) { /* If we tail call into other programs, we * cannot make any assumptions since they can * be replaced dynamically during runtime in * the program array. */ prog->cb_access = 1; env->prog->aux->stack_depth = MAX_BPF_STACK; /* mark bpf_tail_call as different opcode to avoid * conditional branch in the interpeter for every normal * call and to prevent accidental JITing by JIT compiler * that doesn't support bpf_tail_call yet */ insn->imm = 0; insn->code = BPF_JMP | BPF_TAIL_CALL; continue; } /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup * handlers are currently limited to 64 bit only. */ if (ebpf_jit_enabled() && BITS_PER_LONG == 64 && insn->imm == BPF_FUNC_map_lookup_elem) { map_ptr = env->insn_aux_data[i + delta].map_ptr; if (map_ptr == BPF_MAP_PTR_POISON || !map_ptr->ops->map_gen_lookup) goto patch_call_imm; cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; /* keep walking new program and skip insns we just inserted */ env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (insn->imm == BPF_FUNC_redirect_map) { /* Note, we cannot use prog directly as imm as subsequent * rewrites would still change the prog pointer. The only * stable address we can use is aux, which also works with * prog clones during blinding. */ u64 addr = (unsigned long)prog->aux; struct bpf_insn r4_ld[] = { BPF_LD_IMM64(BPF_REG_4, addr), *insn, }; cnt = ARRAY_SIZE(r4_ld); new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; } patch_call_imm: fn = env->ops->get_func_proto(insn->imm); /* all functions that have prototype and verifier allowed * programs to call them, must be real in-kernel functions */ if (!fn->func) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(insn->imm), insn->imm); return -EFAULT; } insn->imm = fn->func - __bpf_call_base; } return 0; } static void free_states(struct bpf_verifier_env *env) { struct bpf_verifier_state_list *sl, *sln; int i; if (!env->explored_states) return; for (i = 0; i < env->prog->len; i++) { sl = env->explored_states[i]; if (sl) while (sl != STATE_LIST_MARK) { sln = sl->next; free_verifier_state(&sl->state, false); kfree(sl); sl = sln; } } kfree(env->explored_states); } int bpf_check(struct bpf_prog **prog, union bpf_attr *attr) { struct bpf_verifier_env *env; struct bpf_verifer_log *log; int ret = -EINVAL; /* no program is valid */ if (ARRAY_SIZE(bpf_verifier_ops) == 0) return -EINVAL; /* 'struct bpf_verifier_env' can be global, but since it's not small, * allocate/free it every time bpf_check() is called */ env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); if (!env) return -ENOMEM; log = &env->log; env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) * (*prog)->len); ret = -ENOMEM; if (!env->insn_aux_data) goto err_free_env; env->prog = *prog; env->ops = bpf_verifier_ops[env->prog->type]; /* grab the mutex to protect few globals used by verifier */ mutex_lock(&bpf_verifier_lock); if (attr->log_level || attr->log_buf || attr->log_size) { /* user requested verbose verifier output * and supplied buffer to store the verification trace */ log->level = attr->log_level; log->ubuf = (char __user *) (unsigned long) attr->log_buf; log->len_total = attr->log_size; ret = -EINVAL; /* log attributes have to be sane */ if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 || !log->level || !log->ubuf) goto err_unlock; } env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) env->strict_alignment = true; if (env->prog->aux->offload) { ret = bpf_prog_offload_verifier_prep(env); if (ret) goto err_unlock; } ret = replace_map_fd_with_map_ptr(env); if (ret < 0) goto skip_full_check; env->explored_states = kcalloc(env->prog->len, sizeof(struct bpf_verifier_state_list *), GFP_USER); ret = -ENOMEM; if (!env->explored_states) goto skip_full_check; ret = check_cfg(env); if (ret < 0) goto skip_full_check; env->allow_ptr_leaks = capable(CAP_SYS_ADMIN); ret = do_check(env); if (env->cur_state) { free_verifier_state(env->cur_state, true); env->cur_state = NULL; } skip_full_check: while (!pop_stack(env, NULL, NULL)); free_states(env); if (ret == 0) sanitize_dead_code(env); if (ret == 0) /* program is valid, convert *(u32*)(ctx + off) accesses */ ret = convert_ctx_accesses(env); if (ret == 0) ret = fixup_bpf_calls(env); if (log->level && bpf_verifier_log_full(log)) ret = -ENOSPC; if (log->level && !log->ubuf) { ret = -EFAULT; goto err_release_maps; } if (ret == 0 && env->used_map_cnt) { /* if program passed verifier, update used_maps in bpf_prog_info */ env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, sizeof(env->used_maps[0]), GFP_KERNEL); if (!env->prog->aux->used_maps) { ret = -ENOMEM; goto err_release_maps; } memcpy(env->prog->aux->used_maps, env->used_maps, sizeof(env->used_maps[0]) * env->used_map_cnt); env->prog->aux->used_map_cnt = env->used_map_cnt; /* program is valid. Convert pseudo bpf_ld_imm64 into generic * bpf_ld_imm64 instructions */ convert_pseudo_ld_imm64(env); } err_release_maps: if (!env->prog->aux->used_maps) /* if we didn't copy map pointers into bpf_prog_info, release * them now. Otherwise free_bpf_prog_info() will release them. */ release_maps(env); *prog = env->prog; err_unlock: mutex_unlock(&bpf_verifier_lock); vfree(env->insn_aux_data); err_free_env: kfree(env); return ret; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2988_0
crossvul-cpp_data_bad_2365_0
/* hivex - Windows Registry "hive" extraction library. * Copyright (C) 2009-2011 Red Hat Inc. * Derived from code by Petter Nordahl-Hagen under a compatible license: * Copyright (c) 1997-2007 Petter Nordahl-Hagen. * Derived from code by Markus Stephany under a compatible license: * Copyright (c) 2000-2004, Markus Stephany. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library 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 * Lesser General Public License for more details. * * See file LICENSE for the full license. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <inttypes.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <errno.h> #include <assert.h> #ifdef HAVE_MMAP #include <sys/mman.h> #else /* On systems without mmap (and munmap), use a replacement function. */ #include "mmap.h" #endif #include "full-read.h" #include "full-write.h" #include "c-ctype.h" #include "hivex.h" #include "hivex-internal.h" static uint32_t header_checksum (const hive_h *h) { uint32_t *daddr = (uint32_t *) h->addr; size_t i; uint32_t sum = 0; for (i = 0; i < 0x1fc / 4; ++i) { sum ^= le32toh (*daddr); daddr++; } return sum; } #define HIVEX_OPEN_MSGLVL_MASK (HIVEX_OPEN_VERBOSE|HIVEX_OPEN_DEBUG) hive_h * hivex_open (const char *filename, int flags) { hive_h *h = NULL; assert (sizeof (struct ntreg_header) == 0x1000); assert (offsetof (struct ntreg_header, csum) == 0x1fc); h = calloc (1, sizeof *h); if (h == NULL) goto error; h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK; const char *debug = getenv ("HIVEX_DEBUG"); if (debug && STREQ (debug, "1")) h->msglvl = 2; DEBUG (2, "created handle %p", h); h->writable = !!(flags & HIVEX_OPEN_WRITE); h->filename = strdup (filename); if (h->filename == NULL) goto error; #ifdef O_CLOEXEC h->fd = open (filename, O_RDONLY | O_CLOEXEC | O_BINARY); #else h->fd = open (filename, O_RDONLY | O_BINARY); #endif if (h->fd == -1) goto error; #ifndef O_CLOEXEC fcntl (h->fd, F_SETFD, FD_CLOEXEC); #endif struct stat statbuf; if (fstat (h->fd, &statbuf) == -1) goto error; h->size = statbuf.st_size; if (h->size < 0x2000) { SET_ERRNO (EINVAL, "%s: file is too small to be a Windows NT Registry hive file", filename); goto error; } if (!h->writable) { h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0); if (h->addr == MAP_FAILED) goto error; DEBUG (2, "mapped file at %p", h->addr); } else { h->addr = malloc (h->size); if (h->addr == NULL) goto error; if (full_read (h->fd, h->addr, h->size) < h->size) goto error; /* We don't need the file descriptor along this path, since we * have read all the data. */ if (close (h->fd) == -1) goto error; h->fd = -1; } /* Check header. */ if (h->hdr->magic[0] != 'r' || h->hdr->magic[1] != 'e' || h->hdr->magic[2] != 'g' || h->hdr->magic[3] != 'f') { SET_ERRNO (ENOTSUP, "%s: not a Windows NT Registry hive file", filename); goto error; } /* Check major version. */ uint32_t major_ver = le32toh (h->hdr->major_ver); if (major_ver != 1) { SET_ERRNO (ENOTSUP, "%s: hive file major version %" PRIu32 " (expected 1)", filename, major_ver); goto error; } h->bitmap = calloc (1 + h->size / 32, 1); if (h->bitmap == NULL) goto error; /* Header checksum. */ uint32_t sum = header_checksum (h); if (sum != le32toh (h->hdr->csum)) { SET_ERRNO (EINVAL, "%s: bad checksum in hive header", filename); goto error; } /* Last modified time. */ h->last_modified = le64toh ((int64_t) h->hdr->last_modified); if (h->msglvl >= 2) { char *name = _hivex_windows_utf16_to_utf8 (h->hdr->name, 64); fprintf (stderr, "hivex_open: header fields:\n" " file version %" PRIu32 ".%" PRIu32 "\n" " sequence nos %" PRIu32 " %" PRIu32 "\n" " (sequences nos should match if hive was synched at shutdown)\n" " last modified %" PRIu64 "\n" " (Windows filetime, x 100 ns since 1601-01-01)\n" " original file name %s\n" " (only 32 chars are stored, name is probably truncated)\n" " root offset 0x%x + 0x1000\n" " end of last page 0x%x + 0x1000 (total file size 0x%zx)\n" " checksum 0x%x (calculated 0x%x)\n", major_ver, le32toh (h->hdr->minor_ver), le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2), h->last_modified, name ? name : "(conversion failed)", le32toh (h->hdr->offset), le32toh (h->hdr->blocks), h->size, le32toh (h->hdr->csum), sum); free (name); } h->rootoffs = le32toh (h->hdr->offset) + 0x1000; h->endpages = le32toh (h->hdr->blocks) + 0x1000; DEBUG (2, "root offset = 0x%zx", h->rootoffs); /* We'll set this flag when we see a block with the root offset (ie. * the root block). */ int seen_root_block = 0, bad_root_block = 0; /* Collect some stats. */ size_t pages = 0; /* Number of hbin pages read. */ size_t smallest_page = SIZE_MAX, largest_page = 0; size_t blocks = 0; /* Total number of blocks found. */ size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0; size_t used_blocks = 0; /* Total number of used blocks found. */ size_t used_size = 0; /* Total size (bytes) of used blocks. */ /* Read the pages and blocks. The aim here is to be robust against * corrupt or malicious registries. So we make sure the loops * always make forward progress. We add the address of each block * we read to a hash table so pointers will only reference the start * of valid blocks. */ size_t off; struct ntreg_hbin_page *page; for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) { if (off >= h->endpages) break; page = (struct ntreg_hbin_page *) ((char *) h->addr + off); if (page->magic[0] != 'h' || page->magic[1] != 'b' || page->magic[2] != 'i' || page->magic[3] != 'n') { SET_ERRNO (ENOTSUP, "%s: trailing garbage at end of file " "(at 0x%zx, after %zu pages)", filename, off, pages); goto error; } size_t page_size = le32toh (page->page_size); DEBUG (2, "page at 0x%zx, size %zu", off, page_size); pages++; if (page_size < smallest_page) smallest_page = page_size; if (page_size > largest_page) largest_page = page_size; if (page_size <= sizeof (struct ntreg_hbin_page) || (page_size & 0x0fff) != 0) { SET_ERRNO (ENOTSUP, "%s: page size %zu at 0x%zx, bad registry", filename, page_size, off); goto error; } /* Read the blocks in this page. */ size_t blkoff; struct ntreg_hbin_block *block; size_t seg_len; for (blkoff = off + 0x20; blkoff < off + page_size; blkoff += seg_len) { blocks++; int is_root = blkoff == h->rootoffs; if (is_root) seen_root_block = 1; block = (struct ntreg_hbin_block *) ((char *) h->addr + blkoff); int used; seg_len = block_len (h, blkoff, &used); if (seg_len <= 4 || (seg_len & 3) != 0) { SET_ERRNO (ENOTSUP, "%s: block size %" PRIu32 " at 0x%zx, bad registry", filename, le32toh (block->seg_len), blkoff); goto error; } if (h->msglvl >= 2) { unsigned char *id = (unsigned char *) block->id; int id0 = id[0], id1 = id[1]; fprintf (stderr, "%s: %s: " "%s block id %d,%d (%c%c) at 0x%zx size %zu%s\n", "hivex", __func__, used ? "used" : "free", id0, id1, c_isprint (id0) ? id0 : '.', c_isprint (id1) ? id1 : '.', blkoff, seg_len, is_root ? " (root)" : ""); } blocks_bytes += seg_len; if (seg_len < smallest_block) smallest_block = seg_len; if (seg_len > largest_block) largest_block = seg_len; if (is_root && !used) bad_root_block = 1; if (used) { used_blocks++; used_size += seg_len; /* Root block must be an nk-block. */ if (is_root && (block->id[0] != 'n' || block->id[1] != 'k')) bad_root_block = 1; /* Note this blkoff is a valid address. */ BITMAP_SET (h->bitmap, blkoff); } } } if (!seen_root_block) { SET_ERRNO (ENOTSUP, "%s: no root block found", filename); goto error; } if (bad_root_block) { SET_ERRNO (ENOTSUP, "%s: bad root block (free or not nk)", filename); goto error; } DEBUG (1, "successfully read Windows Registry hive file:\n" " pages: %zu [sml: %zu, lge: %zu]\n" " blocks: %zu [sml: %zu, avg: %zu, lge: %zu]\n" " blocks used: %zu\n" " bytes used: %zu", pages, smallest_page, largest_page, blocks, smallest_block, blocks_bytes / blocks, largest_block, used_blocks, used_size); return h; error:; int err = errno; if (h) { free (h->bitmap); if (h->addr && h->size && h->addr != MAP_FAILED) { if (!h->writable) munmap (h->addr, h->size); else free (h->addr); } if (h->fd >= 0) close (h->fd); free (h->filename); free (h); } errno = err; return NULL; } int hivex_close (hive_h *h) { int r; DEBUG (1, "hivex_close"); free (h->bitmap); if (!h->writable) munmap (h->addr, h->size); else free (h->addr); if (h->fd >= 0) r = close (h->fd); else r = 0; free (h->filename); free (h); return r; } int hivex_commit (hive_h *h, const char *filename, int flags) { int fd; if (flags != 0) { SET_ERRNO (EINVAL, "flags != 0"); return -1; } CHECK_WRITABLE (-1); filename = filename ? : h->filename; #ifdef O_CLOEXEC fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY|O_CLOEXEC|O_BINARY, 0666); #else fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY|O_BINARY, 0666); #endif if (fd == -1) return -1; #ifndef O_CLOEXEC fcntl (fd, F_SETFD, FD_CLOEXEC); #endif /* Update the header fields. */ uint32_t sequence = le32toh (h->hdr->sequence1); sequence++; h->hdr->sequence1 = htole32 (sequence); h->hdr->sequence2 = htole32 (sequence); /* XXX Ought to update h->hdr->last_modified. */ h->hdr->blocks = htole32 (h->endpages - 0x1000); /* Recompute header checksum. */ uint32_t sum = header_checksum (h); h->hdr->csum = htole32 (sum); DEBUG (2, "hivex_commit: new header checksum: 0x%x", sum); if (full_write (fd, h->addr, h->size) != h->size) { int err = errno; close (fd); errno = err; return -1; } if (close (fd) == -1) return -1; return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2365_0
crossvul-cpp_data_bad_395_1
/* Copyright 1996-2013 Han The Thanh <thanh@pdftex.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "dvips.h" /* * The external declarations: */ #include "protos.h" #include "ptexmac.h" #undef fm_extend #define fm_extend(f) 0 #undef fm_slant #define fm_slant(f) 0 #undef is_reencoded #define is_reencoded(f) (cur_enc_name != NULL) #undef is_subsetted #define is_subsetted(f) true #undef is_included #define is_included(f) true #undef set_cur_file_name #define set_cur_file_name(s) cur_file_name = s #define external_enc() ext_glyph_names #define full_file_name() cur_file_name #define is_used_char(c) (grid[c] == 1) #define end_last_eexec_line() \ hexline_length = HEXLINE_WIDTH; \ end_hexline(); \ t1_eexec_encrypt = false #define t1_scan_only() #define t1_scan_keys() #define embed_all_glyphs(tex_font) false #undef pdfmovechars #ifdef SHIFTLOWCHARS #define pdfmovechars shiftlowchars #define t1_char(c) T1Char(c) #else /* SHIFTLOWCHARS */ #define t1_char(c) c #define pdfmovechars 0 #endif /* SHIFTLOWCHARS */ #define extra_charset() dvips_extra_charset #define make_subset_tag(a, b) #define update_subset_tag() static char *dvips_extra_charset; static char *cur_file_name; static char *cur_enc_name; static unsigned char *grid; static char *ext_glyph_names[256]; static char print_buf[PRINTF_BUF_SIZE]; static int hexline_length; static char notdef[] = ".notdef"; static size_t last_ptr_index; #include <stdarg.h> #define t1_log(str) #define get_length1() #define get_length2() #define get_length3() #define save_offset() #define t1_open() \ ((t1_file = search(type1path, cur_file_name, FOPEN_RBIN_MODE)) != NULL) #define t1_close() xfclose(t1_file, cur_file_name) #define t1_getchar() getc(t1_file) #define t1_putchar(c) fputc(c, bitfile) #define t1_ungetchar(c) ungetc(c, t1_file) #define t1_eof() feof(t1_file) #define str_prefix(s1, s2) (strncmp(s1, s2, strlen(s2)) == 0) #define t1_prefix(s) str_prefix(t1_line_array, s) #define t1_buf_prefix(s) str_prefix(t1_buf_array, s) #define t1_suffix(s) str_suffix(t1_line_array, t1_line_ptr, s) #define t1_buf_suffix(s) str_suffix(t1_buf_array, t1_buf_ptr, s) #define t1_charstrings() strstr(t1_line_array, charstringname) #define t1_subrs() t1_prefix("/Subrs") #define t1_end_eexec() t1_suffix("mark currentfile closefile") #define t1_cleartomark() t1_prefix("cleartomark") #define enc_open() \ ((enc_file = search(encpath, cur_file_name, FOPEN_RBIN_MODE)) != NULL) #define enc_close() xfclose(enc_file, cur_file_name) #define enc_getchar() getc(enc_file) #define enc_eof() feof(enc_file) #define valid_code(c) (c >= 0 && c < 256) #define fixedcontent true /* false for pdfTeX, true for dvips */ static const char *standard_glyph_names[256] = { /* 0x00 */ notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, /* 0x10 */ notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, /* 0x20 */ "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", /* 0x30 */ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", /* 0x40 */ "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", /* 0x50 */ "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", /* 0x60 */ "quoteleft", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", /* 0x70 */ "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", notdef, /* 0x80 */ notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, /* 0x90 */ notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, /* 0xa0 */ notdef, "exclamdown", "cent", "sterling", "fraction", "yen", "florin", "section", "currency", "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi", "fl", /* 0xb0 */ notdef, "endash", "dagger", "daggerdbl", "periodcentered", notdef, "paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright", "guillemotright", "ellipsis", "perthousand", notdef, "questiondown", /* 0xc0 */ notdef, "grave", "acute", "circumflex", "tilde", "macron", "breve", "dotaccent", "dieresis", notdef, "ring", "cedilla", notdef, "hungarumlaut", "ogonek", "caron", /* 0xd0 */ "emdash", notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, /* 0xe0 */ notdef, "AE", notdef, "ordfeminine", notdef, notdef, notdef, notdef, "Lslash", "Oslash", "OE", "ordmasculine", notdef, notdef, notdef, notdef, /* 0xf0 */ notdef, "ae", notdef, notdef, notdef, "dotlessi", notdef, notdef, "lslash", "oslash", "oe", "germandbls", notdef, notdef, notdef, notdef }; char **t1_glyph_names; char *t1_builtin_glyph_names[256]; static boolean read_encoding_only; static char charstringname[] = "/CharStrings"; enum { ENC_STANDARD, ENC_BUILTIN } t1_encoding; #define T1_BUF_SIZE 0x10 #define ENC_BUF_SIZE 0x1000 #define CS_HSTEM 1 #define CS_VSTEM 3 #define CS_VMOVETO 4 #define CS_RLINETO 5 #define CS_HLINETO 6 #define CS_VLINETO 7 #define CS_RRCURVETO 8 #define CS_CLOSEPATH 9 #define CS_CALLSUBR 10 #define CS_RETURN 11 #define CS_ESCAPE 12 #define CS_HSBW 13 #define CS_ENDCHAR 14 #define CS_RMOVETO 21 #define CS_HMOVETO 22 #define CS_VHCURVETO 30 #define CS_HVCURVETO 31 #define CS_1BYTE_MAX (CS_HVCURVETO + 1) #define CS_DOTSECTION CS_1BYTE_MAX + 0 #define CS_VSTEM3 CS_1BYTE_MAX + 1 #define CS_HSTEM3 CS_1BYTE_MAX + 2 #define CS_SEAC CS_1BYTE_MAX + 6 #define CS_SBW CS_1BYTE_MAX + 7 #define CS_DIV CS_1BYTE_MAX + 12 #define CS_CALLOTHERSUBR CS_1BYTE_MAX + 16 #define CS_POP CS_1BYTE_MAX + 17 #define CS_SETCURRENTPOINT CS_1BYTE_MAX + 33 #define CS_2BYTE_MAX (CS_SETCURRENTPOINT + 1) #define CS_MAX CS_2BYTE_MAX typedef unsigned char byte; typedef struct { byte nargs; /* number of arguments */ boolean bottom; /* take arguments from bottom of stack? */ boolean clear; /* clear stack? */ boolean valid; } cc_entry; /* CharString Command */ typedef struct { char *name; /* glyph name (or notdef for Subrs entry) */ byte *data; unsigned short len; /* length of the whole string */ unsigned short cslen; /* length of the encoded part of the string */ boolean used; boolean valid; } cs_entry; static unsigned short t1_dr, t1_er; static const unsigned short t1_c1 = 52845, t1_c2 = 22719; static unsigned short t1_cslen; static short t1_lenIV; static char enc_line[ENC_BUF_SIZE]; /* define t1_line_ptr, t1_line_array & t1_line_limit */ typedef char t1_line_entry; define_array(t1_line); /* define t1_buf_ptr, t1_buf_array & t1_buf_limit */ typedef char t1_buf_entry; define_array(t1_buf); static int cs_start; static cs_entry *cs_tab, *cs_ptr, *cs_notdef; static char *cs_dict_start, *cs_dict_end; static int cs_count, cs_size, cs_size_pos; static cs_entry *subr_tab; static char *subr_array_start, *subr_array_end; static int subr_max, subr_size, subr_size_pos; /* This list contains the begin/end tokens commonly used in the */ /* /Subrs array of a Type 1 font. */ static const char *cs_token_pairs_list[][2] = { {" RD", "NP"}, {" -|", "|"}, {" RD", "noaccess put"}, {" -|", "noaccess put"}, {NULL, NULL} }; static const char **cs_token_pair; static boolean t1_pfa, t1_cs, t1_scan, t1_eexec_encrypt, t1_synthetic; static int t1_in_eexec; /* 0 before eexec-encrypted, 1 during, 2 after */ static long t1_block_length; static int last_hexbyte; static FILE *t1_file; static FILE *enc_file; static void pdftex_fail(const char *fmt, ...) { va_list args; va_start(args, fmt); fputs("\nError: module writet1", stderr); if (cur_file_name) fprintf(stderr, " (file %s)", cur_file_name); fputs(": ", stderr); vsprintf(print_buf, fmt, args); fputs(print_buf, stderr); fputs("\n ==> Fatal error occurred, the output PS file is not finished!\n", stderr); va_end(args); exit(-1); } static void pdftex_warn(const char *fmt, ...) { va_list args; va_start(args, fmt); fputs("\nWarning: module writet1 of dvips", stderr); if (cur_file_name) fprintf(stderr, " (file %s)", cur_file_name); fputs(": ", stderr); vsprintf(print_buf, fmt, args); fputs(print_buf, stderr); fputs("\n", stderr); va_end(args); } #define HEXLINE_WIDTH 64 static void end_hexline(void) { if (hexline_length == HEXLINE_WIDTH) { fputs("\n", bitfile); hexline_length = 0; } } static void t1_outhex(byte b) { static const char *hexdigits = "0123456789ABCDEF"; t1_putchar(hexdigits[b/16]); t1_putchar(hexdigits[b%16]); hexline_length += 2; end_hexline(); } static void enc_getline(void) { char *p; int c; restart: if (enc_eof()) pdftex_fail("unexpected end of file"); p = enc_line; do { c = enc_getchar(); append_char_to_buf(c, p, enc_line, ENC_BUF_SIZE); } while (c != 10); append_eol(p, enc_line, ENC_BUF_SIZE); if (p - enc_line < 2 || *enc_line == '%') goto restart; } /* read encoding from .enc file, return glyph_names array, or pdffail() */ char **load_enc_file(char *enc_name) { char buf[ENC_BUF_SIZE], *p, *r; int i, names_count; char **glyph_names; set_cur_file_name(enc_name); glyph_names = (char **) mymalloc(256 * sizeof(char *)); for (i = 0; i < 256; i++) glyph_names[i] = notdef; if (!enc_open()) { pdftex_warn("cannot open encoding file for reading"); cur_file_name = NULL; return glyph_names; } t1_log("{"); t1_log(cur_file_name = full_file_name()); enc_getline(); if (*enc_line != '/' || (r = strchr(enc_line, '[')) == NULL) { remove_eol(r, enc_line); pdftex_fail ("invalid encoding vector (a name or `[' missing): `%s'", enc_line); } names_count = 0; r++; /* skip '[' */ skip(r, ' '); for (;;) { while (*r == '/') { for (p = buf, r++; *r != ' ' && *r != 10 && *r != ']' && *r != '/'; *p++ = *r++); *p = 0; skip(r, ' '); if (names_count > 255) pdftex_fail("encoding vector contains more than 256 names"); if (strcmp(buf, notdef) != 0) glyph_names[names_count] = xstrdup(buf); names_count++; } if (*r != 10 && *r != '%') { if (str_prefix(r, "] def")) goto done; else { remove_eol(r, enc_line); pdftex_fail ("invalid encoding vector: a name or `] def' expected: `%s'", enc_line); } } enc_getline(); r = enc_line; } done: enc_close(); t1_log("}"); cur_file_name = NULL; return glyph_names; } static void t1_check_pfa(void) { const int c = t1_getchar(); t1_pfa = (c != 128) ? true : false; t1_ungetchar(c); } static int t1_getbyte(void) { int c = t1_getchar(); if (t1_pfa) return c; if (t1_block_length == 0) { if (c != 128) pdftex_fail("invalid marker"); c = t1_getchar(); if (c == 3) { while (!t1_eof()) t1_getchar(); return EOF; } t1_block_length = t1_getchar() & 0xff; t1_block_length |= (t1_getchar() & 0xff) << 8; t1_block_length |= (t1_getchar() & 0xff) << 16; t1_block_length |= (t1_getchar() & 0xff) << 24; c = t1_getchar(); } t1_block_length--; return c; } static int hexval(int c) { if (c >= 'A' && c <= 'F') return c - 'A' + 10; else if (c >= 'a' && c <= 'f') return c - 'a' + 10; else if (c >= '0' && c <= '9') return c - '0'; else return -1; } static byte edecrypt(byte cipher) { byte plain; if (t1_pfa) { while (cipher == 10 || cipher == 13) cipher = t1_getbyte(); last_hexbyte = cipher = (hexval(cipher) << 4) + hexval(t1_getbyte()); } plain = (cipher ^ (t1_dr >> 8)); t1_dr = (cipher + t1_dr) * t1_c1 + t1_c2; return plain; } static byte cdecrypt(byte cipher, unsigned short *cr) { const byte plain = (cipher ^ (*cr >> 8)); *cr = (cipher + *cr) * t1_c1 + t1_c2; return plain; } static byte eencrypt(byte plain) { const byte cipher = (plain ^ (t1_er >> 8)); t1_er = (cipher + t1_er) * t1_c1 + t1_c2; return cipher; } static byte cencrypt(byte plain, unsigned short *cr) { const byte cipher = (plain ^ (*cr >> 8)); *cr = (cipher + *cr) * t1_c1 + t1_c2; return cipher; } static char *eol(char *s) { char *p = strend(s); if (p - s > 1 && p[-1] != 10) { *p++ = 10; *p = 0; } return p; } static float t1_scan_num(char *p, char **r) { float f; skip(p, ' '); if (sscanf(p, "%g", &f) != 1) { remove_eol(p, t1_line_array); pdftex_fail("a number expected: `%s'", t1_line_array); } if (r != NULL) { for (; isdigit((unsigned char)*p) || *p == '.' || *p == 'e' || *p == 'E' || *p == '+' || *p == '-'; p++); *r = p; } return f; } static boolean str_suffix(const char *begin_buf, const char *end_buf, const char *s) { const char *s1 = end_buf - 1, *s2 = strend(s) - 1; if (*s1 == 10) s1--; while (s1 >= begin_buf && s2 >= s) { if (*s1-- != *s2--) return false; } return s2 < s; } static void t1_getline(void) { int c, l, eexec_scan; char *p; static const char eexec_str[] = "currentfile eexec"; static int eexec_len = 17; /* strlen(eexec_str) */ restart: if (t1_eof()) pdftex_fail("unexpected end of file"); t1_line_ptr = t1_line_array; alloc_array(t1_line, 1, T1_BUF_SIZE); t1_cslen = 0; eexec_scan = 0; c = t1_getbyte(); if (c == EOF) goto exit; while (!t1_eof()) { if (t1_in_eexec == 1) c = edecrypt((byte)c); alloc_array(t1_line, 1, T1_BUF_SIZE); append_char_to_buf(c, t1_line_ptr, t1_line_array, t1_line_limit); if (t1_in_eexec == 0 && eexec_scan >= 0 && eexec_scan < eexec_len) { if (t1_line_array[eexec_scan] == eexec_str[eexec_scan]) eexec_scan++; else eexec_scan = -1; } if (c == 10 || (t1_pfa && eexec_scan == eexec_len && c == 32)) break; if (t1_cs && t1_cslen == 0 && (t1_line_ptr - t1_line_array > 4) && (t1_suffix(" RD ") || t1_suffix(" -| "))) { p = t1_line_ptr - 5; while (*p != ' ') p--; t1_cslen = l = t1_scan_num(p + 1, 0); cs_start = t1_line_ptr - t1_line_array; /* cs_start is an index now */ alloc_array(t1_line, l, T1_BUF_SIZE); while (l-- > 0) *t1_line_ptr++ = edecrypt((byte)t1_getbyte()); } c = t1_getbyte(); } alloc_array(t1_line, 2, T1_BUF_SIZE); /* append_eol can append 2 chars */ append_eol(t1_line_ptr, t1_line_array, t1_line_limit); if (t1_line_ptr - t1_line_array < 2) goto restart; if (eexec_scan == eexec_len) t1_in_eexec = 1; exit: /* ensure that t1_buf_array has as much room as t1_line_array */ t1_buf_ptr = t1_buf_array; alloc_array(t1_buf, t1_line_limit, t1_line_limit); } static void t1_putline(void) { char *p = t1_line_array; if (t1_line_ptr - t1_line_array <= 1) return; if (t1_eexec_encrypt) { while (p < t1_line_ptr) t1_outhex(eencrypt(*p++)); /* dvips outputs hex, unlike pdftex */ } else while (p < t1_line_ptr) t1_putchar(*p++); } static void t1_puts(const char *s) { if (s != t1_line_array) strcpy(t1_line_array, s); t1_line_ptr = strend(t1_line_array); t1_putline(); } static void t1_printf(const char *fmt, ...) { va_list args; va_start(args, fmt); vsprintf(t1_line_array, fmt, args); t1_puts(t1_line_array); va_end(args); } static void t1_init_params(const char *open_name_prefix) { t1_log(open_name_prefix); t1_log(cur_file_name); t1_lenIV = 4; t1_dr = 55665; t1_er = 55665; t1_in_eexec = 0; t1_cs = false; t1_scan = true; t1_synthetic = false; t1_eexec_encrypt = false; t1_block_length = 0; t1_check_pfa(); } static void t1_close_font_file(const char *close_name_suffix) { t1_log(close_name_suffix); t1_close(); cur_file_name = NULL; } static void t1_check_block_len(boolean decrypt) { int l, c; if (t1_block_length == 0) return; c = t1_getbyte(); if (decrypt) c = edecrypt((byte)c); l = t1_block_length; if (!(l == 0 && (c == 10 || c == 13))) { pdftex_warn("%i bytes more than expected were ignored", l + 1); while (l-- > 0) t1_getbyte(); } } static void t1_start_eexec(void) { int i; if (is_included(fm_cur)) { get_length1(); save_offset(); } if (!t1_pfa) t1_check_block_len(false); for (t1_line_ptr = t1_line_array, i = 0; i < 4; i++) { edecrypt((byte)t1_getbyte()); *t1_line_ptr++ = 0; } t1_eexec_encrypt = true; if (is_included(fm_cur)) t1_putline(); /* to put the first four bytes */ } static void t1_stop_eexec(void) { int c; if (is_included(fm_cur)) { get_length2(); save_offset(); } end_last_eexec_line(); if (!t1_pfa) t1_check_block_len(true); else { c = edecrypt((byte)t1_getbyte()); if (!(c == 10 || c == 13)) { if (last_hexbyte == 0) t1_puts("00"); else pdftex_warn("unexpected data after eexec"); } } t1_cs = false; t1_in_eexec = 2; } static void t1_scan_param(void) { static const char *lenIV = "/lenIV"; if (!t1_scan || *t1_line_array != '/') return; if (t1_prefix(lenIV)) { t1_lenIV = t1_scan_num(t1_line_array + strlen(lenIV), 0); if (t1_lenIV < 0) pdftex_fail("negative value of lenIV is not supported"); return; } t1_scan_keys(); } static void copy_glyph_names(char **glyph_names, int a, int b) { if (glyph_names[b] != notdef) { xfree(glyph_names[b]); glyph_names[b] = notdef; } if (glyph_names[a] != notdef) { glyph_names[b] = xstrdup(glyph_names[a]); } } /* read encoding from Type1 font file, return glyph_names array, or pdffail() */ static char **t1_builtin_enc(void) { int i, a, b, c, counter = 0; char *r, *p, **glyph_names; /* At this moment "/Encoding" is the prefix of t1_line_array */ glyph_names = t1_builtin_glyph_names; for (i = 0; i < 256; i++) glyph_names[i] = notdef; if (t1_suffix("def")) { /* predefined encoding */ if (sscanf(t1_line_array + strlen("/Encoding"), "%255s", t1_buf_array) == 1 && strcmp(t1_buf_array, "StandardEncoding") == 0) { t1_encoding = ENC_STANDARD; for (i = 0; i < 256; i++) { if (standard_glyph_names[i] != notdef) glyph_names[i] = xstrdup(standard_glyph_names[i]); } return glyph_names; } pdftex_fail("cannot subset font (unknown predefined encoding `%s')", t1_buf_array); } /* At this moment "/Encoding" is the prefix of t1_line_array, and the encoding is * not a predefined encoding. * * We have two possible forms of Encoding vector. The first case is * * /Encoding [/a /b /c...] readonly def * * and the second case can look like * * /Encoding 256 array 0 1 255 {1 index exch /.notdef put} for * dup 0 /x put * dup 1 /y put * ... * readonly def */ t1_encoding = ENC_BUILTIN; if (t1_prefix("/Encoding [") || t1_prefix("/Encoding[")) { /* the first case */ r = strchr(t1_line_array, '[') + 1; skip(r, ' '); for (;;) { while (*r == '/') { for (p = t1_buf_array, r++; *r != 32 && *r != 10 && *r != ']' && *r != '/'; *p++ = *r++); *p = 0; skip(r, ' '); if (counter > 255) pdftex_fail("encoding vector contains more than 256 names"); if (strcmp(t1_buf_array, notdef) != 0) glyph_names[counter] = xstrdup(t1_buf_array); counter++; } if (*r != 10 && *r != '%') { if (str_prefix(r, "] def") || str_prefix(r, "] readonly def")) break; else { remove_eol(r, t1_line_array); pdftex_fail ("a name or `] def' or `] readonly def' expected: `%s'", t1_line_array); } } t1_getline(); r = t1_line_array; } } else { /* the second case */ p = strchr(t1_line_array, 10); for (;;) { if (*p == 10) { t1_getline(); p = t1_line_array; } /* check for `dup <index> <glyph> put' */ if (sscanf(p, "dup %i%255s put", &i, t1_buf_array) == 2 && *t1_buf_array == '/' && valid_code(i)) { if (strcmp(t1_buf_array + 1, notdef) != 0) glyph_names[i] = xstrdup(t1_buf_array + 1); p = strstr(p, " put") + strlen(" put"); skip(p, ' '); } /* check for `dup dup <to> exch <from> get put' */ else if (sscanf(p, "dup dup %i exch %i get put", &b, &a) == 2 && valid_code(a) && valid_code(b)) { copy_glyph_names(glyph_names, a, b); p = strstr(p, " get put") + strlen(" get put"); skip(p, ' '); } /* check for `dup dup <from> <size> getinterval <to> exch putinterval' */ else if (sscanf(p, "dup dup %i %i getinterval %i exch putinterval", &a, &c, &b) == 3 && valid_code(a) && valid_code(b) && valid_code(c)) { for (i = 0; i < c; i++) copy_glyph_names(glyph_names, a + i, b + i); p = strstr(p, " putinterval") + strlen(" putinterval"); skip(p, ' '); } /* check for `def' or `readonly def' */ else if ((p == t1_line_array || (p > t1_line_array && p[-1] == ' ')) && strcmp(p, "def\n") == 0) return glyph_names; /* skip an unrecognizable word */ else { while (*p != ' ' && *p != 10) p++; skip(p, ' '); } } } return glyph_names; } static void t1_check_end(void) { if (t1_eof()) return; t1_getline(); if (t1_prefix("{restore}")) t1_putline(); } static boolean t1_open_fontfile(const char *open_name_prefix) { if (!t1_open()) { char *msg = concat ("! Couldn't find font file ", cur_file_name); error(msg); } t1_init_params(open_name_prefix); return true; /* font file found */ } #define t1_include() #define check_subr(subr) \ if (subr >= subr_size || subr < 0) \ pdftex_fail("Subrs array: entry index out of range (%i)", subr); static const char **check_cs_token_pair(void) { const char **p = (const char **) cs_token_pairs_list; for (; p[0] != NULL; ++p) if (t1_buf_prefix(p[0]) && t1_buf_suffix(p[1])) return p; return NULL; } static void cs_store(boolean is_subr) { char *p; cs_entry *ptr; int subr; for (p = t1_line_array, t1_buf_ptr = t1_buf_array; *p != ' '; *t1_buf_ptr++ = *p++); *t1_buf_ptr = 0; if (is_subr) { subr = t1_scan_num(p + 1, 0); check_subr(subr); ptr = subr_tab + subr; } else { ptr = cs_ptr++; if (cs_ptr - cs_tab > cs_size) pdftex_fail ("CharStrings dict: more entries than dict size (%i)", cs_size); if (strcmp(t1_buf_array + 1, notdef) == 0) /* skip the slash */ ptr->name = notdef; else ptr->name = xstrdup(t1_buf_array + 1); } /* copy " RD " + cs data to t1_buf_array */ memcpy(t1_buf_array, t1_line_array + cs_start - 4, (unsigned) (t1_cslen + 4)); /* copy the end of cs data to t1_buf_array */ for (p = t1_line_array + cs_start + t1_cslen, t1_buf_ptr = t1_buf_array + t1_cslen + 4; *p != 10; *t1_buf_ptr++ = *p++); *t1_buf_ptr++ = 10; if (is_subr && cs_token_pair == NULL) cs_token_pair = check_cs_token_pair(); ptr->len = t1_buf_ptr - t1_buf_array; ptr->cslen = t1_cslen; ptr->data = xtalloc(ptr->len, byte); memcpy(ptr->data, t1_buf_array, ptr->len); ptr->valid = true; } #define store_subr() cs_store(true) #define store_cs() cs_store(false) #define CC_STACK_SIZE 24 static integer cc_stack[CC_STACK_SIZE], *stack_ptr = cc_stack; static cc_entry cc_tab[CS_MAX]; static boolean is_cc_init = false; #define cc_pop(N) \ if (stack_ptr - cc_stack < (N)) \ stack_error(N); \ stack_ptr -= N #define stack_error(N) { \ pdftex_fail("CharString: invalid access (%i) to stack (%i entries)", \ (int) N, (int)(stack_ptr - cc_stack)); \ goto cs_error; \ } /* static integer cc_get(integer index) { if (index < 0) { if (stack_ptr + index < cc_stack ) stack_error(stack_ptr - cc_stack + index); return *(stack_ptr + index); } else { if (cc_stack + index >= stack_ptr) stack_error(index); return cc_stack[index]; } } */ #define cc_get(N) ((N) < 0 ? *(stack_ptr + (N)) : *(cc_stack + (N))) #define cc_push(V) *stack_ptr++ = V #define cc_clear() stack_ptr = cc_stack #define set_cc(N, B, A, C) \ cc_tab[N].nargs = A; \ cc_tab[N].bottom = B; \ cc_tab[N].clear = C; \ cc_tab[N].valid = true static void cc_init(void) { int i; if (is_cc_init) return; for (i = 0; i < CS_MAX; i++) cc_tab[i].valid = false; set_cc(CS_HSTEM, true, 2, true); set_cc(CS_VSTEM, true, 2, true); set_cc(CS_VMOVETO, true, 1, true); set_cc(CS_RLINETO, true, 2, true); set_cc(CS_HLINETO, true, 1, true); set_cc(CS_VLINETO, true, 1, true); set_cc(CS_RRCURVETO, true, 6, true); set_cc(CS_CLOSEPATH, false, 0, true); set_cc(CS_CALLSUBR, false, 1, false); set_cc(CS_RETURN, false, 0, false); /* set_cc(CS_ESCAPE, false, 0, false); */ set_cc(CS_HSBW, true, 2, true); set_cc(CS_ENDCHAR, false, 0, true); set_cc(CS_RMOVETO, true, 2, true); set_cc(CS_HMOVETO, true, 1, true); set_cc(CS_VHCURVETO, true, 4, true); set_cc(CS_HVCURVETO, true, 4, true); set_cc(CS_DOTSECTION, false, 0, true); set_cc(CS_VSTEM3, true, 6, true); set_cc(CS_HSTEM3, true, 6, true); set_cc(CS_SEAC, true, 5, true); set_cc(CS_SBW, true, 4, true); set_cc(CS_DIV, false, 2, false); set_cc(CS_CALLOTHERSUBR, false, 0, false); set_cc(CS_POP, false, 0, false); set_cc(CS_SETCURRENTPOINT, true, 2, true); is_cc_init = true; } #define cs_getchar() cdecrypt(*data++, &cr) #define mark_subr(n) cs_mark(0, n) #define mark_cs(s) cs_mark(s, 0) static void cs_fail(const char *cs_name, int subr, const char *fmt, ...) { char buf[SMALL_BUF_SIZE]; va_list args; va_start(args, fmt); vsprintf(buf, fmt, args); va_end(args); if (cs_name == NULL) pdftex_warn("Subr (%i): %s", (int) subr, buf); else pdftex_warn("CharString (/%s): %s", cs_name, buf); } /* fix a return-less subr by appending CS_RETURN */ static void append_cs_return(cs_entry *ptr) { unsigned short cr; int i; byte *p, *q, *data, *new_data; assert(ptr != NULL && ptr->valid && ptr->used); /* decrypt the cs data to t1_buf_array, append CS_RETURN */ p = (byte *) t1_buf_array; data = ptr->data + 4; cr = 4330; for (i = 0; i < ptr->cslen; i++) *p++ = cs_getchar(); *p = CS_RETURN; /* encrypt the new cs data to new_data */ new_data = xtalloc(ptr->len + 1, byte); memcpy(new_data, ptr->data, 4); p = new_data + 4; q = (byte *) t1_buf_array; cr = 4330; for (i = 0; i < ptr->cslen + 1; i++) *p++ = cencrypt(*q++, &cr); memcpy(p, ptr->data + 4 + ptr->cslen, ptr->len - ptr->cslen - 4); /* update *ptr */ xfree(ptr->data); ptr->data = new_data; ptr->len++; ptr->cslen++; } static void cs_mark(const char *cs_name, int subr) { byte *data; int i, b, cs_len; int last_cmd = 0; integer a, a1, a2; unsigned short cr; static integer lastargOtherSubr3 = 3; /* the argument of last call to OtherSubrs[3] */ cs_entry *ptr; cc_entry *cc; if (cs_name == NULL) { check_subr(subr); ptr = subr_tab + subr; if (!ptr->valid) return; } else { if (cs_notdef != NULL && (cs_name == notdef || strcmp(cs_name, notdef) == 0)) ptr = cs_notdef; else { for (ptr = cs_tab; ptr < cs_ptr; ptr++) if (strcmp(ptr->name, cs_name) == 0) break; if (ptr == cs_ptr) { pdftex_warn("glyph `%s' undefined", cs_name); return; } if (ptr->name == notdef) cs_notdef = ptr; } } /* only marked CharString entries and invalid entries can be skipped; valid marked subrs must be parsed to keep the stack in sync */ if (!ptr->valid || (ptr->used && cs_name != NULL)) return; ptr->used = true; cr = 4330; cs_len = ptr->cslen; data = ptr->data + 4; for (i = 0; i < t1_lenIV; i++, cs_len--) cs_getchar(); while (cs_len > 0) { --cs_len; b = cs_getchar(); if (b >= 32) { if (b <= 246) a = b - 139; else if (b <= 250) { --cs_len; a = ((b - 247) << 8) + 108 + cs_getchar(); } else if (b <= 254) { --cs_len; a = -((b - 251) << 8) - 108 - cs_getchar(); } else { cs_len -= 4; a = (cs_getchar() & 0xff) << 24; a |= (cs_getchar() & 0xff) << 16; a |= (cs_getchar() & 0xff) << 8; a |= (cs_getchar() & 0xff) << 0; if (sizeof(integer) > 4 && (a & 0x80000000)) a |= ~0x7FFFFFFF; } cc_push(a); } else { if (b == CS_ESCAPE) { b = cs_getchar() + CS_1BYTE_MAX; cs_len--; } if (b >= CS_MAX) { cs_fail(cs_name, subr, "command value out of range: %i", (int) b); goto cs_error; } cc = cc_tab + b; if (!cc->valid) { cs_fail(cs_name, subr, "command not valid: %i", (int) b); goto cs_error; } if (cc->bottom) { if (stack_ptr - cc_stack < cc->nargs) cs_fail(cs_name, subr, "less arguments on stack (%i) than required (%i)", (int) (stack_ptr - cc_stack), (int) cc->nargs); else if (stack_ptr - cc_stack > cc->nargs) cs_fail(cs_name, subr, "more arguments on stack (%i) than required (%i)", (int) (stack_ptr - cc_stack), (int) cc->nargs); } last_cmd = b; switch (cc - cc_tab) { case CS_CALLSUBR: a1 = cc_get(-1); cc_pop(1); mark_subr(a1); if (!subr_tab[a1].valid) { cs_fail(cs_name, subr, "cannot call subr (%i)", (int) a1); goto cs_error; } break; case CS_DIV: cc_pop(2); cc_push(0); break; case CS_CALLOTHERSUBR: if (cc_get(-1) == 3) lastargOtherSubr3 = cc_get(-3); a1 = cc_get(-2) + 2; cc_pop(a1); break; case CS_POP: cc_push(lastargOtherSubr3); /* the only case when we care about the value being pushed onto stack is when POP follows CALLOTHERSUBR (changing hints by OtherSubrs[3]) */ break; case CS_SEAC: a1 = cc_get(3); a2 = cc_get(4); cc_clear(); mark_cs(standard_glyph_names[a1]); mark_cs(standard_glyph_names[a2]); break; default: if (cc->clear) cc_clear(); } } } if (cs_name == NULL && last_cmd != CS_RETURN) { pdftex_warn("last command in subr `%i' is not a RETURN; " "I will add it now but please consider fixing the font", (int) subr); append_cs_return(ptr); } return; cs_error: /* an error occured during parsing */ cc_clear(); ptr->valid = false; ptr->used = false; } static void t1_subset_ascii_part(void) { int i, j; t1_getline(); while (!t1_prefix("/Encoding")) { t1_scan_param(); if (!(t1_prefix("/UniqueID") && !strncmp(t1_line_array + strlen(t1_line_array) -4, "def", 3))) t1_putline(); t1_getline(); } if (is_reencoded(fm_cur)) t1_glyph_names = external_enc(); else t1_glyph_names = t1_builtin_enc(); if (is_included(fm_cur) && is_subsetted(fm_cur)) { make_subset_tag(fm_cur, t1_glyph_names); update_subset_tag(); } if (t1_encoding == ENC_STANDARD) t1_puts("/Encoding StandardEncoding def\n"); else { t1_puts ("/Encoding 256 array\n0 1 255 {1 index exch /.notdef put} for\n"); for (i = 0, j = 0; i < 256; i++) { if (is_used_char(i) && t1_glyph_names[i] != notdef) { j++; t1_printf("dup %i /%s put\n", (int)t1_char(i), t1_glyph_names[i]); } } if (j == 0) /* We didn't mark anything for the Encoding array. */ /* We add "dup 0 /.notdef put" for compatibility */ /* with Acrobat 5.0. */ t1_puts("dup 0 /.notdef put\n"); t1_puts("readonly def\n"); } do { t1_getline(); t1_scan_param(); if (!t1_prefix("/UniqueID")) /* ignore UniqueID for subsetted fonts */ t1_putline(); } while (t1_in_eexec == 0); } static void cs_init(void) { cs_ptr = cs_tab = NULL; cs_dict_start = cs_dict_end = NULL; cs_count = cs_size = cs_size_pos = 0; cs_token_pair = NULL; subr_tab = NULL; subr_array_start = subr_array_end = NULL; subr_max = subr_size = subr_size_pos = 0; } static void init_cs_entry(cs_entry *cs) { cs->data = NULL; cs->name = NULL; cs->len = 0; cs->cslen = 0; cs->used = false; cs->valid = false; } static void t1_read_subrs(void) { int i, s; cs_entry *ptr; t1_getline(); while (!(t1_charstrings() || t1_subrs())) { t1_scan_param(); t1_putline(); t1_getline(); } found: t1_cs = true; t1_scan = false; if (!t1_subrs()) return; subr_size_pos = strlen("/Subrs") + 1; /* subr_size_pos points to the number indicating dict size after "/Subrs" */ subr_size = t1_scan_num(t1_line_array + subr_size_pos, 0); if (subr_size == 0) { while (!t1_charstrings()) t1_getline(); return; } subr_tab = xtalloc(subr_size, cs_entry); for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++) init_cs_entry(ptr); subr_array_start = xstrdup(t1_line_array); t1_getline(); while (t1_cslen) { store_subr(); t1_getline(); } /* mark the first four entries without parsing */ for (i = 0; i < subr_size && i < 4; i++) subr_tab[i].used = true; /* the end of the Subrs array might have more than one line so we need to concatnate them to subr_array_end. Unfortunately some fonts don't have the Subrs array followed by the CharStrings dict immediately (synthetic fonts). If we cannot find CharStrings in next POST_SUBRS_SCAN lines then we will treat the font as synthetic and ignore everything until next Subrs is found */ #define POST_SUBRS_SCAN 5 s = 0; *t1_buf_array = 0; for (i = 0; i < POST_SUBRS_SCAN; i++) { if (t1_charstrings()) break; s += t1_line_ptr - t1_line_array; alloc_array(t1_buf, s, T1_BUF_SIZE); strcat(t1_buf_array, t1_line_array); t1_getline(); } subr_array_end = xstrdup(t1_buf_array); if (i == POST_SUBRS_SCAN) { /* CharStrings not found; suppose synthetic font */ for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++) if (ptr->valid) xfree(ptr->data); xfree(subr_tab); xfree(subr_array_start); xfree(subr_array_end); cs_init(); t1_cs = false; t1_synthetic = true; while (!(t1_charstrings() || t1_subrs())) t1_getline(); goto found; } } #define t1_subr_flush() t1_flush_cs(true) #define t1_cs_flush() t1_flush_cs(false) static void t1_flush_cs(boolean is_subr) { char *p; byte *r, *return_cs = NULL; cs_entry *tab, *end_tab, *ptr; char *start_line, *line_end; int count, size_pos; unsigned short cr, cs_len = 0; /* to avoid warning about uninitialized use of cs_len */ if (is_subr) { start_line = subr_array_start; line_end = subr_array_end; size_pos = subr_size_pos; tab = subr_tab; count = subr_max + 1; end_tab = subr_tab + count; } else { start_line = cs_dict_start; line_end = cs_dict_end; size_pos = cs_size_pos; tab = cs_tab; end_tab = cs_ptr; count = cs_count; } t1_line_ptr = t1_line_array; for (p = start_line; p - start_line < size_pos;) *t1_line_ptr++ = *p++; while (isdigit((unsigned char)*p)) p++; sprintf(t1_line_ptr, "%u", count); strcat(t1_line_ptr, p); t1_line_ptr = eol(t1_line_array); t1_putline(); /* create return_cs to replace unused subr's */ if (is_subr) { cr = 4330; cs_len = 0; /* at this point we have t1_lenIV >= 0; * a negative value would be caught in t1_scan_param() */ return_cs = xtalloc(t1_lenIV + 1, byte); for (cs_len = 0, r = return_cs; cs_len < t1_lenIV; cs_len++, r++) *r = cencrypt(0x00, &cr); *r = cencrypt(CS_RETURN, &cr); cs_len++; } for (ptr = tab; ptr < end_tab; ptr++) { if (ptr->used) { if (is_subr) sprintf(t1_line_array, "dup %lu %u", (unsigned long) (ptr - tab), ptr->cslen); else sprintf(t1_line_array, "/%s %u", ptr->name, ptr->cslen); p = strend(t1_line_array); memcpy(p, ptr->data, ptr->len); t1_line_ptr = p + ptr->len; t1_putline(); } else { /* replace unsused subr's by return_cs */ if (is_subr) { sprintf(t1_line_array, "dup %lu %u%s ", (unsigned long) (ptr - tab), cs_len, cs_token_pair[0]); p = strend(t1_line_array); memcpy(p, return_cs, cs_len); t1_line_ptr = p + cs_len; t1_putline(); sprintf(t1_line_array, " %s", cs_token_pair[1]); t1_line_ptr = eol(t1_line_array); t1_putline(); } } xfree(ptr->data); if (ptr->name != notdef) xfree(ptr->name); } sprintf(t1_line_array, "%s", line_end); t1_line_ptr = eol(t1_line_array); t1_putline(); if (is_subr) xfree(return_cs); xfree(tab); xfree(start_line); xfree(line_end); } static void t1_mark_glyphs(void) { int i; char *charset = extra_charset(); char *g, *s, *r; cs_entry *ptr; if (t1_synthetic || embed_all_glyphs(tex_font)) { /* mark everything */ if (cs_tab != NULL) for (ptr = cs_tab; ptr < cs_ptr; ptr++) if (ptr->valid) ptr->used = true; if (subr_tab != NULL) { for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++) if (ptr->valid) ptr->used = true; subr_max = subr_size - 1; } return; } mark_cs(notdef); for (i = 0; i < 256; i++) if (is_used_char(i)) { if (t1_glyph_names[i] == notdef) pdftex_warn("character %i is mapped to %s", i, notdef); else mark_cs(t1_glyph_names[i]); } if (charset == NULL) goto set_subr_max; g = s = charset + 1; /* skip the first '/' */ r = strend(g); while (g < r) { while (*s != '/' && s < r) s++; *s = 0; /* terminate g by rewriting '/' to 0 */ mark_cs(g); g = s + 1; } set_subr_max: if (subr_tab != NULL) for (subr_max = -1, ptr = subr_tab; ptr - subr_tab < subr_size; ptr++) if (ptr->used && ptr - subr_tab > subr_max) subr_max = ptr - subr_tab; } static void t1_check_unusual_charstring(void) { char *p = strstr(t1_line_array, charstringname) + strlen(charstringname); int i; /* if no number follows "/CharStrings", let's read the next line */ if (sscanf(p, "%i", &i) != 1) { /* pdftex_warn("no number found after `%s', I assume it's on the next line", charstringname); */ strcpy(t1_buf_array, t1_line_array); /* t1_getline always appends EOL to t1_line_array; let's change it to * space before appending the next line */ *(strend(t1_buf_array) - 1) = ' '; t1_getline(); strcat(t1_buf_array, t1_line_array); strcpy(t1_line_array, t1_buf_array); t1_line_ptr = eol(t1_line_array); } } static void t1_subset_charstrings(void) { cs_entry *ptr; /* at this point t1_line_array contains "/CharStrings". when we hit a case like this: dup/CharStrings 229 dict dup begin we read the next line and concatenate to t1_line_array before moving on */ t1_check_unusual_charstring(); cs_size_pos = strstr(t1_line_array, charstringname) + strlen(charstringname) - t1_line_array + 1; /* cs_size_pos points to the number indicating dict size after "/CharStrings" */ cs_size = t1_scan_num(t1_line_array + cs_size_pos, 0); cs_ptr = cs_tab = xtalloc(cs_size, cs_entry); for (ptr = cs_tab; ptr - cs_tab < cs_size; ptr++) init_cs_entry(ptr); cs_notdef = NULL; cs_dict_start = xstrdup(t1_line_array); t1_getline(); while (t1_cslen) { store_cs(); t1_getline(); } cs_dict_end = xstrdup(t1_line_array); t1_mark_glyphs(); if (subr_tab != NULL) { if (cs_token_pair == NULL) pdftex_fail ("This Type 1 font uses mismatched subroutine begin/end token pairs."); t1_subr_flush(); } for (cs_count = 0, ptr = cs_tab; ptr < cs_ptr; ptr++) if (ptr->used) cs_count++; t1_cs_flush(); } static void t1_subset_end(void) { if (t1_synthetic) { /* copy to "dup /FontName get exch definefont pop" */ while (!strstr(t1_line_array, "definefont")) { t1_getline(); t1_putline(); } while (!t1_end_eexec()) t1_getline(); /* ignore the rest */ t1_putline(); /* write "mark currentfile closefile" */ } else while (!t1_end_eexec()) { /* copy to "mark currentfile closefile" */ t1_getline(); t1_putline(); } t1_stop_eexec(); if (fixedcontent) { /* copy 512 zeros (not needed for PDF) */ while (!t1_cleartomark()) { t1_getline(); t1_putline(); } if (!t1_synthetic) /* don't check "{restore}if" for synthetic fonts */ t1_check_end(); /* write "{restore}if" if found */ } get_length3(); } static void writet1(void) { read_encoding_only = false; if (!is_included(fm_cur)) { /* scan parameters from font file */ if (!t1_open_fontfile("{")) return; t1_scan_only(); t1_close_font_file("}"); return; } if (!is_subsetted(fm_cur)) { /* include entire font */ if (!t1_open_fontfile("<<")) return; t1_include(); t1_close_font_file(">>"); return; } /* partial downloading */ if (!t1_open_fontfile("<")) return; t1_subset_ascii_part(); t1_start_eexec(); cc_init(); cs_init(); t1_read_subrs(); t1_subset_charstrings(); t1_subset_end(); t1_close_font_file(">"); } boolean t1_subset_2(char *fontfile, unsigned char *g, char *extraGlyphs) { int i; for (i = 0; i < 256; i++) ext_glyph_names[i] = (char*) notdef; grid = g; cur_file_name = fontfile; hexline_length = 0; dvips_extra_charset = extraGlyphs; writet1(); for (i = 0; i < 256; i++) if (ext_glyph_names[i] != notdef) free(ext_glyph_names[i]); return 1; /* note: there *is* no unsuccessful return */ }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_395_1
crossvul-cpp_data_good_5590_0
/* * An implementation of key value pair (KVP) functionality for Linux. * * * Copyright (C) 2010, Novell, Inc. * Author : K. Y. Srinivasan <ksrinivasan@novell.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * 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, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/net.h> #include <linux/nls.h> #include <linux/connector.h> #include <linux/workqueue.h> #include <linux/hyperv.h> #include "hv_kvp.h" /* * Global state maintained for transaction that is being processed. * Note that only one transaction can be active at any point in time. * * This state is set when we receive a request from the host; we * cleanup this state when the transaction is completed - when we respond * to the host with the key value. */ static struct { bool active; /* transaction status - active or not */ int recv_len; /* number of bytes received. */ int index; /* current index */ struct vmbus_channel *recv_channel; /* chn we got the request */ u64 recv_req_id; /* request ID. */ } kvp_transaction; static void kvp_send_key(struct work_struct *dummy); #define TIMEOUT_FIRED 1 static void kvp_respond_to_host(char *key, char *value, int error); static void kvp_work_func(struct work_struct *dummy); static void kvp_register(void); static DECLARE_DELAYED_WORK(kvp_work, kvp_work_func); static DECLARE_WORK(kvp_sendkey_work, kvp_send_key); static struct cb_id kvp_id = { CN_KVP_IDX, CN_KVP_VAL }; static const char kvp_name[] = "kvp_kernel_module"; static u8 *recv_buffer; /* * Register the kernel component with the user-level daemon. * As part of this registration, pass the LIC version number. */ static void kvp_register(void) { struct cn_msg *msg; msg = kzalloc(sizeof(*msg) + strlen(HV_DRV_VERSION) + 1 , GFP_ATOMIC); if (msg) { msg->id.idx = CN_KVP_IDX; msg->id.val = CN_KVP_VAL; msg->seq = KVP_REGISTER; strcpy(msg->data, HV_DRV_VERSION); msg->len = strlen(HV_DRV_VERSION) + 1; cn_netlink_send(msg, 0, GFP_ATOMIC); kfree(msg); } } static void kvp_work_func(struct work_struct *dummy) { /* * If the timer fires, the user-mode component has not responded; * process the pending transaction. */ kvp_respond_to_host("Unknown key", "Guest timed out", TIMEOUT_FIRED); } /* * Callback when data is received from user mode. */ static void kvp_cn_callback(struct cn_msg *msg, struct netlink_skb_parms *nsp) { struct hv_ku_msg *message; message = (struct hv_ku_msg *)msg->data; if (msg->seq == KVP_REGISTER) { pr_info("KVP: user-mode registering done.\n"); kvp_register(); } if (msg->seq == KVP_USER_SET) { /* * Complete the transaction by forwarding the key value * to the host. But first, cancel the timeout. */ if (cancel_delayed_work_sync(&kvp_work)) kvp_respond_to_host(message->kvp_key, message->kvp_value, !strlen(message->kvp_key)); } } static void kvp_send_key(struct work_struct *dummy) { struct cn_msg *msg; int index = kvp_transaction.index; msg = kzalloc(sizeof(*msg) + sizeof(struct hv_kvp_msg) , GFP_ATOMIC); if (msg) { msg->id.idx = CN_KVP_IDX; msg->id.val = CN_KVP_VAL; msg->seq = KVP_KERNEL_GET; ((struct hv_ku_msg *)msg->data)->kvp_index = index; msg->len = sizeof(struct hv_ku_msg); cn_netlink_send(msg, 0, GFP_ATOMIC); kfree(msg); } return; } /* * Send a response back to the host. */ static void kvp_respond_to_host(char *key, char *value, int error) { struct hv_kvp_msg *kvp_msg; struct hv_kvp_msg_enumerate *kvp_data; char *key_name; struct icmsg_hdr *icmsghdrp; int keylen, valuelen; u32 buf_len; struct vmbus_channel *channel; u64 req_id; /* * If a transaction is not active; log and return. */ if (!kvp_transaction.active) { /* * This is a spurious call! */ pr_warn("KVP: Transaction not active\n"); return; } /* * Copy the global state for completing the transaction. Note that * only one transaction can be active at a time. */ buf_len = kvp_transaction.recv_len; channel = kvp_transaction.recv_channel; req_id = kvp_transaction.recv_req_id; kvp_transaction.active = false; if (channel->onchannel_callback == NULL) /* * We have raced with util driver being unloaded; * silently return. */ return; icmsghdrp = (struct icmsg_hdr *) &recv_buffer[sizeof(struct vmbuspipe_hdr)]; kvp_msg = (struct hv_kvp_msg *) &recv_buffer[sizeof(struct vmbuspipe_hdr) + sizeof(struct icmsg_hdr)]; kvp_data = &kvp_msg->kvp_data; key_name = key; /* * If the error parameter is set, terminate the host's enumeration. */ if (error) { /* * We don't support this index or the we have timedout; * terminate the host-side iteration by returning an error. */ icmsghdrp->status = HV_E_FAIL; goto response_done; } /* * The windows host expects the key/value pair to be encoded * in utf16. */ keylen = utf8s_to_utf16s(key_name, strlen(key_name), UTF16_HOST_ENDIAN, (wchar_t *) kvp_data->data.key, HV_KVP_EXCHANGE_MAX_KEY_SIZE / 2); kvp_data->data.key_size = 2*(keylen + 1); /* utf16 encoding */ valuelen = utf8s_to_utf16s(value, strlen(value), UTF16_HOST_ENDIAN, (wchar_t *) kvp_data->data.value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE / 2); kvp_data->data.value_size = 2*(valuelen + 1); /* utf16 encoding */ kvp_data->data.value_type = REG_SZ; /* all our values are strings */ icmsghdrp->status = HV_S_OK; response_done: icmsghdrp->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE; vmbus_sendpacket(channel, recv_buffer, buf_len, req_id, VM_PKT_DATA_INBAND, 0); } /* * This callback is invoked when we get a KVP message from the host. * The host ensures that only one KVP transaction can be active at a time. * KVP implementation in Linux needs to forward the key to a user-mde * component to retrive the corresponding value. Consequently, we cannot * respond to the host in the conext of this callback. Since the host * guarantees that at most only one transaction can be active at a time, * we stash away the transaction state in a set of global variables. */ void hv_kvp_onchannelcallback(void *context) { struct vmbus_channel *channel = context; u32 recvlen; u64 requestid; struct hv_kvp_msg *kvp_msg; struct hv_kvp_msg_enumerate *kvp_data; struct icmsg_hdr *icmsghdrp; struct icmsg_negotiate *negop = NULL; vmbus_recvpacket(channel, recv_buffer, PAGE_SIZE, &recvlen, &requestid); if (recvlen > 0) { icmsghdrp = (struct icmsg_hdr *)&recv_buffer[ sizeof(struct vmbuspipe_hdr)]; if (icmsghdrp->icmsgtype == ICMSGTYPE_NEGOTIATE) { vmbus_prep_negotiate_resp(icmsghdrp, negop, recv_buffer); } else { kvp_msg = (struct hv_kvp_msg *)&recv_buffer[ sizeof(struct vmbuspipe_hdr) + sizeof(struct icmsg_hdr)]; kvp_data = &kvp_msg->kvp_data; /* * We only support the "get" operation on * "KVP_POOL_AUTO" pool. */ if ((kvp_msg->kvp_hdr.pool != KVP_POOL_AUTO) || (kvp_msg->kvp_hdr.operation != KVP_OP_ENUMERATE)) { icmsghdrp->status = HV_E_FAIL; goto callback_done; } /* * Stash away this global state for completing the * transaction; note transactions are serialized. */ kvp_transaction.recv_len = recvlen; kvp_transaction.recv_channel = channel; kvp_transaction.recv_req_id = requestid; kvp_transaction.active = true; kvp_transaction.index = kvp_data->index; /* * Get the information from the * user-mode component. * component. This transaction will be * completed when we get the value from * the user-mode component. * Set a timeout to deal with * user-mode not responding. */ schedule_work(&kvp_sendkey_work); schedule_delayed_work(&kvp_work, 5*HZ); return; } callback_done: icmsghdrp->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE; vmbus_sendpacket(channel, recv_buffer, recvlen, requestid, VM_PKT_DATA_INBAND, 0); } } int hv_kvp_init(struct hv_util_service *srv) { int err; err = cn_add_callback(&kvp_id, kvp_name, kvp_cn_callback); if (err) return err; recv_buffer = srv->recv_buffer; return 0; } void hv_kvp_deinit(void) { cn_del_callback(&kvp_id); cancel_delayed_work_sync(&kvp_work); cancel_work_sync(&kvp_sendkey_work); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_5590_0
crossvul-cpp_data_good_5502_0
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Generic socket support routines. Memory allocators, socket lock/release * handler for protocols to use and generic option handler. * * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Florian La Roche, <flla@stud.uni-sb.de> * Alan Cox, <A.Cox@swansea.ac.uk> * * Fixes: * Alan Cox : Numerous verify_area() problems * Alan Cox : Connecting on a connecting socket * now returns an error for tcp. * Alan Cox : sock->protocol is set correctly. * and is not sometimes left as 0. * Alan Cox : connect handles icmp errors on a * connect properly. Unfortunately there * is a restart syscall nasty there. I * can't match BSD without hacking the C * library. Ideas urgently sought! * Alan Cox : Disallow bind() to addresses that are * not ours - especially broadcast ones!! * Alan Cox : Socket 1024 _IS_ ok for users. (fencepost) * Alan Cox : sock_wfree/sock_rfree don't destroy sockets, * instead they leave that for the DESTROY timer. * Alan Cox : Clean up error flag in accept * Alan Cox : TCP ack handling is buggy, the DESTROY timer * was buggy. Put a remove_sock() in the handler * for memory when we hit 0. Also altered the timer * code. The ACK stuff can wait and needs major * TCP layer surgery. * Alan Cox : Fixed TCP ack bug, removed remove sock * and fixed timer/inet_bh race. * Alan Cox : Added zapped flag for TCP * Alan Cox : Move kfree_skb into skbuff.c and tidied up surplus code * Alan Cox : for new sk_buff allocations wmalloc/rmalloc now call alloc_skb * Alan Cox : kfree_s calls now are kfree_skbmem so we can track skb resources * Alan Cox : Supports socket option broadcast now as does udp. Packet and raw need fixing. * Alan Cox : Added RCVBUF,SNDBUF size setting. It suddenly occurred to me how easy it was so... * Rick Sladkey : Relaxed UDP rules for matching packets. * C.E.Hawkins : IFF_PROMISC/SIOCGHWADDR support * Pauline Middelink : identd support * Alan Cox : Fixed connect() taking signals I think. * Alan Cox : SO_LINGER supported * Alan Cox : Error reporting fixes * Anonymous : inet_create tidied up (sk->reuse setting) * Alan Cox : inet sockets don't set sk->type! * Alan Cox : Split socket option code * Alan Cox : Callbacks * Alan Cox : Nagle flag for Charles & Johannes stuff * Alex : Removed restriction on inet fioctl * Alan Cox : Splitting INET from NET core * Alan Cox : Fixed bogus SO_TYPE handling in getsockopt() * Adam Caldwell : Missing return in SO_DONTROUTE/SO_DEBUG code * Alan Cox : Split IP from generic code * Alan Cox : New kfree_skbmem() * Alan Cox : Make SO_DEBUG superuser only. * Alan Cox : Allow anyone to clear SO_DEBUG * (compatibility fix) * Alan Cox : Added optimistic memory grabbing for AF_UNIX throughput. * Alan Cox : Allocator for a socket is settable. * Alan Cox : SO_ERROR includes soft errors. * Alan Cox : Allow NULL arguments on some SO_ opts * Alan Cox : Generic socket allocation to make hooks * easier (suggested by Craig Metz). * Michael Pall : SO_ERROR returns positive errno again * Steve Whitehouse: Added default destructor to free * protocol private data. * Steve Whitehouse: Added various other default routines * common to several socket families. * Chris Evans : Call suser() check last on F_SETOWN * Jay Schulist : Added SO_ATTACH_FILTER and SO_DETACH_FILTER. * Andi Kleen : Add sock_kmalloc()/sock_kfree_s() * Andi Kleen : Fix write_space callback * Chris Evans : Security fixes - signedness again * Arnaldo C. Melo : cleanups, use skb_queue_purge * * To Fix: * * * 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. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/capability.h> #include <linux/errno.h> #include <linux/errqueue.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/poll.h> #include <linux/tcp.h> #include <linux/init.h> #include <linux/highmem.h> #include <linux/user_namespace.h> #include <linux/static_key.h> #include <linux/memcontrol.h> #include <linux/prefetch.h> #include <asm/uaccess.h> #include <linux/netdevice.h> #include <net/protocol.h> #include <linux/skbuff.h> #include <net/net_namespace.h> #include <net/request_sock.h> #include <net/sock.h> #include <linux/net_tstamp.h> #include <net/xfrm.h> #include <linux/ipsec.h> #include <net/cls_cgroup.h> #include <net/netprio_cgroup.h> #include <linux/sock_diag.h> #include <linux/filter.h> #include <net/sock_reuseport.h> #include <trace/events/sock.h> #ifdef CONFIG_INET #include <net/tcp.h> #endif #include <net/busy_poll.h> static DEFINE_MUTEX(proto_list_mutex); static LIST_HEAD(proto_list); /** * sk_ns_capable - General socket capability test * @sk: Socket to use a capability on or through * @user_ns: The user namespace of the capability to use * @cap: The capability to use * * Test to see if the opener of the socket had when the socket was * created and the current process has the capability @cap in the user * namespace @user_ns. */ bool sk_ns_capable(const struct sock *sk, struct user_namespace *user_ns, int cap) { return file_ns_capable(sk->sk_socket->file, user_ns, cap) && ns_capable(user_ns, cap); } EXPORT_SYMBOL(sk_ns_capable); /** * sk_capable - Socket global capability test * @sk: Socket to use a capability on or through * @cap: The global capability to use * * Test to see if the opener of the socket had when the socket was * created and the current process has the capability @cap in all user * namespaces. */ bool sk_capable(const struct sock *sk, int cap) { return sk_ns_capable(sk, &init_user_ns, cap); } EXPORT_SYMBOL(sk_capable); /** * sk_net_capable - Network namespace socket capability test * @sk: Socket to use a capability on or through * @cap: The capability to use * * Test to see if the opener of the socket had when the socket was created * and the current process has the capability @cap over the network namespace * the socket is a member of. */ bool sk_net_capable(const struct sock *sk, int cap) { return sk_ns_capable(sk, sock_net(sk)->user_ns, cap); } EXPORT_SYMBOL(sk_net_capable); /* * Each address family might have different locking rules, so we have * one slock key per address family: */ static struct lock_class_key af_family_keys[AF_MAX]; static struct lock_class_key af_family_slock_keys[AF_MAX]; /* * Make lock validator output more readable. (we pre-construct these * strings build-time, so that runtime initialization of socket * locks is fast): */ static const char *const af_family_key_strings[AF_MAX+1] = { "sk_lock-AF_UNSPEC", "sk_lock-AF_UNIX" , "sk_lock-AF_INET" , "sk_lock-AF_AX25" , "sk_lock-AF_IPX" , "sk_lock-AF_APPLETALK", "sk_lock-AF_NETROM", "sk_lock-AF_BRIDGE" , "sk_lock-AF_ATMPVC" , "sk_lock-AF_X25" , "sk_lock-AF_INET6" , "sk_lock-AF_ROSE" , "sk_lock-AF_DECnet", "sk_lock-AF_NETBEUI" , "sk_lock-AF_SECURITY" , "sk_lock-AF_KEY" , "sk_lock-AF_NETLINK" , "sk_lock-AF_PACKET" , "sk_lock-AF_ASH" , "sk_lock-AF_ECONET" , "sk_lock-AF_ATMSVC" , "sk_lock-AF_RDS" , "sk_lock-AF_SNA" , "sk_lock-AF_IRDA" , "sk_lock-AF_PPPOX" , "sk_lock-AF_WANPIPE" , "sk_lock-AF_LLC" , "sk_lock-27" , "sk_lock-28" , "sk_lock-AF_CAN" , "sk_lock-AF_TIPC" , "sk_lock-AF_BLUETOOTH", "sk_lock-IUCV" , "sk_lock-AF_RXRPC" , "sk_lock-AF_ISDN" , "sk_lock-AF_PHONET" , "sk_lock-AF_IEEE802154", "sk_lock-AF_CAIF" , "sk_lock-AF_ALG" , "sk_lock-AF_NFC" , "sk_lock-AF_VSOCK" , "sk_lock-AF_KCM" , "sk_lock-AF_MAX" }; static const char *const af_family_slock_key_strings[AF_MAX+1] = { "slock-AF_UNSPEC", "slock-AF_UNIX" , "slock-AF_INET" , "slock-AF_AX25" , "slock-AF_IPX" , "slock-AF_APPLETALK", "slock-AF_NETROM", "slock-AF_BRIDGE" , "slock-AF_ATMPVC" , "slock-AF_X25" , "slock-AF_INET6" , "slock-AF_ROSE" , "slock-AF_DECnet", "slock-AF_NETBEUI" , "slock-AF_SECURITY" , "slock-AF_KEY" , "slock-AF_NETLINK" , "slock-AF_PACKET" , "slock-AF_ASH" , "slock-AF_ECONET" , "slock-AF_ATMSVC" , "slock-AF_RDS" , "slock-AF_SNA" , "slock-AF_IRDA" , "slock-AF_PPPOX" , "slock-AF_WANPIPE" , "slock-AF_LLC" , "slock-27" , "slock-28" , "slock-AF_CAN" , "slock-AF_TIPC" , "slock-AF_BLUETOOTH", "slock-AF_IUCV" , "slock-AF_RXRPC" , "slock-AF_ISDN" , "slock-AF_PHONET" , "slock-AF_IEEE802154", "slock-AF_CAIF" , "slock-AF_ALG" , "slock-AF_NFC" , "slock-AF_VSOCK" ,"slock-AF_KCM" , "slock-AF_MAX" }; static const char *const af_family_clock_key_strings[AF_MAX+1] = { "clock-AF_UNSPEC", "clock-AF_UNIX" , "clock-AF_INET" , "clock-AF_AX25" , "clock-AF_IPX" , "clock-AF_APPLETALK", "clock-AF_NETROM", "clock-AF_BRIDGE" , "clock-AF_ATMPVC" , "clock-AF_X25" , "clock-AF_INET6" , "clock-AF_ROSE" , "clock-AF_DECnet", "clock-AF_NETBEUI" , "clock-AF_SECURITY" , "clock-AF_KEY" , "clock-AF_NETLINK" , "clock-AF_PACKET" , "clock-AF_ASH" , "clock-AF_ECONET" , "clock-AF_ATMSVC" , "clock-AF_RDS" , "clock-AF_SNA" , "clock-AF_IRDA" , "clock-AF_PPPOX" , "clock-AF_WANPIPE" , "clock-AF_LLC" , "clock-27" , "clock-28" , "clock-AF_CAN" , "clock-AF_TIPC" , "clock-AF_BLUETOOTH", "clock-AF_IUCV" , "clock-AF_RXRPC" , "clock-AF_ISDN" , "clock-AF_PHONET" , "clock-AF_IEEE802154", "clock-AF_CAIF" , "clock-AF_ALG" , "clock-AF_NFC" , "clock-AF_VSOCK" , "clock-AF_KCM" , "clock-AF_MAX" }; /* * sk_callback_lock locking rules are per-address-family, * so split the lock classes by using a per-AF key: */ static struct lock_class_key af_callback_keys[AF_MAX]; /* Take into consideration the size of the struct sk_buff overhead in the * determination of these values, since that is non-constant across * platforms. This makes socket queueing behavior and performance * not depend upon such differences. */ #define _SK_MEM_PACKETS 256 #define _SK_MEM_OVERHEAD SKB_TRUESIZE(256) #define SK_WMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS) #define SK_RMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS) /* Run time adjustable parameters. */ __u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX; EXPORT_SYMBOL(sysctl_wmem_max); __u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX; EXPORT_SYMBOL(sysctl_rmem_max); __u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX; __u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX; /* Maximal space eaten by iovec or ancillary data plus some space */ int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512); EXPORT_SYMBOL(sysctl_optmem_max); int sysctl_tstamp_allow_data __read_mostly = 1; struct static_key memalloc_socks = STATIC_KEY_INIT_FALSE; EXPORT_SYMBOL_GPL(memalloc_socks); /** * sk_set_memalloc - sets %SOCK_MEMALLOC * @sk: socket to set it on * * Set %SOCK_MEMALLOC on a socket for access to emergency reserves. * It's the responsibility of the admin to adjust min_free_kbytes * to meet the requirements */ void sk_set_memalloc(struct sock *sk) { sock_set_flag(sk, SOCK_MEMALLOC); sk->sk_allocation |= __GFP_MEMALLOC; static_key_slow_inc(&memalloc_socks); } EXPORT_SYMBOL_GPL(sk_set_memalloc); void sk_clear_memalloc(struct sock *sk) { sock_reset_flag(sk, SOCK_MEMALLOC); sk->sk_allocation &= ~__GFP_MEMALLOC; static_key_slow_dec(&memalloc_socks); /* * SOCK_MEMALLOC is allowed to ignore rmem limits to ensure forward * progress of swapping. SOCK_MEMALLOC may be cleared while * it has rmem allocations due to the last swapfile being deactivated * but there is a risk that the socket is unusable due to exceeding * the rmem limits. Reclaim the reserves and obey rmem limits again. */ sk_mem_reclaim(sk); } EXPORT_SYMBOL_GPL(sk_clear_memalloc); int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb) { int ret; unsigned long pflags = current->flags; /* these should have been dropped before queueing */ BUG_ON(!sock_flag(sk, SOCK_MEMALLOC)); current->flags |= PF_MEMALLOC; ret = sk->sk_backlog_rcv(sk, skb); tsk_restore_flags(current, pflags, PF_MEMALLOC); return ret; } EXPORT_SYMBOL(__sk_backlog_rcv); static int sock_set_timeout(long *timeo_p, char __user *optval, int optlen) { struct timeval tv; if (optlen < sizeof(tv)) return -EINVAL; if (copy_from_user(&tv, optval, sizeof(tv))) return -EFAULT; if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC) return -EDOM; if (tv.tv_sec < 0) { static int warned __read_mostly; *timeo_p = 0; if (warned < 10 && net_ratelimit()) { warned++; pr_info("%s: `%s' (pid %d) tries to set negative timeout\n", __func__, current->comm, task_pid_nr(current)); } return 0; } *timeo_p = MAX_SCHEDULE_TIMEOUT; if (tv.tv_sec == 0 && tv.tv_usec == 0) return 0; if (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT/HZ - 1)) *timeo_p = tv.tv_sec*HZ + (tv.tv_usec+(1000000/HZ-1))/(1000000/HZ); return 0; } static void sock_warn_obsolete_bsdism(const char *name) { static int warned; static char warncomm[TASK_COMM_LEN]; if (strcmp(warncomm, current->comm) && warned < 5) { strcpy(warncomm, current->comm); pr_warn("process `%s' is using obsolete %s SO_BSDCOMPAT\n", warncomm, name); warned++; } } static bool sock_needs_netstamp(const struct sock *sk) { switch (sk->sk_family) { case AF_UNSPEC: case AF_UNIX: return false; default: return true; } } static void sock_disable_timestamp(struct sock *sk, unsigned long flags) { if (sk->sk_flags & flags) { sk->sk_flags &= ~flags; if (sock_needs_netstamp(sk) && !(sk->sk_flags & SK_FLAGS_TIMESTAMP)) net_disable_timestamp(); } } int __sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { unsigned long flags; struct sk_buff_head *list = &sk->sk_receive_queue; if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) { atomic_inc(&sk->sk_drops); trace_sock_rcvqueue_full(sk, skb); return -ENOMEM; } if (!sk_rmem_schedule(sk, skb, skb->truesize)) { atomic_inc(&sk->sk_drops); return -ENOBUFS; } skb->dev = NULL; skb_set_owner_r(skb, sk); /* we escape from rcu protected region, make sure we dont leak * a norefcounted dst */ skb_dst_force(skb); spin_lock_irqsave(&list->lock, flags); sock_skb_set_dropcount(sk, skb); __skb_queue_tail(list, skb); spin_unlock_irqrestore(&list->lock, flags); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk); return 0; } EXPORT_SYMBOL(__sock_queue_rcv_skb); int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int err; err = sk_filter(sk, skb); if (err) return err; return __sock_queue_rcv_skb(sk, skb); } EXPORT_SYMBOL(sock_queue_rcv_skb); int __sk_receive_skb(struct sock *sk, struct sk_buff *skb, const int nested, unsigned int trim_cap, bool refcounted) { int rc = NET_RX_SUCCESS; if (sk_filter_trim_cap(sk, skb, trim_cap)) goto discard_and_relse; skb->dev = NULL; if (sk_rcvqueues_full(sk, sk->sk_rcvbuf)) { atomic_inc(&sk->sk_drops); goto discard_and_relse; } if (nested) bh_lock_sock_nested(sk); else bh_lock_sock(sk); if (!sock_owned_by_user(sk)) { /* * trylock + unlock semantics: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_); rc = sk_backlog_rcv(sk, skb); mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_); } else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) { bh_unlock_sock(sk); atomic_inc(&sk->sk_drops); goto discard_and_relse; } bh_unlock_sock(sk); out: if (refcounted) sock_put(sk); return rc; discard_and_relse: kfree_skb(skb); goto out; } EXPORT_SYMBOL(__sk_receive_skb); struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = __sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_tx_queue_clear(sk); RCU_INIT_POINTER(sk->sk_dst_cache, NULL); dst_release(dst); return NULL; } return dst; } EXPORT_SYMBOL(__sk_dst_check); struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_dst_reset(sk); dst_release(dst); return NULL; } return dst; } EXPORT_SYMBOL(sk_dst_check); static int sock_setbindtodevice(struct sock *sk, char __user *optval, int optlen) { int ret = -ENOPROTOOPT; #ifdef CONFIG_NETDEVICES struct net *net = sock_net(sk); char devname[IFNAMSIZ]; int index; /* Sorry... */ ret = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_RAW)) goto out; ret = -EINVAL; if (optlen < 0) goto out; /* Bind this socket to a particular device like "eth0", * as specified in the passed interface name. If the * name is "" or the option length is zero the socket * is not bound. */ if (optlen > IFNAMSIZ - 1) optlen = IFNAMSIZ - 1; memset(devname, 0, sizeof(devname)); ret = -EFAULT; if (copy_from_user(devname, optval, optlen)) goto out; index = 0; if (devname[0] != '\0') { struct net_device *dev; rcu_read_lock(); dev = dev_get_by_name_rcu(net, devname); if (dev) index = dev->ifindex; rcu_read_unlock(); ret = -ENODEV; if (!dev) goto out; } lock_sock(sk); sk->sk_bound_dev_if = index; sk_dst_reset(sk); release_sock(sk); ret = 0; out: #endif return ret; } static int sock_getbindtodevice(struct sock *sk, char __user *optval, int __user *optlen, int len) { int ret = -ENOPROTOOPT; #ifdef CONFIG_NETDEVICES struct net *net = sock_net(sk); char devname[IFNAMSIZ]; if (sk->sk_bound_dev_if == 0) { len = 0; goto zero; } ret = -EINVAL; if (len < IFNAMSIZ) goto out; ret = netdev_get_name(net, devname, sk->sk_bound_dev_if); if (ret) goto out; len = strlen(devname) + 1; ret = -EFAULT; if (copy_to_user(optval, devname, len)) goto out; zero: ret = -EFAULT; if (put_user(len, optlen)) goto out; ret = 0; out: #endif return ret; } static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool) { if (valbool) sock_set_flag(sk, bit); else sock_reset_flag(sk, bit); } bool sk_mc_loop(struct sock *sk) { if (dev_recursion_level()) return false; if (!sk) return true; switch (sk->sk_family) { case AF_INET: return inet_sk(sk)->mc_loop; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: return inet6_sk(sk)->mc_loop; #endif } WARN_ON(1); return true; } EXPORT_SYMBOL(sk_mc_loop); /* * This is meant for all protocols to use and covers goings on * at the socket level. Everything here is generic. */ int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_setbindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_REUSEPORT: sk->sk_reuseport = valbool; break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check_tx = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } if (val & SOF_TIMESTAMPING_OPT_ID && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) { if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) { if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) { ret = -EINVAL; break; } sk->sk_tskey = tcp_sk(sk)->snd_una; } else { sk->sk_tskey = 0; } } sk->sk_tsflags = val; if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_ATTACH_BPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_attach_bpf(ufd, sk); } break; case SO_ATTACH_REUSEPORT_CBPF: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_reuseport_attach_filter(&fprog, sk); } break; case SO_ATTACH_REUSEPORT_EBPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_reuseport_attach_bpf(ufd, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_LOCK_FILTER: if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool) ret = -EPERM; else sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) ret = sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; case SO_SELECT_ERR_QUEUE: sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: /* allow unprivileged users to decrease the value */ if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN)) ret = -EPERM; else { if (val < 0) ret = -EINVAL; else sk->sk_ll_usec = val; } break; #endif case SO_MAX_PACING_RATE: sk->sk_max_pacing_rate = val; sk->sk_pacing_rate = min(sk->sk_pacing_rate, sk->sk_max_pacing_rate); break; case SO_INCOMING_CPU: sk->sk_incoming_cpu = val; break; case SO_CNX_ADVICE: if (val == 1) dst_negative_advice(sk); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; } EXPORT_SYMBOL(sock_setsockopt); static void cred_to_ucred(struct pid *pid, const struct cred *cred, struct ucred *ucred) { ucred->pid = pid_vnr(pid); ucred->uid = ucred->gid = -1; if (cred) { struct user_namespace *current_ns = current_user_ns(); ucred->uid = from_kuid_munged(current_ns, cred->euid); ucred->gid = from_kgid_munged(current_ns, cred->egid); } } int sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; union { int val; struct linger ling; struct timeval tm; } v; int lv = sizeof(int); int len; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; memset(&v, 0, sizeof(v)); switch (optname) { case SO_DEBUG: v.val = sock_flag(sk, SOCK_DBG); break; case SO_DONTROUTE: v.val = sock_flag(sk, SOCK_LOCALROUTE); break; case SO_BROADCAST: v.val = sock_flag(sk, SOCK_BROADCAST); break; case SO_SNDBUF: v.val = sk->sk_sndbuf; break; case SO_RCVBUF: v.val = sk->sk_rcvbuf; break; case SO_REUSEADDR: v.val = sk->sk_reuse; break; case SO_REUSEPORT: v.val = sk->sk_reuseport; break; case SO_KEEPALIVE: v.val = sock_flag(sk, SOCK_KEEPOPEN); break; case SO_TYPE: v.val = sk->sk_type; break; case SO_PROTOCOL: v.val = sk->sk_protocol; break; case SO_DOMAIN: v.val = sk->sk_family; break; case SO_ERROR: v.val = -sock_error(sk); if (v.val == 0) v.val = xchg(&sk->sk_err_soft, 0); break; case SO_OOBINLINE: v.val = sock_flag(sk, SOCK_URGINLINE); break; case SO_NO_CHECK: v.val = sk->sk_no_check_tx; break; case SO_PRIORITY: v.val = sk->sk_priority; break; case SO_LINGER: lv = sizeof(v.ling); v.ling.l_onoff = sock_flag(sk, SOCK_LINGER); v.ling.l_linger = sk->sk_lingertime / HZ; break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("getsockopt"); break; case SO_TIMESTAMP: v.val = sock_flag(sk, SOCK_RCVTSTAMP) && !sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPNS: v.val = sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPING: v.val = sk->sk_tsflags; break; case SO_RCVTIMEO: lv = sizeof(struct timeval); if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_rcvtimeo / HZ; v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ; } break; case SO_SNDTIMEO: lv = sizeof(struct timeval); if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_sndtimeo / HZ; v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ; } break; case SO_RCVLOWAT: v.val = sk->sk_rcvlowat; break; case SO_SNDLOWAT: v.val = 1; break; case SO_PASSCRED: v.val = !!test_bit(SOCK_PASSCRED, &sock->flags); break; case SO_PEERCRED: { struct ucred peercred; if (len > sizeof(peercred)) len = sizeof(peercred); cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred); if (copy_to_user(optval, &peercred, len)) return -EFAULT; goto lenout; } case SO_PEERNAME: { char address[128]; if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2)) return -ENOTCONN; if (lv < len) return -EINVAL; if (copy_to_user(optval, address, len)) return -EFAULT; goto lenout; } /* Dubious BSD thing... Probably nobody even uses it, but * the UNIX standard wants it for whatever reason... -DaveM */ case SO_ACCEPTCONN: v.val = sk->sk_state == TCP_LISTEN; break; case SO_PASSSEC: v.val = !!test_bit(SOCK_PASSSEC, &sock->flags); break; case SO_PEERSEC: return security_socket_getpeersec_stream(sock, optval, optlen, len); case SO_MARK: v.val = sk->sk_mark; break; case SO_RXQ_OVFL: v.val = sock_flag(sk, SOCK_RXQ_OVFL); break; case SO_WIFI_STATUS: v.val = sock_flag(sk, SOCK_WIFI_STATUS); break; case SO_PEEK_OFF: if (!sock->ops->set_peek_off) return -EOPNOTSUPP; v.val = sk->sk_peek_off; break; case SO_NOFCS: v.val = sock_flag(sk, SOCK_NOFCS); break; case SO_BINDTODEVICE: return sock_getbindtodevice(sk, optval, optlen, len); case SO_GET_FILTER: len = sk_get_filter(sk, (struct sock_filter __user *)optval, len); if (len < 0) return len; goto lenout; case SO_LOCK_FILTER: v.val = sock_flag(sk, SOCK_FILTER_LOCKED); break; case SO_BPF_EXTENSIONS: v.val = bpf_tell_extensions(); break; case SO_SELECT_ERR_QUEUE: v.val = sock_flag(sk, SOCK_SELECT_ERR_QUEUE); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: v.val = sk->sk_ll_usec; break; #endif case SO_MAX_PACING_RATE: v.val = sk->sk_max_pacing_rate; break; case SO_INCOMING_CPU: v.val = sk->sk_incoming_cpu; break; default: /* We implement the SO_SNDLOWAT etc to not be settable * (1003.1g 7). */ return -ENOPROTOOPT; } if (len > lv) len = lv; if (copy_to_user(optval, &v, len)) return -EFAULT; lenout: if (put_user(len, optlen)) return -EFAULT; return 0; } /* * Initialize an sk_lock. * * (We also register the sk_lock with the lock validator.) */ static inline void sock_lock_init(struct sock *sk) { sock_lock_init_class_and_name(sk, af_family_slock_key_strings[sk->sk_family], af_family_slock_keys + sk->sk_family, af_family_key_strings[sk->sk_family], af_family_keys + sk->sk_family); } /* * Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet, * even temporarly, because of RCU lookups. sk_node should also be left as is. * We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end */ static void sock_copy(struct sock *nsk, const struct sock *osk) { #ifdef CONFIG_SECURITY_NETWORK void *sptr = nsk->sk_security; #endif memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin)); memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end, osk->sk_prot->obj_size - offsetof(struct sock, sk_dontcopy_end)); #ifdef CONFIG_SECURITY_NETWORK nsk->sk_security = sptr; security_sk_clone(osk, nsk); #endif } static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority, int family) { struct sock *sk; struct kmem_cache *slab; slab = prot->slab; if (slab != NULL) { sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO); if (!sk) return sk; if (priority & __GFP_ZERO) sk_prot_clear_nulls(sk, prot->obj_size); } else sk = kmalloc(prot->obj_size, priority); if (sk != NULL) { kmemcheck_annotate_bitfield(sk, flags); if (security_sk_alloc(sk, family, priority)) goto out_free; if (!try_module_get(prot->owner)) goto out_free_sec; sk_tx_queue_clear(sk); } return sk; out_free_sec: security_sk_free(sk); out_free: if (slab != NULL) kmem_cache_free(slab, sk); else kfree(sk); return NULL; } static void sk_prot_free(struct proto *prot, struct sock *sk) { struct kmem_cache *slab; struct module *owner; owner = prot->owner; slab = prot->slab; cgroup_sk_free(&sk->sk_cgrp_data); mem_cgroup_sk_free(sk); security_sk_free(sk); if (slab != NULL) kmem_cache_free(slab, sk); else kfree(sk); module_put(owner); } /** * sk_alloc - All socket objects are allocated here * @net: the applicable net namespace * @family: protocol family * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * @prot: struct proto associated with this new sock instance * @kern: is this to be a kernel socket? */ struct sock *sk_alloc(struct net *net, int family, gfp_t priority, struct proto *prot, int kern) { struct sock *sk; sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family); if (sk) { sk->sk_family = family; /* * See comment in struct sock definition to understand * why we need sk_prot_creator -acme */ sk->sk_prot = sk->sk_prot_creator = prot; sock_lock_init(sk); sk->sk_net_refcnt = kern ? 0 : 1; if (likely(sk->sk_net_refcnt)) get_net(net); sock_net_set(sk, net); atomic_set(&sk->sk_wmem_alloc, 1); mem_cgroup_sk_alloc(sk); cgroup_sk_alloc(&sk->sk_cgrp_data); sock_update_classid(&sk->sk_cgrp_data); sock_update_netprioidx(&sk->sk_cgrp_data); } return sk; } EXPORT_SYMBOL(sk_alloc); /* Sockets having SOCK_RCU_FREE will call this function after one RCU * grace period. This is the case for UDP sockets and TCP listeners. */ static void __sk_destruct(struct rcu_head *head) { struct sock *sk = container_of(head, struct sock, sk_rcu); struct sk_filter *filter; if (sk->sk_destruct) sk->sk_destruct(sk); filter = rcu_dereference_check(sk->sk_filter, atomic_read(&sk->sk_wmem_alloc) == 0); if (filter) { sk_filter_uncharge(sk, filter); RCU_INIT_POINTER(sk->sk_filter, NULL); } if (rcu_access_pointer(sk->sk_reuseport_cb)) reuseport_detach_sock(sk); sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP); if (atomic_read(&sk->sk_omem_alloc)) pr_debug("%s: optmem leakage (%d bytes) detected\n", __func__, atomic_read(&sk->sk_omem_alloc)); if (sk->sk_peer_cred) put_cred(sk->sk_peer_cred); put_pid(sk->sk_peer_pid); if (likely(sk->sk_net_refcnt)) put_net(sock_net(sk)); sk_prot_free(sk->sk_prot_creator, sk); } void sk_destruct(struct sock *sk) { if (sock_flag(sk, SOCK_RCU_FREE)) call_rcu(&sk->sk_rcu, __sk_destruct); else __sk_destruct(&sk->sk_rcu); } static void __sk_free(struct sock *sk) { if (unlikely(sock_diag_has_destroy_listeners(sk) && sk->sk_net_refcnt)) sock_diag_broadcast_destroy(sk); else sk_destruct(sk); } void sk_free(struct sock *sk) { /* * We subtract one from sk_wmem_alloc and can know if * some packets are still in some tx queue. * If not null, sock_wfree() will call __sk_free(sk) later */ if (atomic_dec_and_test(&sk->sk_wmem_alloc)) __sk_free(sk); } EXPORT_SYMBOL(sk_free); /** * sk_clone_lock - clone a socket, and lock its clone * @sk: the socket to clone * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * * Caller must unlock socket even in error path (bh_unlock_sock(newsk)) */ struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority) { struct sock *newsk; bool is_charged = true; newsk = sk_prot_alloc(sk->sk_prot, priority, sk->sk_family); if (newsk != NULL) { struct sk_filter *filter; sock_copy(newsk, sk); /* SANITY */ if (likely(newsk->sk_net_refcnt)) get_net(sock_net(newsk)); sk_node_init(&newsk->sk_node); sock_lock_init(newsk); bh_lock_sock(newsk); newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL; newsk->sk_backlog.len = 0; atomic_set(&newsk->sk_rmem_alloc, 0); /* * sk_wmem_alloc set to one (see sk_free() and sock_wfree()) */ atomic_set(&newsk->sk_wmem_alloc, 1); atomic_set(&newsk->sk_omem_alloc, 0); skb_queue_head_init(&newsk->sk_receive_queue); skb_queue_head_init(&newsk->sk_write_queue); rwlock_init(&newsk->sk_callback_lock); lockdep_set_class_and_name(&newsk->sk_callback_lock, af_callback_keys + newsk->sk_family, af_family_clock_key_strings[newsk->sk_family]); newsk->sk_dst_cache = NULL; newsk->sk_wmem_queued = 0; newsk->sk_forward_alloc = 0; atomic_set(&newsk->sk_drops, 0); newsk->sk_send_head = NULL; newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK; sock_reset_flag(newsk, SOCK_DONE); skb_queue_head_init(&newsk->sk_error_queue); filter = rcu_dereference_protected(newsk->sk_filter, 1); if (filter != NULL) /* though it's an empty new sock, the charging may fail * if sysctl_optmem_max was changed between creation of * original socket and cloning */ is_charged = sk_filter_charge(newsk, filter); if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) { /* It is still raw copy of parent, so invalidate * destructor and make plain sk_free() */ newsk->sk_destruct = NULL; bh_unlock_sock(newsk); sk_free(newsk); newsk = NULL; goto out; } RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL); newsk->sk_err = 0; newsk->sk_err_soft = 0; newsk->sk_priority = 0; newsk->sk_incoming_cpu = raw_smp_processor_id(); atomic64_set(&newsk->sk_cookie, 0); mem_cgroup_sk_alloc(newsk); cgroup_sk_alloc(&newsk->sk_cgrp_data); /* * Before updating sk_refcnt, we must commit prior changes to memory * (Documentation/RCU/rculist_nulls.txt for details) */ smp_wmb(); atomic_set(&newsk->sk_refcnt, 2); /* * Increment the counter in the same struct proto as the master * sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that * is the same as sk->sk_prot->socks, as this field was copied * with memcpy). * * This _changes_ the previous behaviour, where * tcp_create_openreq_child always was incrementing the * equivalent to tcp_prot->socks (inet_sock_nr), so this have * to be taken into account in all callers. -acme */ sk_refcnt_debug_inc(newsk); sk_set_socket(newsk, NULL); newsk->sk_wq = NULL; if (newsk->sk_prot->sockets_allocated) sk_sockets_allocated_inc(newsk); if (sock_needs_netstamp(sk) && newsk->sk_flags & SK_FLAGS_TIMESTAMP) net_enable_timestamp(); } out: return newsk; } EXPORT_SYMBOL_GPL(sk_clone_lock); void sk_setup_caps(struct sock *sk, struct dst_entry *dst) { u32 max_segs = 1; sk_dst_set(sk, dst); sk->sk_route_caps = dst->dev->features; if (sk->sk_route_caps & NETIF_F_GSO) sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE; sk->sk_route_caps &= ~sk->sk_route_nocaps; if (sk_can_gso(sk)) { if (dst->header_len) { sk->sk_route_caps &= ~NETIF_F_GSO_MASK; } else { sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM; sk->sk_gso_max_size = dst->dev->gso_max_size; max_segs = max_t(u32, dst->dev->gso_max_segs, 1); } } sk->sk_gso_max_segs = max_segs; } EXPORT_SYMBOL_GPL(sk_setup_caps); /* * Simple resource managers for sockets. */ /* * Write buffer destructor automatically called from kfree_skb. */ void sock_wfree(struct sk_buff *skb) { struct sock *sk = skb->sk; unsigned int len = skb->truesize; if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) { /* * Keep a reference on sk_wmem_alloc, this will be released * after sk_write_space() call */ atomic_sub(len - 1, &sk->sk_wmem_alloc); sk->sk_write_space(sk); len = 1; } /* * if sk_wmem_alloc reaches 0, we must finish what sk_free() * could not do because of in-flight packets */ if (atomic_sub_and_test(len, &sk->sk_wmem_alloc)) __sk_free(sk); } EXPORT_SYMBOL(sock_wfree); /* This variant of sock_wfree() is used by TCP, * since it sets SOCK_USE_WRITE_QUEUE. */ void __sock_wfree(struct sk_buff *skb) { struct sock *sk = skb->sk; if (atomic_sub_and_test(skb->truesize, &sk->sk_wmem_alloc)) __sk_free(sk); } void skb_set_owner_w(struct sk_buff *skb, struct sock *sk) { skb_orphan(skb); skb->sk = sk; #ifdef CONFIG_INET if (unlikely(!sk_fullsock(sk))) { skb->destructor = sock_edemux; sock_hold(sk); return; } #endif skb->destructor = sock_wfree; skb_set_hash_from_sk(skb, sk); /* * We used to take a refcount on sk, but following operation * is enough to guarantee sk_free() wont free this sock until * all in-flight packets are completed */ atomic_add(skb->truesize, &sk->sk_wmem_alloc); } EXPORT_SYMBOL(skb_set_owner_w); /* This helper is used by netem, as it can hold packets in its * delay queue. We want to allow the owner socket to send more * packets, as if they were already TX completed by a typical driver. * But we also want to keep skb->sk set because some packet schedulers * rely on it (sch_fq for example). So we set skb->truesize to a small * amount (1) and decrease sk_wmem_alloc accordingly. */ void skb_orphan_partial(struct sk_buff *skb) { /* If this skb is a TCP pure ACK or already went here, * we have nothing to do. 2 is already a very small truesize. */ if (skb->truesize <= 2) return; /* TCP stack sets skb->ooo_okay based on sk_wmem_alloc, * so we do not completely orphan skb, but transfert all * accounted bytes but one, to avoid unexpected reorders. */ if (skb->destructor == sock_wfree #ifdef CONFIG_INET || skb->destructor == tcp_wfree #endif ) { atomic_sub(skb->truesize - 1, &skb->sk->sk_wmem_alloc); skb->truesize = 1; } else { skb_orphan(skb); } } EXPORT_SYMBOL(skb_orphan_partial); /* * Read buffer destructor automatically called from kfree_skb. */ void sock_rfree(struct sk_buff *skb) { struct sock *sk = skb->sk; unsigned int len = skb->truesize; atomic_sub(len, &sk->sk_rmem_alloc); sk_mem_uncharge(sk, len); } EXPORT_SYMBOL(sock_rfree); /* * Buffer destructor for skbs that are not used directly in read or write * path, e.g. for error handler skbs. Automatically called from kfree_skb. */ void sock_efree(struct sk_buff *skb) { sock_put(skb->sk); } EXPORT_SYMBOL(sock_efree); kuid_t sock_i_uid(struct sock *sk) { kuid_t uid; read_lock_bh(&sk->sk_callback_lock); uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : GLOBAL_ROOT_UID; read_unlock_bh(&sk->sk_callback_lock); return uid; } EXPORT_SYMBOL(sock_i_uid); unsigned long sock_i_ino(struct sock *sk) { unsigned long ino; read_lock_bh(&sk->sk_callback_lock); ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0; read_unlock_bh(&sk->sk_callback_lock); return ino; } EXPORT_SYMBOL(sock_i_ino); /* * Allocate a skb from the socket's send buffer. */ struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force, gfp_t priority) { if (force || atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) { struct sk_buff *skb = alloc_skb(size, priority); if (skb) { skb_set_owner_w(skb, sk); return skb; } } return NULL; } EXPORT_SYMBOL(sock_wmalloc); /* * Allocate a memory block from the socket's option memory buffer. */ void *sock_kmalloc(struct sock *sk, int size, gfp_t priority) { if ((unsigned int)size <= sysctl_optmem_max && atomic_read(&sk->sk_omem_alloc) + size < sysctl_optmem_max) { void *mem; /* First do the add, to avoid the race if kmalloc * might sleep. */ atomic_add(size, &sk->sk_omem_alloc); mem = kmalloc(size, priority); if (mem) return mem; atomic_sub(size, &sk->sk_omem_alloc); } return NULL; } EXPORT_SYMBOL(sock_kmalloc); /* Free an option memory block. Note, we actually want the inline * here as this allows gcc to detect the nullify and fold away the * condition entirely. */ static inline void __sock_kfree_s(struct sock *sk, void *mem, int size, const bool nullify) { if (WARN_ON_ONCE(!mem)) return; if (nullify) kzfree(mem); else kfree(mem); atomic_sub(size, &sk->sk_omem_alloc); } void sock_kfree_s(struct sock *sk, void *mem, int size) { __sock_kfree_s(sk, mem, size, false); } EXPORT_SYMBOL(sock_kfree_s); void sock_kzfree_s(struct sock *sk, void *mem, int size) { __sock_kfree_s(sk, mem, size, true); } EXPORT_SYMBOL(sock_kzfree_s); /* It is almost wait_for_tcp_memory minus release_sock/lock_sock. I think, these locks should be removed for datagram sockets. */ static long sock_wait_for_wmem(struct sock *sk, long timeo) { DEFINE_WAIT(wait); sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); for (;;) { if (!timeo) break; if (signal_pending(current)) break; set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) break; if (sk->sk_shutdown & SEND_SHUTDOWN) break; if (sk->sk_err) break; timeo = schedule_timeout(timeo); } finish_wait(sk_sleep(sk), &wait); return timeo; } /* * Generic send/receive buffer handlers */ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, unsigned long data_len, int noblock, int *errcode, int max_page_order) { struct sk_buff *skb; long timeo; int err; timeo = sock_sndtimeo(sk, noblock); for (;;) { err = sock_error(sk); if (err != 0) goto failure; err = -EPIPE; if (sk->sk_shutdown & SEND_SHUTDOWN) goto failure; if (sk_wmem_alloc_get(sk) < sk->sk_sndbuf) break; sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); err = -EAGAIN; if (!timeo) goto failure; if (signal_pending(current)) goto interrupted; timeo = sock_wait_for_wmem(sk, timeo); } skb = alloc_skb_with_frags(header_len, data_len, max_page_order, errcode, sk->sk_allocation); if (skb) skb_set_owner_w(skb, sk); return skb; interrupted: err = sock_intr_errno(timeo); failure: *errcode = err; return NULL; } EXPORT_SYMBOL(sock_alloc_send_pskb); struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size, int noblock, int *errcode) { return sock_alloc_send_pskb(sk, size, 0, noblock, errcode, 0); } EXPORT_SYMBOL(sock_alloc_send_skb); int __sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct cmsghdr *cmsg, struct sockcm_cookie *sockc) { u32 tsflags; switch (cmsg->cmsg_type) { case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) return -EINVAL; sockc->mark = *(u32 *)CMSG_DATA(cmsg); break; case SO_TIMESTAMPING: if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) return -EINVAL; tsflags = *(u32 *)CMSG_DATA(cmsg); if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK) return -EINVAL; sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK; sockc->tsflags |= tsflags; break; /* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */ case SCM_RIGHTS: case SCM_CREDENTIALS: break; default: return -EINVAL; } return 0; } EXPORT_SYMBOL(__sock_cmsg_send); int sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct sockcm_cookie *sockc) { struct cmsghdr *cmsg; int ret; for_each_cmsghdr(cmsg, msg) { if (!CMSG_OK(msg, cmsg)) return -EINVAL; if (cmsg->cmsg_level != SOL_SOCKET) continue; ret = __sock_cmsg_send(sk, msg, cmsg, sockc); if (ret) return ret; } return 0; } EXPORT_SYMBOL(sock_cmsg_send); /* On 32bit arches, an skb frag is limited to 2^15 */ #define SKB_FRAG_PAGE_ORDER get_order(32768) /** * skb_page_frag_refill - check that a page_frag contains enough room * @sz: minimum size of the fragment we want to get * @pfrag: pointer to page_frag * @gfp: priority for memory allocation * * Note: While this allocator tries to use high order pages, there is * no guarantee that allocations succeed. Therefore, @sz MUST be * less or equal than PAGE_SIZE. */ bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp) { if (pfrag->page) { if (page_ref_count(pfrag->page) == 1) { pfrag->offset = 0; return true; } if (pfrag->offset + sz <= pfrag->size) return true; put_page(pfrag->page); } pfrag->offset = 0; if (SKB_FRAG_PAGE_ORDER) { /* Avoid direct reclaim but allow kswapd to wake */ pfrag->page = alloc_pages((gfp & ~__GFP_DIRECT_RECLAIM) | __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY, SKB_FRAG_PAGE_ORDER); if (likely(pfrag->page)) { pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER; return true; } } pfrag->page = alloc_page(gfp); if (likely(pfrag->page)) { pfrag->size = PAGE_SIZE; return true; } return false; } EXPORT_SYMBOL(skb_page_frag_refill); bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag) { if (likely(skb_page_frag_refill(32U, pfrag, sk->sk_allocation))) return true; sk_enter_memory_pressure(sk); sk_stream_moderate_sndbuf(sk); return false; } EXPORT_SYMBOL(sk_page_frag_refill); static void __lock_sock(struct sock *sk) __releases(&sk->sk_lock.slock) __acquires(&sk->sk_lock.slock) { DEFINE_WAIT(wait); for (;;) { prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait, TASK_UNINTERRUPTIBLE); spin_unlock_bh(&sk->sk_lock.slock); schedule(); spin_lock_bh(&sk->sk_lock.slock); if (!sock_owned_by_user(sk)) break; } finish_wait(&sk->sk_lock.wq, &wait); } static void __release_sock(struct sock *sk) __releases(&sk->sk_lock.slock) __acquires(&sk->sk_lock.slock) { struct sk_buff *skb, *next; while ((skb = sk->sk_backlog.head) != NULL) { sk->sk_backlog.head = sk->sk_backlog.tail = NULL; spin_unlock_bh(&sk->sk_lock.slock); do { next = skb->next; prefetch(next); WARN_ON_ONCE(skb_dst_is_noref(skb)); skb->next = NULL; sk_backlog_rcv(sk, skb); cond_resched(); skb = next; } while (skb != NULL); spin_lock_bh(&sk->sk_lock.slock); } /* * Doing the zeroing here guarantee we can not loop forever * while a wild producer attempts to flood us. */ sk->sk_backlog.len = 0; } void __sk_flush_backlog(struct sock *sk) { spin_lock_bh(&sk->sk_lock.slock); __release_sock(sk); spin_unlock_bh(&sk->sk_lock.slock); } /** * sk_wait_data - wait for data to arrive at sk_receive_queue * @sk: sock to wait on * @timeo: for how long * @skb: last skb seen on sk_receive_queue * * Now socket state including sk->sk_err is changed only under lock, * hence we may omit checks after joining wait queue. * We check receive queue before schedule() only as optimization; * it is very likely that release_sock() added new data. */ int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb) { int rc; DEFINE_WAIT(wait); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk); rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb); sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk); finish_wait(sk_sleep(sk), &wait); return rc; } EXPORT_SYMBOL(sk_wait_data); /** * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated * @sk: socket * @size: memory size to allocate * @kind: allocation type * * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means * rmem allocation. This function assumes that protocols which have * memory_pressure use sk_wmem_queued as write buffer accounting. */ int __sk_mem_schedule(struct sock *sk, int size, int kind) { struct proto *prot = sk->sk_prot; int amt = sk_mem_pages(size); long allocated; sk->sk_forward_alloc += amt * SK_MEM_QUANTUM; allocated = sk_memory_allocated_add(sk, amt); if (mem_cgroup_sockets_enabled && sk->sk_memcg && !mem_cgroup_charge_skmem(sk->sk_memcg, amt)) goto suppress_allocation; /* Under limit. */ if (allocated <= sk_prot_mem_limits(sk, 0)) { sk_leave_memory_pressure(sk); return 1; } /* Under pressure. */ if (allocated > sk_prot_mem_limits(sk, 1)) sk_enter_memory_pressure(sk); /* Over hard limit. */ if (allocated > sk_prot_mem_limits(sk, 2)) goto suppress_allocation; /* guarantee minimum buffer size under pressure */ if (kind == SK_MEM_RECV) { if (atomic_read(&sk->sk_rmem_alloc) < prot->sysctl_rmem[0]) return 1; } else { /* SK_MEM_SEND */ if (sk->sk_type == SOCK_STREAM) { if (sk->sk_wmem_queued < prot->sysctl_wmem[0]) return 1; } else if (atomic_read(&sk->sk_wmem_alloc) < prot->sysctl_wmem[0]) return 1; } if (sk_has_memory_pressure(sk)) { int alloc; if (!sk_under_memory_pressure(sk)) return 1; alloc = sk_sockets_allocated_read_positive(sk); if (sk_prot_mem_limits(sk, 2) > alloc * sk_mem_pages(sk->sk_wmem_queued + atomic_read(&sk->sk_rmem_alloc) + sk->sk_forward_alloc)) return 1; } suppress_allocation: if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) { sk_stream_moderate_sndbuf(sk); /* Fail only if socket is _under_ its sndbuf. * In this case we cannot block, so that we have to fail. */ if (sk->sk_wmem_queued + size >= sk->sk_sndbuf) return 1; } trace_sock_exceed_buf_limit(sk, prot, allocated); /* Alas. Undo changes. */ sk->sk_forward_alloc -= amt * SK_MEM_QUANTUM; sk_memory_allocated_sub(sk, amt); if (mem_cgroup_sockets_enabled && sk->sk_memcg) mem_cgroup_uncharge_skmem(sk->sk_memcg, amt); return 0; } EXPORT_SYMBOL(__sk_mem_schedule); /** * __sk_mem_reclaim - reclaim memory_allocated * @sk: socket * @amount: number of bytes (rounded down to a SK_MEM_QUANTUM multiple) */ void __sk_mem_reclaim(struct sock *sk, int amount) { amount >>= SK_MEM_QUANTUM_SHIFT; sk_memory_allocated_sub(sk, amount); sk->sk_forward_alloc -= amount << SK_MEM_QUANTUM_SHIFT; if (mem_cgroup_sockets_enabled && sk->sk_memcg) mem_cgroup_uncharge_skmem(sk->sk_memcg, amount); if (sk_under_memory_pressure(sk) && (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0))) sk_leave_memory_pressure(sk); } EXPORT_SYMBOL(__sk_mem_reclaim); int sk_set_peek_off(struct sock *sk, int val) { if (val < 0) return -EINVAL; sk->sk_peek_off = val; return 0; } EXPORT_SYMBOL_GPL(sk_set_peek_off); /* * Set of default routines for initialising struct proto_ops when * the protocol does not support a particular function. In certain * cases where it makes no sense for a protocol to have a "do nothing" * function, some default processing is provided. */ int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_bind); int sock_no_connect(struct socket *sock, struct sockaddr *saddr, int len, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_connect); int sock_no_socketpair(struct socket *sock1, struct socket *sock2) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_socketpair); int sock_no_accept(struct socket *sock, struct socket *newsock, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_accept); int sock_no_getname(struct socket *sock, struct sockaddr *saddr, int *len, int peer) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_getname); unsigned int sock_no_poll(struct file *file, struct socket *sock, poll_table *pt) { return 0; } EXPORT_SYMBOL(sock_no_poll); int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_ioctl); int sock_no_listen(struct socket *sock, int backlog) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_listen); int sock_no_shutdown(struct socket *sock, int how) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_shutdown); int sock_no_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_setsockopt); int sock_no_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_getsockopt); int sock_no_sendmsg(struct socket *sock, struct msghdr *m, size_t len) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_sendmsg); int sock_no_recvmsg(struct socket *sock, struct msghdr *m, size_t len, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_recvmsg); int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma) { /* Mirror missing mmap method error code */ return -ENODEV; } EXPORT_SYMBOL(sock_no_mmap); ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { ssize_t res; struct msghdr msg = {.msg_flags = flags}; struct kvec iov; char *kaddr = kmap(page); iov.iov_base = kaddr + offset; iov.iov_len = size; res = kernel_sendmsg(sock, &msg, &iov, 1, size); kunmap(page); return res; } EXPORT_SYMBOL(sock_no_sendpage); /* * Default Socket Callbacks */ static void sock_def_wakeup(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_all(&wq->wait); rcu_read_unlock(); } static void sock_def_error_report(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_poll(&wq->wait, POLLERR); sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR); rcu_read_unlock(); } static void sock_def_readable(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND); sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); rcu_read_unlock(); } static void sock_def_write_space(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); /* Do not wake up a writer until he can make "significant" * progress. --DaveM */ if ((atomic_read(&sk->sk_wmem_alloc) << 1) <= sk->sk_sndbuf) { wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLOUT | POLLWRNORM | POLLWRBAND); /* Should agree with poll, otherwise some programs break */ if (sock_writeable(sk)) sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT); } rcu_read_unlock(); } static void sock_def_destruct(struct sock *sk) { } void sk_send_sigurg(struct sock *sk) { if (sk->sk_socket && sk->sk_socket->file) if (send_sigurg(&sk->sk_socket->file->f_owner)) sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI); } EXPORT_SYMBOL(sk_send_sigurg); void sk_reset_timer(struct sock *sk, struct timer_list* timer, unsigned long expires) { if (!mod_timer(timer, expires)) sock_hold(sk); } EXPORT_SYMBOL(sk_reset_timer); void sk_stop_timer(struct sock *sk, struct timer_list* timer) { if (del_timer(timer)) __sock_put(sk); } EXPORT_SYMBOL(sk_stop_timer); void sock_init_data(struct socket *sock, struct sock *sk) { skb_queue_head_init(&sk->sk_receive_queue); skb_queue_head_init(&sk->sk_write_queue); skb_queue_head_init(&sk->sk_error_queue); sk->sk_send_head = NULL; init_timer(&sk->sk_timer); sk->sk_allocation = GFP_KERNEL; sk->sk_rcvbuf = sysctl_rmem_default; sk->sk_sndbuf = sysctl_wmem_default; sk->sk_state = TCP_CLOSE; sk_set_socket(sk, sock); sock_set_flag(sk, SOCK_ZAPPED); if (sock) { sk->sk_type = sock->type; sk->sk_wq = sock->wq; sock->sk = sk; } else sk->sk_wq = NULL; rwlock_init(&sk->sk_callback_lock); lockdep_set_class_and_name(&sk->sk_callback_lock, af_callback_keys + sk->sk_family, af_family_clock_key_strings[sk->sk_family]); sk->sk_state_change = sock_def_wakeup; sk->sk_data_ready = sock_def_readable; sk->sk_write_space = sock_def_write_space; sk->sk_error_report = sock_def_error_report; sk->sk_destruct = sock_def_destruct; sk->sk_frag.page = NULL; sk->sk_frag.offset = 0; sk->sk_peek_off = -1; sk->sk_peer_pid = NULL; sk->sk_peer_cred = NULL; sk->sk_write_pending = 0; sk->sk_rcvlowat = 1; sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT; sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT; sk->sk_stamp = ktime_set(-1L, 0); #ifdef CONFIG_NET_RX_BUSY_POLL sk->sk_napi_id = 0; sk->sk_ll_usec = sysctl_net_busy_read; #endif sk->sk_max_pacing_rate = ~0U; sk->sk_pacing_rate = ~0U; sk->sk_incoming_cpu = -1; /* * Before updating sk_refcnt, we must commit prior changes to memory * (Documentation/RCU/rculist_nulls.txt for details) */ smp_wmb(); atomic_set(&sk->sk_refcnt, 1); atomic_set(&sk->sk_drops, 0); } EXPORT_SYMBOL(sock_init_data); void lock_sock_nested(struct sock *sk, int subclass) { might_sleep(); spin_lock_bh(&sk->sk_lock.slock); if (sk->sk_lock.owned) __lock_sock(sk); sk->sk_lock.owned = 1; spin_unlock(&sk->sk_lock.slock); /* * The sk_lock has mutex_lock() semantics here: */ mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_); local_bh_enable(); } EXPORT_SYMBOL(lock_sock_nested); void release_sock(struct sock *sk) { spin_lock_bh(&sk->sk_lock.slock); if (sk->sk_backlog.tail) __release_sock(sk); /* Warning : release_cb() might need to release sk ownership, * ie call sock_release_ownership(sk) before us. */ if (sk->sk_prot->release_cb) sk->sk_prot->release_cb(sk); sock_release_ownership(sk); if (waitqueue_active(&sk->sk_lock.wq)) wake_up(&sk->sk_lock.wq); spin_unlock_bh(&sk->sk_lock.slock); } EXPORT_SYMBOL(release_sock); /** * lock_sock_fast - fast version of lock_sock * @sk: socket * * This version should be used for very small section, where process wont block * return false if fast path is taken * sk_lock.slock locked, owned = 0, BH disabled * return true if slow path is taken * sk_lock.slock unlocked, owned = 1, BH enabled */ bool lock_sock_fast(struct sock *sk) { might_sleep(); spin_lock_bh(&sk->sk_lock.slock); if (!sk->sk_lock.owned) /* * Note : We must disable BH */ return false; __lock_sock(sk); sk->sk_lock.owned = 1; spin_unlock(&sk->sk_lock.slock); /* * The sk_lock has mutex_lock() semantics here: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 0, _RET_IP_); local_bh_enable(); return true; } EXPORT_SYMBOL(lock_sock_fast); int sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp) { struct timeval tv; if (!sock_flag(sk, SOCK_TIMESTAMP)) sock_enable_timestamp(sk, SOCK_TIMESTAMP); tv = ktime_to_timeval(sk->sk_stamp); if (tv.tv_sec == -1) return -ENOENT; if (tv.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); tv = ktime_to_timeval(sk->sk_stamp); } return copy_to_user(userstamp, &tv, sizeof(tv)) ? -EFAULT : 0; } EXPORT_SYMBOL(sock_get_timestamp); int sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp) { struct timespec ts; if (!sock_flag(sk, SOCK_TIMESTAMP)) sock_enable_timestamp(sk, SOCK_TIMESTAMP); ts = ktime_to_timespec(sk->sk_stamp); if (ts.tv_sec == -1) return -ENOENT; if (ts.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); ts = ktime_to_timespec(sk->sk_stamp); } return copy_to_user(userstamp, &ts, sizeof(ts)) ? -EFAULT : 0; } EXPORT_SYMBOL(sock_get_timestampns); void sock_enable_timestamp(struct sock *sk, int flag) { if (!sock_flag(sk, flag)) { unsigned long previous_flags = sk->sk_flags; sock_set_flag(sk, flag); /* * we just set one of the two flags which require net * time stamping, but time stamping might have been on * already because of the other one */ if (sock_needs_netstamp(sk) && !(previous_flags & SK_FLAGS_TIMESTAMP)) net_enable_timestamp(); } } int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len, int level, int type) { struct sock_exterr_skb *serr; struct sk_buff *skb; int copied, err; err = -EAGAIN; skb = sock_dequeue_err_skb(sk); if (skb == NULL) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_msg(skb, 0, msg, copied); if (err) goto out_free_skb; sock_recv_timestamp(msg, sk, skb); serr = SKB_EXT_ERR(skb); put_cmsg(msg, level, type, sizeof(serr->ee), &serr->ee); msg->msg_flags |= MSG_ERRQUEUE; err = copied; out_free_skb: kfree_skb(skb); out: return err; } EXPORT_SYMBOL(sock_recv_errqueue); /* * Get a socket option on an socket. * * FIX: POSIX 1003.1g is very ambiguous here. It states that * asynchronous errors should be reported by getsockopt. We assume * this means if you specify SO_ERROR (otherwise whats the point of it). */ int sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(sock_common_getsockopt); #ifdef CONFIG_COMPAT int compat_sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; if (sk->sk_prot->compat_getsockopt != NULL) return sk->sk_prot->compat_getsockopt(sk, level, optname, optval, optlen); return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_sock_common_getsockopt); #endif int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int addr_len = 0; int err; err = sk->sk_prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT, flags & ~MSG_DONTWAIT, &addr_len); if (err >= 0) msg->msg_namelen = addr_len; return err; } EXPORT_SYMBOL(sock_common_recvmsg); /* * Set socket options on an inet socket. */ int sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(sock_common_setsockopt); #ifdef CONFIG_COMPAT int compat_sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; if (sk->sk_prot->compat_setsockopt != NULL) return sk->sk_prot->compat_setsockopt(sk, level, optname, optval, optlen); return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_sock_common_setsockopt); #endif void sk_common_release(struct sock *sk) { if (sk->sk_prot->destroy) sk->sk_prot->destroy(sk); /* * Observation: when sock_common_release is called, processes have * no access to socket. But net still has. * Step one, detach it from networking: * * A. Remove from hash tables. */ sk->sk_prot->unhash(sk); /* * In this point socket cannot receive new packets, but it is possible * that some packets are in flight because some CPU runs receiver and * did hash table lookup before we unhashed socket. They will achieve * receive queue and will be purged by socket destructor. * * Also we still have packets pending on receive queue and probably, * our own packets waiting in device queues. sock_destroy will drain * receive queue, but transmitted packets will delay socket destruction * until the last reference will be released. */ sock_orphan(sk); xfrm_sk_free_policy(sk); sk_refcnt_debug_release(sk); if (sk->sk_frag.page) { put_page(sk->sk_frag.page); sk->sk_frag.page = NULL; } sock_put(sk); } EXPORT_SYMBOL(sk_common_release); #ifdef CONFIG_PROC_FS #define PROTO_INUSE_NR 64 /* should be enough for the first time */ struct prot_inuse { int val[PROTO_INUSE_NR]; }; static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR); #ifdef CONFIG_NET_NS void sock_prot_inuse_add(struct net *net, struct proto *prot, int val) { __this_cpu_add(net->core.inuse->val[prot->inuse_idx], val); } EXPORT_SYMBOL_GPL(sock_prot_inuse_add); int sock_prot_inuse_get(struct net *net, struct proto *prot) { int cpu, idx = prot->inuse_idx; int res = 0; for_each_possible_cpu(cpu) res += per_cpu_ptr(net->core.inuse, cpu)->val[idx]; return res >= 0 ? res : 0; } EXPORT_SYMBOL_GPL(sock_prot_inuse_get); static int __net_init sock_inuse_init_net(struct net *net) { net->core.inuse = alloc_percpu(struct prot_inuse); return net->core.inuse ? 0 : -ENOMEM; } static void __net_exit sock_inuse_exit_net(struct net *net) { free_percpu(net->core.inuse); } static struct pernet_operations net_inuse_ops = { .init = sock_inuse_init_net, .exit = sock_inuse_exit_net, }; static __init int net_inuse_init(void) { if (register_pernet_subsys(&net_inuse_ops)) panic("Cannot initialize net inuse counters"); return 0; } core_initcall(net_inuse_init); #else static DEFINE_PER_CPU(struct prot_inuse, prot_inuse); void sock_prot_inuse_add(struct net *net, struct proto *prot, int val) { __this_cpu_add(prot_inuse.val[prot->inuse_idx], val); } EXPORT_SYMBOL_GPL(sock_prot_inuse_add); int sock_prot_inuse_get(struct net *net, struct proto *prot) { int cpu, idx = prot->inuse_idx; int res = 0; for_each_possible_cpu(cpu) res += per_cpu(prot_inuse, cpu).val[idx]; return res >= 0 ? res : 0; } EXPORT_SYMBOL_GPL(sock_prot_inuse_get); #endif static void assign_proto_idx(struct proto *prot) { prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR); if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) { pr_err("PROTO_INUSE_NR exhausted\n"); return; } set_bit(prot->inuse_idx, proto_inuse_idx); } static void release_proto_idx(struct proto *prot) { if (prot->inuse_idx != PROTO_INUSE_NR - 1) clear_bit(prot->inuse_idx, proto_inuse_idx); } #else static inline void assign_proto_idx(struct proto *prot) { } static inline void release_proto_idx(struct proto *prot) { } #endif static void req_prot_cleanup(struct request_sock_ops *rsk_prot) { if (!rsk_prot) return; kfree(rsk_prot->slab_name); rsk_prot->slab_name = NULL; kmem_cache_destroy(rsk_prot->slab); rsk_prot->slab = NULL; } static int req_prot_init(const struct proto *prot) { struct request_sock_ops *rsk_prot = prot->rsk_prot; if (!rsk_prot) return 0; rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s", prot->name); if (!rsk_prot->slab_name) return -ENOMEM; rsk_prot->slab = kmem_cache_create(rsk_prot->slab_name, rsk_prot->obj_size, 0, prot->slab_flags, NULL); if (!rsk_prot->slab) { pr_crit("%s: Can't create request sock SLAB cache!\n", prot->name); return -ENOMEM; } return 0; } int proto_register(struct proto *prot, int alloc_slab) { if (alloc_slab) { prot->slab = kmem_cache_create(prot->name, prot->obj_size, 0, SLAB_HWCACHE_ALIGN | prot->slab_flags, NULL); if (prot->slab == NULL) { pr_crit("%s: Can't create sock SLAB cache!\n", prot->name); goto out; } if (req_prot_init(prot)) goto out_free_request_sock_slab; if (prot->twsk_prot != NULL) { prot->twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", prot->name); if (prot->twsk_prot->twsk_slab_name == NULL) goto out_free_request_sock_slab; prot->twsk_prot->twsk_slab = kmem_cache_create(prot->twsk_prot->twsk_slab_name, prot->twsk_prot->twsk_obj_size, 0, prot->slab_flags, NULL); if (prot->twsk_prot->twsk_slab == NULL) goto out_free_timewait_sock_slab_name; } } mutex_lock(&proto_list_mutex); list_add(&prot->node, &proto_list); assign_proto_idx(prot); mutex_unlock(&proto_list_mutex); return 0; out_free_timewait_sock_slab_name: kfree(prot->twsk_prot->twsk_slab_name); out_free_request_sock_slab: req_prot_cleanup(prot->rsk_prot); kmem_cache_destroy(prot->slab); prot->slab = NULL; out: return -ENOBUFS; } EXPORT_SYMBOL(proto_register); void proto_unregister(struct proto *prot) { mutex_lock(&proto_list_mutex); release_proto_idx(prot); list_del(&prot->node); mutex_unlock(&proto_list_mutex); kmem_cache_destroy(prot->slab); prot->slab = NULL; req_prot_cleanup(prot->rsk_prot); if (prot->twsk_prot != NULL && prot->twsk_prot->twsk_slab != NULL) { kmem_cache_destroy(prot->twsk_prot->twsk_slab); kfree(prot->twsk_prot->twsk_slab_name); prot->twsk_prot->twsk_slab = NULL; } } EXPORT_SYMBOL(proto_unregister); #ifdef CONFIG_PROC_FS static void *proto_seq_start(struct seq_file *seq, loff_t *pos) __acquires(proto_list_mutex) { mutex_lock(&proto_list_mutex); return seq_list_start_head(&proto_list, *pos); } static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &proto_list, pos); } static void proto_seq_stop(struct seq_file *seq, void *v) __releases(proto_list_mutex) { mutex_unlock(&proto_list_mutex); } static char proto_method_implemented(const void *method) { return method == NULL ? 'n' : 'y'; } static long sock_prot_memory_allocated(struct proto *proto) { return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L; } static char *sock_prot_memory_pressure(struct proto *proto) { return proto->memory_pressure != NULL ? proto_memory_pressure(proto) ? "yes" : "no" : "NI"; } static void proto_seq_printf(struct seq_file *seq, struct proto *proto) { seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s " "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n", proto->name, proto->obj_size, sock_prot_inuse_get(seq_file_net(seq), proto), sock_prot_memory_allocated(proto), sock_prot_memory_pressure(proto), proto->max_header, proto->slab == NULL ? "no" : "yes", module_name(proto->owner), proto_method_implemented(proto->close), proto_method_implemented(proto->connect), proto_method_implemented(proto->disconnect), proto_method_implemented(proto->accept), proto_method_implemented(proto->ioctl), proto_method_implemented(proto->init), proto_method_implemented(proto->destroy), proto_method_implemented(proto->shutdown), proto_method_implemented(proto->setsockopt), proto_method_implemented(proto->getsockopt), proto_method_implemented(proto->sendmsg), proto_method_implemented(proto->recvmsg), proto_method_implemented(proto->sendpage), proto_method_implemented(proto->bind), proto_method_implemented(proto->backlog_rcv), proto_method_implemented(proto->hash), proto_method_implemented(proto->unhash), proto_method_implemented(proto->get_port), proto_method_implemented(proto->enter_memory_pressure)); } static int proto_seq_show(struct seq_file *seq, void *v) { if (v == &proto_list) seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s", "protocol", "size", "sockets", "memory", "press", "maxhdr", "slab", "module", "cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n"); else proto_seq_printf(seq, list_entry(v, struct proto, node)); return 0; } static const struct seq_operations proto_seq_ops = { .start = proto_seq_start, .next = proto_seq_next, .stop = proto_seq_stop, .show = proto_seq_show, }; static int proto_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &proto_seq_ops, sizeof(struct seq_net_private)); } static const struct file_operations proto_seq_fops = { .owner = THIS_MODULE, .open = proto_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static __net_init int proto_init_net(struct net *net) { if (!proc_create("protocols", S_IRUGO, net->proc_net, &proto_seq_fops)) return -ENOMEM; return 0; } static __net_exit void proto_exit_net(struct net *net) { remove_proc_entry("protocols", net->proc_net); } static __net_initdata struct pernet_operations proto_net_ops = { .init = proto_init_net, .exit = proto_exit_net, }; static int __init proto_init(void) { return register_pernet_subsys(&proto_net_ops); } subsys_initcall(proto_init); #endif /* PROC_FS */
./CrossVul/dataset_final_sorted/CWE-119/c/good_5502_0
crossvul-cpp_data_good_5286_1
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Andrei Zmievski <andrei@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_WDDX #include "ext/xml/expat_compat.h" #include "php_wddx.h" #include "php_wddx_api.h" #define PHP_XML_INTERNAL #include "ext/xml/php_xml.h" #include "ext/standard/php_incomplete_class.h" #include "ext/standard/base64.h" #include "ext/standard/info.h" #include "ext/standard/php_smart_str.h" #include "ext/standard/html.h" #include "ext/standard/php_string.h" #include "ext/date/php_date.h" #include "zend_globals.h" #define WDDX_BUF_LEN 256 #define PHP_CLASS_NAME_VAR "php_class_name" #define EL_ARRAY "array" #define EL_BINARY "binary" #define EL_BOOLEAN "boolean" #define EL_CHAR "char" #define EL_CHAR_CODE "code" #define EL_NULL "null" #define EL_NUMBER "number" #define EL_PACKET "wddxPacket" #define EL_STRING "string" #define EL_STRUCT "struct" #define EL_VALUE "value" #define EL_VAR "var" #define EL_NAME "name" #define EL_VERSION "version" #define EL_RECORDSET "recordset" #define EL_FIELD "field" #define EL_DATETIME "dateTime" #define php_wddx_deserialize(a,b) \ php_wddx_deserialize_ex((a)->value.str.val, (a)->value.str.len, (b)) #define SET_STACK_VARNAME \ if (stack->varname) { \ ent.varname = estrdup(stack->varname); \ efree(stack->varname); \ stack->varname = NULL; \ } else \ ent.varname = NULL; \ static int le_wddx; typedef struct { zval *data; enum { ST_ARRAY, ST_BOOLEAN, ST_NULL, ST_NUMBER, ST_STRING, ST_BINARY, ST_STRUCT, ST_RECORDSET, ST_FIELD, ST_DATETIME } type; char *varname; } st_entry; typedef struct { int top, max; char *varname; zend_bool done; void **elements; } wddx_stack; static void php_wddx_process_data(void *user_data, const XML_Char *s, int len); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_value, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_vars, 0, 0, 1) ZEND_ARG_VARIADIC_INFO(0, var_names) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_start, 0, 0, 0) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_packet_end, 0, 0, 1) ZEND_ARG_INFO(0, packet_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_add_vars, 0, 0, 2) ZEND_ARG_INFO(0, packet_id) ZEND_ARG_VARIADIC_INFO(0, var_names) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_deserialize, 0, 0, 1) ZEND_ARG_INFO(0, packet) ZEND_END_ARG_INFO() /* }}} */ /* {{{ wddx_functions[] */ const zend_function_entry wddx_functions[] = { PHP_FE(wddx_serialize_value, arginfo_wddx_serialize_value) PHP_FE(wddx_serialize_vars, arginfo_wddx_serialize_vars) PHP_FE(wddx_packet_start, arginfo_wddx_serialize_start) PHP_FE(wddx_packet_end, arginfo_wddx_packet_end) PHP_FE(wddx_add_vars, arginfo_wddx_add_vars) PHP_FE(wddx_deserialize, arginfo_wddx_deserialize) PHP_FE_END }; /* }}} */ PHP_MINIT_FUNCTION(wddx); PHP_MINFO_FUNCTION(wddx); /* {{{ dynamically loadable module stuff */ #ifdef COMPILE_DL_WDDX ZEND_GET_MODULE(wddx) #endif /* COMPILE_DL_WDDX */ /* }}} */ /* {{{ wddx_module_entry */ zend_module_entry wddx_module_entry = { STANDARD_MODULE_HEADER, "wddx", wddx_functions, PHP_MINIT(wddx), NULL, NULL, NULL, PHP_MINFO(wddx), NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; /* }}} */ /* {{{ wddx_stack_init */ static int wddx_stack_init(wddx_stack *stack) { stack->top = 0; stack->elements = (void **) safe_emalloc(sizeof(void **), STACK_BLOCK_SIZE, 0); stack->max = STACK_BLOCK_SIZE; stack->varname = NULL; stack->done = 0; return SUCCESS; } /* }}} */ /* {{{ wddx_stack_push */ static int wddx_stack_push(wddx_stack *stack, void *element, int size) { if (stack->top >= stack->max) { /* we need to allocate more memory */ stack->elements = (void **) erealloc(stack->elements, (sizeof(void **) * (stack->max += STACK_BLOCK_SIZE))); } stack->elements[stack->top] = (void *) emalloc(size); memcpy(stack->elements[stack->top], element, size); return stack->top++; } /* }}} */ /* {{{ wddx_stack_top */ static int wddx_stack_top(wddx_stack *stack, void **element) { if (stack->top > 0) { *element = stack->elements[stack->top - 1]; return SUCCESS; } else { *element = NULL; return FAILURE; } } /* }}} */ /* {{{ wddx_stack_is_empty */ static int wddx_stack_is_empty(wddx_stack *stack) { if (stack->top == 0) { return 1; } else { return 0; } } /* }}} */ /* {{{ wddx_stack_destroy */ static int wddx_stack_destroy(wddx_stack *stack) { register int i; if (stack->elements) { for (i = 0; i < stack->top; i++) { if (((st_entry *)stack->elements[i])->data && ((st_entry *)stack->elements[i])->type != ST_FIELD) { zval_ptr_dtor(&((st_entry *)stack->elements[i])->data); } if (((st_entry *)stack->elements[i])->varname) { efree(((st_entry *)stack->elements[i])->varname); } efree(stack->elements[i]); } efree(stack->elements); } return SUCCESS; } /* }}} */ /* {{{ release_wddx_packet_rsrc */ static void release_wddx_packet_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC) { smart_str *str = (smart_str *)rsrc->ptr; smart_str_free(str); efree(str); } /* }}} */ #include "ext/session/php_session.h" #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) /* {{{ PS_SERIALIZER_ENCODE_FUNC */ PS_SERIALIZER_ENCODE_FUNC(wddx) { wddx_packet *packet; PS_ENCODE_VARS; packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); PS_ENCODE_LOOP( php_wddx_serialize_var(packet, *struc, key, key_length TSRMLS_CC); ); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); *newstr = php_wddx_gather(packet); php_wddx_destructor(packet); if (newlen) { *newlen = strlen(*newstr); } return SUCCESS; } /* }}} */ /* {{{ PS_SERIALIZER_DECODE_FUNC */ PS_SERIALIZER_DECODE_FUNC(wddx) { zval *retval; zval **ent; char *key; uint key_length; char tmp[128]; ulong idx; int hash_type; int ret; if (vallen == 0) { return SUCCESS; } MAKE_STD_ZVAL(retval); if ((ret = php_wddx_deserialize_ex((char *)val, vallen, retval)) == SUCCESS) { if (Z_TYPE_P(retval) != IS_ARRAY) { zval_ptr_dtor(&retval); return FAILURE; } for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(retval)); zend_hash_get_current_data(Z_ARRVAL_P(retval), (void **) &ent) == SUCCESS; zend_hash_move_forward(Z_ARRVAL_P(retval))) { hash_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(retval), &key, &key_length, &idx, 0, NULL); switch (hash_type) { case HASH_KEY_IS_LONG: key_length = slprintf(tmp, sizeof(tmp), "%ld", idx) + 1; key = tmp; /* fallthru */ case HASH_KEY_IS_STRING: php_set_session_var(key, key_length-1, *ent, NULL TSRMLS_CC); PS_ADD_VAR(key); } } } zval_ptr_dtor(&retval); return ret; } /* }}} */ #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(wddx) { le_wddx = zend_register_list_destructors_ex(release_wddx_packet_rsrc, NULL, "wddx", module_number); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_session_register_serializer("wddx", PS_SERIALIZER_ENCODE_NAME(wddx), PS_SERIALIZER_DECODE_NAME(wddx)); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(wddx) { php_info_print_table_start(); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_info_print_table_header(2, "WDDX Support", "enabled" ); php_info_print_table_row(2, "WDDX Session Serializer", "enabled" ); #else php_info_print_table_row(2, "WDDX Support", "enabled" ); #endif php_info_print_table_end(); } /* }}} */ /* {{{ php_wddx_packet_start */ void php_wddx_packet_start(wddx_packet *packet, char *comment, int comment_len) { php_wddx_add_chunk_static(packet, WDDX_PACKET_S); if (comment) { char *escaped; size_t escaped_len; TSRMLS_FETCH(); escaped = php_escape_html_entities( comment, comment_len, &escaped_len, 0, ENT_QUOTES, NULL TSRMLS_CC); php_wddx_add_chunk_static(packet, WDDX_HEADER_S); php_wddx_add_chunk_static(packet, WDDX_COMMENT_S); php_wddx_add_chunk_ex(packet, escaped, escaped_len); php_wddx_add_chunk_static(packet, WDDX_COMMENT_E); php_wddx_add_chunk_static(packet, WDDX_HEADER_E); str_efree(escaped); } else { php_wddx_add_chunk_static(packet, WDDX_HEADER); } php_wddx_add_chunk_static(packet, WDDX_DATA_S); } /* }}} */ /* {{{ php_wddx_packet_end */ void php_wddx_packet_end(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_DATA_E); php_wddx_add_chunk_static(packet, WDDX_PACKET_E); } /* }}} */ #define FLUSH_BUF() \ if (l > 0) { \ php_wddx_add_chunk_ex(packet, buf, l); \ l = 0; \ } /* {{{ php_wddx_serialize_string */ static void php_wddx_serialize_string(wddx_packet *packet, zval *var TSRMLS_DC) { php_wddx_add_chunk_static(packet, WDDX_STRING_S); if (Z_STRLEN_P(var) > 0) { char *buf; size_t buf_len; buf = php_escape_html_entities(Z_STRVAL_P(var), Z_STRLEN_P(var), &buf_len, 0, ENT_QUOTES, NULL TSRMLS_CC); php_wddx_add_chunk_ex(packet, buf, buf_len); str_efree(buf); } php_wddx_add_chunk_static(packet, WDDX_STRING_E); } /* }}} */ /* {{{ php_wddx_serialize_number */ static void php_wddx_serialize_number(wddx_packet *packet, zval *var) { char tmp_buf[WDDX_BUF_LEN]; zval tmp; tmp = *var; zval_copy_ctor(&tmp); convert_to_string(&tmp); snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, Z_STRVAL(tmp)); zval_dtor(&tmp); php_wddx_add_chunk(packet, tmp_buf); } /* }}} */ /* {{{ php_wddx_serialize_boolean */ static void php_wddx_serialize_boolean(wddx_packet *packet, zval *var) { php_wddx_add_chunk(packet, Z_LVAL_P(var) ? WDDX_BOOLEAN_TRUE : WDDX_BOOLEAN_FALSE); } /* }}} */ /* {{{ php_wddx_serialize_unset */ static void php_wddx_serialize_unset(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_NULL); } /* }}} */ /* {{{ php_wddx_serialize_object */ static void php_wddx_serialize_object(wddx_packet *packet, zval *obj) { /* OBJECTS_FIXME */ zval **ent, *fname, **varname; zval *retval = NULL; const char *key; ulong idx; char tmp_buf[WDDX_BUF_LEN]; HashTable *objhash, *sleephash; TSRMLS_FETCH(); MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__sleep", 1); /* * We try to call __sleep() method on object. It's supposed to return an * array of property names to be serialized. */ if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) { if (retval && (sleephash = HASH_OF(retval))) { PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); PHP_CLEANUP_CLASS_ATTRIBUTES(); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(sleephash); zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS; zend_hash_move_forward(sleephash)) { if (Z_TYPE_PP(varname) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize."); continue; } if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) { php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } } else { uint key_len; PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); PHP_CLEANUP_CLASS_ATTRIBUTES(); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(objhash); zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS; zend_hash_move_forward(objhash)) { if (*ent == obj) { continue; } if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) { const char *class_name, *prop_name; zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name); php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } /* }}} */ /* {{{ php_wddx_serialize_array */ static void php_wddx_serialize_array(wddx_packet *packet, zval *arr) { zval **ent; char *key; uint key_len; int is_struct = 0, ent_type; ulong idx; HashTable *target_hash; char tmp_buf[WDDX_BUF_LEN]; ulong ind = 0; int type; TSRMLS_FETCH(); target_hash = HASH_OF(arr); for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { type = zend_hash_get_current_key(target_hash, &key, &idx, 0); if (type == HASH_KEY_IS_STRING) { is_struct = 1; break; } if (idx != ind) { is_struct = 1; break; } ind++; } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); } else { snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash)); php_wddx_add_chunk(packet, tmp_buf); } for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { if (*ent == arr) { continue; } if (is_struct) { ent_type = zend_hash_get_current_key_ex(target_hash, &key, &key_len, &idx, 0, NULL); if (ent_type == HASH_KEY_IS_STRING) { php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } else { php_wddx_serialize_var(packet, *ent, NULL, 0 TSRMLS_CC); } } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } else { php_wddx_add_chunk_static(packet, WDDX_ARRAY_E); } } /* }}} */ /* {{{ php_wddx_serialize_var */ void php_wddx_serialize_var(wddx_packet *packet, zval *var, char *name, int name_len TSRMLS_DC) { HashTable *ht; if (name) { size_t name_esc_len; char *tmp_buf, *name_esc; name_esc = php_escape_html_entities(name, name_len, &name_esc_len, 0, ENT_QUOTES, NULL TSRMLS_CC); tmp_buf = emalloc(name_esc_len + sizeof(WDDX_VAR_S)); snprintf(tmp_buf, name_esc_len + sizeof(WDDX_VAR_S), WDDX_VAR_S, name_esc); php_wddx_add_chunk(packet, tmp_buf); efree(tmp_buf); str_efree(name_esc); } switch(Z_TYPE_P(var)) { case IS_STRING: php_wddx_serialize_string(packet, var TSRMLS_CC); break; case IS_LONG: case IS_DOUBLE: php_wddx_serialize_number(packet, var); break; case IS_BOOL: php_wddx_serialize_boolean(packet, var); break; case IS_NULL: php_wddx_serialize_unset(packet); break; case IS_ARRAY: ht = Z_ARRVAL_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_array(packet, var); ht->nApplyCount--; break; case IS_OBJECT: ht = Z_OBJPROP_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_object(packet, var); ht->nApplyCount--; break; } if (name) { php_wddx_add_chunk_static(packet, WDDX_VAR_E); } } /* }}} */ /* {{{ php_wddx_add_var */ static void php_wddx_add_var(wddx_packet *packet, zval *name_var) { zval **val; HashTable *target_hash; TSRMLS_FETCH(); if (Z_TYPE_P(name_var) == IS_STRING) { if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (zend_hash_find(EG(active_symbol_table), Z_STRVAL_P(name_var), Z_STRLEN_P(name_var)+1, (void**)&val) != FAILURE) { php_wddx_serialize_var(packet, *val, Z_STRVAL_P(name_var), Z_STRLEN_P(name_var) TSRMLS_CC); } } else if (Z_TYPE_P(name_var) == IS_ARRAY || Z_TYPE_P(name_var) == IS_OBJECT) { int is_array = Z_TYPE_P(name_var) == IS_ARRAY; target_hash = HASH_OF(name_var); if (is_array && target_hash->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return; } zend_hash_internal_pointer_reset(target_hash); while(zend_hash_get_current_data(target_hash, (void**)&val) == SUCCESS) { if (is_array) { target_hash->nApplyCount++; } php_wddx_add_var(packet, *val); if (is_array) { target_hash->nApplyCount--; } zend_hash_move_forward(target_hash); } } } /* }}} */ /* {{{ php_wddx_push_element */ static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } /* }}} */ /* {{{ php_wddx_pop_element */ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); if (new_str) { Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } else { ZVAL_EMPTY_STRING(ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } /* }}} */ /* {{{ php_wddx_process_data */ static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if(!ent->data) { break; } if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; if (Z_TYPE_P(ent->data) == IS_STRING) { tmp = safe_emalloc(Z_STRLEN_P(ent->data), 1, (size_t)len + 1); memcpy(tmp, Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data)); memcpy(tmp + Z_STRLEN_P(ent->data), s, len); len += Z_STRLEN_P(ent->data); efree(Z_STRVAL_P(ent->data)); Z_TYPE_P(ent->data) = IS_LONG; } else { tmp = emalloc(len + 1); memcpy(tmp, s, len); } tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { ZVAL_STRINGL(ent->data, tmp, len, 0); } else { efree(tmp); } } break; default: break; } } } /* }}} */ /* {{{ php_wddx_deserialize_ex */ int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate("UTF-8"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); XML_Parse(parser, value, vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); if(ent->data == NULL) { retval = FAILURE; } else { *return_value = *(ent->data); zval_copy_ctor(return_value); retval = SUCCESS; } } else { retval = FAILURE; } wddx_stack_destroy(&stack); return retval; } /* }}} */ /* {{{ proto string wddx_serialize_value(mixed var [, string comment]) Creates a new packet and serializes the given value */ PHP_FUNCTION(wddx_serialize_value) { zval *var; char *comment = NULL; int comment_len = 0; wddx_packet *packet; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|s", &var, &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_serialize_var(packet, var, NULL, 0 TSRMLS_CC); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto string wddx_serialize_vars(mixed var_name [, mixed ...]) Creates a new packet and serializes given variables into a struct */ PHP_FUNCTION(wddx_serialize_vars) { int num_args, i; wddx_packet *packet; zval ***args = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, *args[i]); } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); efree(args); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ php_wddx_constructor */ wddx_packet *php_wddx_constructor(void) { smart_str *packet; packet = (smart_str *)emalloc(sizeof(smart_str)); packet->c = NULL; return packet; } /* }}} */ /* {{{ php_wddx_destructor */ void php_wddx_destructor(wddx_packet *packet) { smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto resource wddx_packet_start([string comment]) Starts a WDDX packet with optional comment and returns the packet id */ PHP_FUNCTION(wddx_packet_start) { char *comment = NULL; int comment_len = 0; wddx_packet *packet; comment = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); ZEND_REGISTER_RESOURCE(return_value, packet, le_wddx); } /* }}} */ /* {{{ proto string wddx_packet_end(resource packet_id) Ends specified WDDX packet and returns the string containing the packet */ PHP_FUNCTION(wddx_packet_end) { zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &packet_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); zend_list_delete(Z_LVAL_P(packet_id)); } /* }}} */ /* {{{ proto int wddx_add_vars(resource packet_id, mixed var_names [, mixed ...]) Serializes given variables and adds them to packet given by packet_id */ PHP_FUNCTION(wddx_add_vars) { int num_args, i; zval ***args = NULL; zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r+", &packet_id, &args, &num_args) == FAILURE) { return; } if (!ZEND_FETCH_RESOURCE_NO_RETURN(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx)) { efree(args); RETURN_FALSE; } if (!packet) { efree(args); RETURN_FALSE; } for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, (*args[i])); } efree(args); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed wddx_deserialize(mixed packet) Deserializes given packet and returns a PHP value */ PHP_FUNCTION(wddx_deserialize) { zval *packet; char *payload; int payload_len; php_stream *stream = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &packet) == FAILURE) { return; } if (Z_TYPE_P(packet) == IS_STRING) { payload = Z_STRVAL_P(packet); payload_len = Z_STRLEN_P(packet); } else if (Z_TYPE_P(packet) == IS_RESOURCE) { php_stream_from_zval(stream, &packet); if (stream) { payload_len = php_stream_copy_to_mem(stream, &payload, PHP_STREAM_COPY_ALL, 0); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expecting parameter 1 to be a string or a stream"); return; } if (payload_len == 0) { return; } php_wddx_deserialize_ex(payload, payload_len, return_value); if (stream) { pefree(payload, 0); } } /* }}} */ #endif /* HAVE_LIBEXPAT */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-119/c/good_5286_1
crossvul-cpp_data_good_5182_1
/* +--------------------------------------------------------------------+ | PECL :: http | +--------------------------------------------------------------------+ | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the conditions mentioned | | in the accompanying LICENSE file are met. | +--------------------------------------------------------------------+ | Copyright (c) 2004-2014, Michael Wallner <mike@php.net> | +--------------------------------------------------------------------+ */ #include "php_http_api.h" #if PHP_HTTP_HAVE_IDN2 # include <idn2.h> #elif PHP_HTTP_HAVE_IDN # include <idna.h> #endif #ifdef PHP_HTTP_HAVE_WCHAR # include <wchar.h> # include <wctype.h> #endif #ifdef HAVE_ARPA_INET_H # include <arpa/inet.h> #endif #include "php_http_utf8.h" static inline char *localhostname(void) { char hostname[1024] = {0}; #ifdef PHP_WIN32 if (SUCCESS == gethostname(hostname, lenof(hostname))) { return estrdup(hostname); } #elif defined(HAVE_GETHOSTNAME) if (SUCCESS == gethostname(hostname, lenof(hostname))) { # if defined(HAVE_GETDOMAINNAME) size_t hlen = strlen(hostname); if (hlen <= lenof(hostname) - lenof("(none)")) { hostname[hlen++] = '.'; if (SUCCESS == getdomainname(&hostname[hlen], lenof(hostname) - hlen)) { if (!strcmp(&hostname[hlen], "(none)")) { hostname[hlen - 1] = '\0'; } return estrdup(hostname); } } # endif if (strcmp(hostname, "(none)")) { return estrdup(hostname); } } #endif return estrndup("localhost", lenof("localhost")); } #define url(buf) ((php_http_url_t *) (buf).data) static php_http_url_t *php_http_url_from_env(TSRMLS_D) { zval *https, *zhost, *zport; long port; php_http_buffer_t buf; php_http_buffer_init_ex(&buf, MAX(PHP_HTTP_BUFFER_DEFAULT_SIZE, sizeof(php_http_url_t)<<2), PHP_HTTP_BUFFER_INIT_PREALLOC); php_http_buffer_account(&buf, sizeof(php_http_url_t)); memset(buf.data, 0, buf.used); /* scheme */ url(buf)->scheme = &buf.data[buf.used]; https = php_http_env_get_server_var(ZEND_STRL("HTTPS"), 1 TSRMLS_CC); if (https && !strcasecmp(Z_STRVAL_P(https), "ON")) { php_http_buffer_append(&buf, "https", sizeof("https")); } else { php_http_buffer_append(&buf, "http", sizeof("http")); } /* host */ url(buf)->host = &buf.data[buf.used]; if ((((zhost = php_http_env_get_server_var(ZEND_STRL("HTTP_HOST"), 1 TSRMLS_CC)) || (zhost = php_http_env_get_server_var(ZEND_STRL("SERVER_NAME"), 1 TSRMLS_CC)) || (zhost = php_http_env_get_server_var(ZEND_STRL("SERVER_ADDR"), 1 TSRMLS_CC)))) && Z_STRLEN_P(zhost)) { size_t stop_at = strspn(Z_STRVAL_P(zhost), "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-."); php_http_buffer_append(&buf, Z_STRVAL_P(zhost), stop_at); php_http_buffer_append(&buf, "", 1); } else { char *host_str = localhostname(); php_http_buffer_append(&buf, host_str, strlen(host_str) + 1); efree(host_str); } /* port */ zport = php_http_env_get_server_var(ZEND_STRL("SERVER_PORT"), 1 TSRMLS_CC); if (zport && IS_LONG == is_numeric_string(Z_STRVAL_P(zport), Z_STRLEN_P(zport), &port, NULL, 0)) { url(buf)->port = port; } /* path */ if (SG(request_info).request_uri && SG(request_info).request_uri[0]) { const char *q = strchr(SG(request_info).request_uri, '?'); url(buf)->path = &buf.data[buf.used]; if (q) { php_http_buffer_append(&buf, SG(request_info).request_uri, q - SG(request_info).request_uri); php_http_buffer_append(&buf, "", 1); } else { php_http_buffer_append(&buf, SG(request_info).request_uri, strlen(SG(request_info).request_uri) + 1); } } /* query */ if (SG(request_info).query_string && SG(request_info).query_string[0]) { url(buf)->query = &buf.data[buf.used]; php_http_buffer_append(&buf, SG(request_info).query_string, strlen(SG(request_info).query_string) + 1); } return url(buf); } #define url_isset(u,n) \ ((u)&&(u)->n) #define url_append(buf, append) do { \ char *_ptr = (buf)->data; \ php_http_url_t *_url = (php_http_url_t *) _ptr, _mem = *_url; \ append; \ /* relocate */ \ if (_ptr != (buf)->data) { \ ptrdiff_t diff = (buf)->data - _ptr; \ _url = (php_http_url_t *) (buf)->data; \ if (_mem.scheme) _url->scheme += diff; \ if (_mem.user) _url->user += diff; \ if (_mem.pass) _url->pass += diff; \ if (_mem.host) _url->host += diff; \ if (_mem.path) _url->path += diff; \ if (_mem.query) _url->query += diff; \ if (_mem.fragment) _url->fragment += diff; \ } \ } while (0) #define url_copy(n) do { \ if (url_isset(new_url, n)) { \ url(buf)->n = &buf.data[buf.used]; \ url_append(&buf, php_http_buffer_append(&buf, new_url->n, strlen(new_url->n) + 1)); \ } else if (url_isset(old_url, n)) { \ url(buf)->n = &buf.data[buf.used]; \ url_append(&buf, php_http_buffer_append(&buf, old_url->n, strlen(old_url->n) + 1)); \ } \ } while (0) php_http_url_t *php_http_url_mod(const php_http_url_t *old_url, const php_http_url_t *new_url, unsigned flags TSRMLS_DC) { php_http_url_t *tmp_url = NULL; php_http_buffer_t buf; php_http_buffer_init_ex(&buf, MAX(PHP_HTTP_BUFFER_DEFAULT_SIZE, sizeof(php_http_url_t)<<2), PHP_HTTP_BUFFER_INIT_PREALLOC); php_http_buffer_account(&buf, sizeof(php_http_url_t)); memset(buf.data, 0, buf.used); /* set from env if requested */ if (flags & PHP_HTTP_URL_FROM_ENV) { php_http_url_t *env_url = php_http_url_from_env(TSRMLS_C); old_url = tmp_url = php_http_url_mod(env_url, old_url, flags ^ PHP_HTTP_URL_FROM_ENV TSRMLS_CC); php_http_url_free(&env_url); } url_copy(scheme); if (!(flags & PHP_HTTP_URL_STRIP_USER)) { url_copy(user); } if (!(flags & PHP_HTTP_URL_STRIP_PASS)) { url_copy(pass); } url_copy(host); if (!(flags & PHP_HTTP_URL_STRIP_PORT)) { url(buf)->port = url_isset(new_url, port) ? new_url->port : ((old_url) ? old_url->port : 0); } if (!(flags & PHP_HTTP_URL_STRIP_PATH)) { if ((flags & PHP_HTTP_URL_JOIN_PATH) && url_isset(old_url, path) && url_isset(new_url, path) && *new_url->path != '/') { size_t old_path_len = strlen(old_url->path), new_path_len = strlen(new_url->path); char *path = ecalloc(1, old_path_len + new_path_len + 1 + 1); strcat(path, old_url->path); if (path[old_path_len - 1] != '/') { php_dirname(path, old_path_len); strcat(path, "/"); } strcat(path, new_url->path); url(buf)->path = &buf.data[buf.used]; if (path[0] != '/') { url_append(&buf, php_http_buffer_append(&buf, "/", 1)); } url_append(&buf, php_http_buffer_append(&buf, path, strlen(path) + 1)); efree(path); } else { const char *path = NULL; if (url_isset(new_url, path)) { path = new_url->path; } else if (url_isset(old_url, path)) { path = old_url->path; } if (path) { url(buf)->path = &buf.data[buf.used]; url_append(&buf, php_http_buffer_append(&buf, path, strlen(path) + 1)); } } } if (!(flags & PHP_HTTP_URL_STRIP_QUERY)) { if ((flags & PHP_HTTP_URL_JOIN_QUERY) && url_isset(new_url, query) && url_isset(old_url, query)) { zval qarr, qstr; INIT_PZVAL(&qstr); INIT_PZVAL(&qarr); array_init(&qarr); ZVAL_STRING(&qstr, old_url->query, 0); php_http_querystring_update(&qarr, &qstr, NULL TSRMLS_CC); ZVAL_STRING(&qstr, new_url->query, 0); php_http_querystring_update(&qarr, &qstr, NULL TSRMLS_CC); ZVAL_NULL(&qstr); php_http_querystring_update(&qarr, NULL, &qstr TSRMLS_CC); url(buf)->query = &buf.data[buf.used]; url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL(qstr), Z_STRLEN(qstr) + 1)); zval_dtor(&qstr); zval_dtor(&qarr); } else { url_copy(query); } } if (!(flags & PHP_HTTP_URL_STRIP_FRAGMENT)) { url_copy(fragment); } /* done with copy & combine & strip */ if (flags & PHP_HTTP_URL_FROM_ENV) { /* free old_url we tainted above */ php_http_url_free(&tmp_url); } /* replace directory references if path is not a single slash */ if ((flags & PHP_HTTP_URL_SANITIZE_PATH) && url(buf)->path[0] && url(buf)->path[1]) { char *ptr, *end = url(buf)->path + strlen(url(buf)->path) + 1; for (ptr = strchr(url(buf)->path, '/'); ptr; ptr = strchr(ptr, '/')) { switch (ptr[1]) { case '/': memmove(&ptr[1], &ptr[2], end - &ptr[2]); break; case '.': switch (ptr[2]) { case '\0': ptr[1] = '\0'; break; case '/': memmove(&ptr[1], &ptr[3], end - &ptr[3]); break; case '.': if (ptr[3] == '/') { char *pos = &ptr[4]; while (ptr != url(buf)->path) { if (*--ptr == '/') { break; } } memmove(&ptr[1], pos, end - pos); break; } else if (!ptr[3]) { /* .. at the end */ ptr[1] = '\0'; } /* no break */ default: /* something else */ ++ptr; break; } break; default: ++ptr; break; } } } /* unset default ports */ if (url(buf)->port) { if ( ((url(buf)->port == 80) && url(buf)->scheme && !strcmp(url(buf)->scheme, "http")) || ((url(buf)->port ==443) && url(buf)->scheme && !strcmp(url(buf)->scheme, "https")) ) { url(buf)->port = 0; } } return url(buf); } char *php_http_url_to_string(const php_http_url_t *url, char **url_str, size_t *url_len, zend_bool persistent) { php_http_buffer_t buf; php_http_buffer_init_ex(&buf, PHP_HTTP_BUFFER_DEFAULT_SIZE, persistent ? PHP_HTTP_BUFFER_INIT_PERSISTENT : 0); if (url->scheme && *url->scheme) { php_http_buffer_appendl(&buf, url->scheme); php_http_buffer_appends(&buf, "://"); } else if ((url->user && *url->user) || (url->host && *url->host)) { php_http_buffer_appends(&buf, "//"); } if (url->user && *url->user) { php_http_buffer_appendl(&buf, url->user); if (url->pass && *url->pass) { php_http_buffer_appends(&buf, ":"); php_http_buffer_appendl(&buf, url->pass); } php_http_buffer_appends(&buf, "@"); } if (url->host && *url->host) { php_http_buffer_appendl(&buf, url->host); if (url->port) { php_http_buffer_appendf(&buf, ":%hu", url->port); } } if (url->path && *url->path) { if (*url->path != '/') { php_http_buffer_appends(&buf, "/"); } php_http_buffer_appendl(&buf, url->path); } else if (buf.used) { php_http_buffer_appends(&buf, "/"); } if (url->query && *url->query) { php_http_buffer_appends(&buf, "?"); php_http_buffer_appendl(&buf, url->query); } if (url->fragment && *url->fragment) { php_http_buffer_appends(&buf, "#"); php_http_buffer_appendl(&buf, url->fragment); } php_http_buffer_shrink(&buf); php_http_buffer_fix(&buf); if (url_len) { *url_len = buf.used; } if (url_str) { *url_str = buf.data; } return buf.data; } char *php_http_url_authority_to_string(const php_http_url_t *url, char **url_str, size_t *url_len) { php_http_buffer_t buf; php_http_buffer_init(&buf); if (url->user && *url->user) { php_http_buffer_appendl(&buf, url->user); if (url->pass && *url->pass) { php_http_buffer_appends(&buf, ":"); php_http_buffer_appendl(&buf, url->pass); } php_http_buffer_appends(&buf, "@"); } if (url->host && *url->host) { php_http_buffer_appendl(&buf, url->host); if (url->port) { php_http_buffer_appendf(&buf, ":%hu", url->port); } } php_http_buffer_shrink(&buf); php_http_buffer_fix(&buf); if (url_len) { *url_len = buf.used; } if (url_str) { *url_str = buf.data; } return buf.data; } php_http_url_t *php_http_url_from_zval(zval *value, unsigned flags TSRMLS_DC) { zval *zcpy; php_http_url_t *purl; switch (Z_TYPE_P(value)) { case IS_ARRAY: case IS_OBJECT: purl = php_http_url_from_struct(HASH_OF(value)); break; default: zcpy = php_http_ztyp(IS_STRING, value); purl = php_http_url_parse(Z_STRVAL_P(zcpy), Z_STRLEN_P(zcpy), flags TSRMLS_CC); zval_ptr_dtor(&zcpy); } return purl; } php_http_url_t *php_http_url_from_struct(HashTable *ht) { zval **e; php_http_buffer_t buf; php_http_buffer_init_ex(&buf, MAX(PHP_HTTP_BUFFER_DEFAULT_SIZE, sizeof(php_http_url_t)<<2), PHP_HTTP_BUFFER_INIT_PREALLOC); php_http_buffer_account(&buf, sizeof(php_http_url_t)); memset(buf.data, 0, buf.used); if (SUCCESS == zend_hash_find(ht, "scheme", sizeof("scheme"), (void *) &e)) { zval *cpy = php_http_ztyp(IS_STRING, *e); url(buf)->scheme = &buf.data[buf.used]; url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1)); zval_ptr_dtor(&cpy); } if (SUCCESS == zend_hash_find(ht, "user", sizeof("user"), (void *) &e)) { zval *cpy = php_http_ztyp(IS_STRING, *e); url(buf)->user = &buf.data[buf.used]; url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1)); zval_ptr_dtor(&cpy); } if (SUCCESS == zend_hash_find(ht, "pass", sizeof("pass"), (void *) &e)) { zval *cpy = php_http_ztyp(IS_STRING, *e); url(buf)->pass = &buf.data[buf.used]; url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1)); zval_ptr_dtor(&cpy); } if (SUCCESS == zend_hash_find(ht, "host", sizeof("host"), (void *) &e)) { zval *cpy = php_http_ztyp(IS_STRING, *e); url(buf)->host = &buf.data[buf.used]; url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1)); zval_ptr_dtor(&cpy); } if (SUCCESS == zend_hash_find(ht, "port", sizeof("port"), (void *) &e)) { zval *cpy = php_http_ztyp(IS_LONG, *e); url(buf)->port = (unsigned short) Z_LVAL_P(cpy); zval_ptr_dtor(&cpy); } if (SUCCESS == zend_hash_find(ht, "path", sizeof("path"), (void *) &e)) { zval *cpy = php_http_ztyp(IS_STRING, *e); url(buf)->path = &buf.data[buf.used]; url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1)); zval_ptr_dtor(&cpy); } if (SUCCESS == zend_hash_find(ht, "query", sizeof("query"), (void *) &e)) { zval *cpy = php_http_ztyp(IS_STRING, *e); url(buf)->query = &buf.data[buf.used]; url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1)); zval_ptr_dtor(&cpy); } if (SUCCESS == zend_hash_find(ht, "fragment", sizeof("fragment"), (void *) &e)) { zval *cpy = php_http_ztyp(IS_STRING, *e); url(buf)->fragment = &buf.data[buf.used]; url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy) + 1)); zval_ptr_dtor(&cpy); } return url(buf); } HashTable *php_http_url_to_struct(const php_http_url_t *url, zval *strct TSRMLS_DC) { zval arr; if (strct) { switch (Z_TYPE_P(strct)) { default: zval_dtor(strct); array_init(strct); /* no break */ case IS_ARRAY: case IS_OBJECT: INIT_PZVAL_ARRAY((&arr), HASH_OF(strct)); break; } } else { INIT_PZVAL(&arr); array_init(&arr); } if (url) { if (url->scheme) { add_assoc_string(&arr, "scheme", url->scheme, 1); } if (url->user) { add_assoc_string(&arr, "user", url->user, 1); } if (url->pass) { add_assoc_string(&arr, "pass", url->pass, 1); } if (url->host) { add_assoc_string(&arr, "host", url->host, 1); } if (url->port) { add_assoc_long(&arr, "port", (long) url->port); } if (url->path) { add_assoc_string(&arr, "path", url->path, 1); } if (url->query) { add_assoc_string(&arr, "query", url->query, 1); } if (url->fragment) { add_assoc_string(&arr, "fragment", url->fragment, 1); } } return Z_ARRVAL(arr); } ZEND_RESULT_CODE php_http_url_encode_hash(HashTable *hash, const char *pre_encoded_str, size_t pre_encoded_len, char **encoded_str, size_t *encoded_len TSRMLS_DC) { const char *arg_sep_str = "&"; size_t arg_sep_len = 1; php_http_buffer_t *qstr = php_http_buffer_new(); php_http_url_argsep(&arg_sep_str, &arg_sep_len TSRMLS_CC); if (SUCCESS != php_http_url_encode_hash_ex(hash, qstr, arg_sep_str, arg_sep_len, "=", 1, pre_encoded_str, pre_encoded_len TSRMLS_CC)) { php_http_buffer_free(&qstr); return FAILURE; } php_http_buffer_data(qstr, encoded_str, encoded_len); php_http_buffer_free(&qstr); return SUCCESS; } ZEND_RESULT_CODE php_http_url_encode_hash_ex(HashTable *hash, php_http_buffer_t *qstr, const char *arg_sep_str, size_t arg_sep_len, const char *val_sep_str, size_t val_sep_len, const char *pre_encoded_str, size_t pre_encoded_len TSRMLS_DC) { if (pre_encoded_len && pre_encoded_str) { php_http_buffer_append(qstr, pre_encoded_str, pre_encoded_len); } if (!php_http_params_to_string(qstr, hash, arg_sep_str, arg_sep_len, "", 0, val_sep_str, val_sep_len, PHP_HTTP_PARAMS_QUERY TSRMLS_CC)) { return FAILURE; } return SUCCESS; } struct parse_state { php_http_url_t url; #ifdef ZTS void ***ts; #endif const char *ptr; const char *end; size_t maxlen; off_t offset; unsigned flags; char buffer[1]; /* last member */ }; void php_http_url_free(php_http_url_t **url) { if (*url) { efree(*url); *url = NULL; } } php_http_url_t *php_http_url_copy(const php_http_url_t *url, zend_bool persistent) { php_http_url_t *cpy; const char *end = NULL, *url_ptr = (const char *) url; char *cpy_ptr; end = MAX(url->scheme, end); end = MAX(url->pass, end); end = MAX(url->user, end); end = MAX(url->host, end); end = MAX(url->path, end); end = MAX(url->query, end); end = MAX(url->fragment, end); if (end) { end += strlen(end) + 1; cpy_ptr = pecalloc(1, end - url_ptr, persistent); cpy = (php_http_url_t *) cpy_ptr; memcpy(cpy_ptr + sizeof(*cpy), url_ptr + sizeof(*url), end - url_ptr - sizeof(*url)); cpy->scheme = url->scheme ? cpy_ptr + (url->scheme - url_ptr) : NULL; cpy->pass = url->pass ? cpy_ptr + (url->pass - url_ptr) : NULL; cpy->user = url->user ? cpy_ptr + (url->user - url_ptr) : NULL; cpy->host = url->host ? cpy_ptr + (url->host - url_ptr) : NULL; cpy->path = url->path ? cpy_ptr + (url->path - url_ptr) : NULL; cpy->query = url->query ? cpy_ptr + (url->query - url_ptr) : NULL; cpy->fragment = url->fragment ? cpy_ptr + (url->fragment - url_ptr) : NULL; } else { cpy = ecalloc(1, sizeof(*url)); } cpy->port = url->port; return cpy; } static size_t parse_mb_utf8(unsigned *wc, const char *ptr, const char *end) { unsigned wchar; size_t consumed = utf8towc(&wchar, (const unsigned char *) ptr, end - ptr); if (!consumed || consumed == (size_t) -1) { return 0; } if (wc) { *wc = wchar; } return consumed; } #ifdef PHP_HTTP_HAVE_WCHAR static size_t parse_mb_loc(unsigned *wc, const char *ptr, const char *end) { wchar_t wchar; size_t consumed = 0; #if defined(HAVE_MBRTOWC) mbstate_t ps; memset(&ps, 0, sizeof(ps)); consumed = mbrtowc(&wchar, ptr, end - ptr, &ps); #elif defined(HAVE_MBTOWC) consumed = mbtowc(&wchar, ptr, end - ptr); #endif if (!consumed || consumed == (size_t) -1) { return 0; } if (wc) { *wc = wchar; } return consumed; } #endif typedef enum parse_mb_what { PARSE_SCHEME, PARSE_USERINFO, PARSE_HOSTINFO, PARSE_PATH, PARSE_QUERY, PARSE_FRAGMENT } parse_mb_what_t; static const char * const parse_what[] = { "scheme", "userinfo", "hostinfo", "path", "query", "fragment" }; static const char parse_xdigits[] = "0123456789ABCDEF"; static size_t parse_mb(struct parse_state *state, parse_mb_what_t what, const char *ptr, const char *end, const char *begin, zend_bool silent) { unsigned wchar; size_t consumed = 0; if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) { consumed = parse_mb_utf8(&wchar, ptr, end); } #ifdef PHP_HTTP_HAVE_WCHAR else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) { consumed = parse_mb_loc(&wchar, ptr, end); } #endif while (consumed) { if (!(state->flags & PHP_HTTP_URL_PARSE_TOPCT) || what == PARSE_HOSTINFO || what == PARSE_SCHEME) { if (what == PARSE_HOSTINFO && (state->flags & PHP_HTTP_URL_PARSE_TOIDN)) { /* idna */ } else if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) { if (!isualnum(wchar)) { break; } #ifdef PHP_HTTP_HAVE_WCHAR } else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) { if (!iswalnum(wchar)) { break; } #endif } PHP_HTTP_DUFF(consumed, state->buffer[state->offset++] = *ptr++); } else { int i = 0; PHP_HTTP_DUFF(consumed, state->buffer[state->offset++] = '%'; state->buffer[state->offset++] = parse_xdigits[((unsigned char) ptr[i]) >> 4]; state->buffer[state->offset++] = parse_xdigits[((unsigned char) ptr[i]) & 0xf]; ++i; ); } return consumed; } if (!silent) { TSRMLS_FETCH_FROM_CTX(state->ts); if (consumed) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse %s; unexpected multibyte sequence 0x%x at pos %u in '%s'", parse_what[what], wchar, (unsigned) (ptr - begin), begin); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse %s; unexpected byte 0x%02x at pos %u in '%s'", parse_what[what], (unsigned char) *ptr, (unsigned) (ptr - begin), begin); } } return 0; } static ZEND_RESULT_CODE parse_userinfo(struct parse_state *state, const char *ptr) { size_t mb; const char *password = NULL, *end = state->ptr, *tmp = ptr; TSRMLS_FETCH_FROM_CTX(state->ts); state->url.user = &state->buffer[state->offset]; do { switch (*ptr) { case ':': if (password) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse password; duplicate ':' at pos %u in '%s'", (unsigned) (ptr - tmp), tmp); return FAILURE; } password = ptr + 1; state->buffer[state->offset++] = 0; state->url.pass = &state->buffer[state->offset]; break; case '%': if (ptr[1] != '%' && (end - ptr <= 2 || !isxdigit(*(ptr+1)) || !isxdigit(*(ptr+2)))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse userinfo; invalid percent encoding at pos %u in '%s'", (unsigned) (ptr - tmp), tmp); return FAILURE; } state->buffer[state->offset++] = *ptr++; state->buffer[state->offset++] = *ptr++; state->buffer[state->offset++] = *ptr; break; case '!': case '$': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case ';': case '=': /* sub-delims */ case '-': case '.': case '_': case '~': /* unreserved */ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* allowed */ state->buffer[state->offset++] = *ptr; break; default: if (!(mb = parse_mb(state, PARSE_USERINFO, ptr, end, tmp, 0))) { return FAILURE; } ptr += mb - 1; } } while(++ptr != end); state->buffer[state->offset++] = 0; return SUCCESS; } #if defined(PHP_WIN32) || defined(HAVE_UIDNA_IDNTOASCII) typedef size_t (*parse_mb_func)(unsigned *wc, const char *ptr, const char *end); static ZEND_RESULT_CODE to_utf16(parse_mb_func fn, const char *u8, uint16_t **u16, size_t *len TSRMLS_DC) { size_t offset = 0, u8_len = strlen(u8); *u16 = ecalloc(4 * sizeof(uint16_t), u8_len + 1); *len = 0; while (offset < u8_len) { unsigned wc; uint16_t buf[2], *ptr = buf; size_t consumed = fn(&wc, &u8[offset], &u8[u8_len]); if (!consumed) { efree(*u16); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse UTF-8 at pos %zu of '%s'", offset, u8); return FAILURE; } else { offset += consumed; } switch (wctoutf16(buf, wc)) { case 2: (*u16)[(*len)++] = *ptr++; /* no break */ case 1: (*u16)[(*len)++] = *ptr++; break; case 0: default: efree(*u16); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to convert UTF-32 'U+%X' to UTF-16", wc); return FAILURE; } } return SUCCESS; } #endif #ifndef MAXHOSTNAMELEN # define MAXHOSTNAMELEN 256 #endif #if PHP_HTTP_HAVE_IDN2 static ZEND_RESULT_CODE parse_idn2(struct parse_state *state, size_t prev_len) { char *idn = NULL; int rv = -1; TSRMLS_FETCH_FROM_CTX(state->ts); if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) { rv = idn2_lookup_u8((const unsigned char *) state->url.host, (unsigned char **) &idn, IDN2_NFC_INPUT); } # ifdef PHP_HTTP_HAVE_WCHAR else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) { rv = idn2_lookup_ul(state->url.host, &idn, 0); } # endif if (rv != IDN2_OK) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN; %s", idn2_strerror(rv)); return FAILURE; } else { size_t idnlen = strlen(idn); memcpy(state->url.host, idn, idnlen + 1); free(idn); state->offset += idnlen - prev_len; return SUCCESS; } } #elif PHP_HTTP_HAVE_IDN static ZEND_RESULT_CODE parse_idn(struct parse_state *state, size_t prev_len) { char *idn = NULL; int rv = -1; TSRMLS_FETCH_FROM_CTX(state->ts); if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) { rv = idna_to_ascii_8z(state->url.host, &idn, IDNA_ALLOW_UNASSIGNED|IDNA_USE_STD3_ASCII_RULES); } # ifdef PHP_HTTP_HAVE_WCHAR else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) { rv = idna_to_ascii_lz(state->url.host, &idn, IDNA_ALLOW_UNASSIGNED|IDNA_USE_STD3_ASCII_RULES); } # endif if (rv != IDNA_SUCCESS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN; %s", idna_strerror(rv)); return FAILURE; } else { size_t idnlen = strlen(idn); memcpy(state->url.host, idn, idnlen + 1); free(idn); state->offset += idnlen - prev_len; return SUCCESS; } } #endif #ifdef HAVE_UIDNA_IDNTOASCII # if HAVE_UNICODE_UIDNA_H # include <unicode/uidna.h> # else typedef uint16_t UChar; typedef enum { U_ZERO_ERROR = 0 } UErrorCode; int32_t uidna_IDNToASCII(const UChar *src, int32_t srcLength, UChar *dest, int32_t destCapacity, int32_t options, void *parseError, UErrorCode *status); # endif static ZEND_RESULT_CODE parse_uidn(struct parse_state *state) { char *host_ptr; uint16_t *uhost_str, ahost_str[MAXHOSTNAMELEN], *ahost_ptr; size_t uhost_len, ahost_len; UErrorCode error = U_ZERO_ERROR; TSRMLS_FETCH_FROM_CTX(state->ts); if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) { if (SUCCESS != to_utf16(parse_mb_utf8, state->url.host, &uhost_str, &uhost_len TSRMLS_CC)) { return FAILURE; } #ifdef PHP_HTTP_HAVE_WCHAR } else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) { if (SUCCESS != to_utf16(parse_mb_loc, state->url.host, &uhost_str, &uhost_len TSRMLS_CC)) { return FAILURE; } #endif } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN; codepage not specified"); return FAILURE; } ahost_len = uidna_IDNToASCII(uhost_str, uhost_len, ahost_str, MAXHOSTNAMELEN, 3, NULL, &error); efree(uhost_str); if (error != U_ZERO_ERROR) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN; ICU error %d", error); return FAILURE; } host_ptr = state->url.host; ahost_ptr = ahost_str; PHP_HTTP_DUFF(ahost_len, *host_ptr++ = *ahost_ptr++); *host_ptr = '\0'; state->offset += host_ptr - state->url.host; return SUCCESS; } #endif #if 0 && defined(PHP_WIN32) static ZEND_RESULT_CODE parse_widn(struct parse_state *state) { char *host_ptr; uint16_t *uhost_str, ahost_str[MAXHOSTNAMELEN], *ahost_ptr; size_t uhost_len; TSRMLS_FETCH_FROM_CTX(state->ts); if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) { if (SUCCESS != to_utf16(parse_mb_utf8, state->url.host, &uhost_str, &uhost_len)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN"); return FAILURE; } #ifdef PHP_HTTP_HAVE_WCHAR } else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) { if (SUCCESS != to_utf16(parse_mb_loc, state->url.host, &uhost_str, &uhost_len)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN"); return FAILURE; } #endif } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN"); return FAILURE; } if (!IdnToAscii(IDN_ALLOW_UNASSIGNED|IDN_USE_STD3_ASCII_RULES, uhost_str, uhost_len, ahost_str, MAXHOSTNAMELEN)) { efree(uhost_str); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse IDN"); return FAILURE; } efree(uhost_str); host_ptr = state->url.host; ahost_ptr = ahost_str; PHP_HTTP_DUFF(wcslen(ahost_str), *host_ptr++ = *ahost_ptr++); efree(ahost_str); *host_ptr = '\0'; state->offset += host_ptr - state->url.host; return SUCCESS; } #endif #ifdef HAVE_INET_PTON static const char *parse_ip6(struct parse_state *state, const char *ptr) { const char *error = NULL, *end = state->ptr, *tmp = memchr(ptr, ']', end - ptr); TSRMLS_FETCH_FROM_CTX(state->ts); if (tmp) { size_t addrlen = tmp - ptr + 1; char buf[16], *addr = estrndup(ptr + 1, addrlen - 2); int rv = inet_pton(AF_INET6, addr, buf); if (rv == 1) { state->buffer[state->offset] = '['; state->url.host = &state->buffer[state->offset]; inet_ntop(AF_INET6, buf, state->url.host + 1, state->maxlen - state->offset); state->offset += strlen(state->url.host); state->buffer[state->offset++] = ']'; state->buffer[state->offset++] = 0; ptr = tmp + 1; } else if (rv == -1) { error = strerror(errno); } else { error = "unexpected '['"; } efree(addr); } else { error = "expected ']'"; } if (error) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse hostinfo; %s", error); return NULL; } return ptr; } #endif static ZEND_RESULT_CODE parse_hostinfo(struct parse_state *state, const char *ptr) { size_t mb, len; const char *end = state->ptr, *tmp = ptr, *port = NULL, *label = NULL; TSRMLS_FETCH_FROM_CTX(state->ts); #ifdef HAVE_INET_PTON if (*ptr == '[' && !(ptr = parse_ip6(state, ptr))) { return FAILURE; } #endif if (ptr != end) do { switch (*ptr) { case ':': if (port) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse port; unexpected ':' at pos %u in '%s'", (unsigned) (ptr - tmp), tmp); return FAILURE; } port = ptr + 1; break; case '%': if (ptr[1] != '%' && (end - ptr <= 2 || !isxdigit(*(ptr+1)) || !isxdigit(*(ptr+2)))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse hostinfo; invalid percent encoding at pos %u in '%s'", (unsigned) (ptr - tmp), tmp); return FAILURE; } state->buffer[state->offset++] = *ptr++; state->buffer[state->offset++] = *ptr++; state->buffer[state->offset++] = *ptr; break; case '!': case '$': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case ';': case '=': /* sub-delims */ case '-': case '.': case '_': case '~': /* unreserved */ if (port || !label) { /* sort of a compromise, just ensure we don't end up * with a dot at the beginning or two consecutive dots */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse %s; unexpected '%c' at pos %u in '%s'", port ? "port" : "host", (unsigned char) *ptr, (unsigned) (ptr - tmp), tmp); return FAILURE; } state->buffer[state->offset++] = *ptr; label = NULL; break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': if (port) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse port; unexpected char '%c' at pos %u in '%s'", (unsigned char) *ptr, (unsigned) (ptr - tmp), tmp); return FAILURE; } /* no break */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* allowed */ if (port) { state->url.port *= 10; state->url.port += *ptr - '0'; } else { label = ptr; state->buffer[state->offset++] = *ptr; } break; default: if (ptr == end) { break; } else if (port) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse port; unexpected byte 0x%02x at pos %u in '%s'", (unsigned char) *ptr, (unsigned) (ptr - tmp), tmp); return FAILURE; } else if (!(mb = parse_mb(state, PARSE_HOSTINFO, ptr, end, tmp, 0))) { return FAILURE; } label = ptr; ptr += mb - 1; } } while (++ptr != end); if (!state->url.host) { len = (port ? port - tmp - 1 : end - tmp); state->url.host = &state->buffer[state->offset - len]; state->buffer[state->offset++] = 0; } if (state->flags & PHP_HTTP_URL_PARSE_TOIDN) { #if PHP_HTTP_HAVE_IDN2 return parse_idn2(state, len); #elif PHP_HTTP_HAVE_IDN return parse_idn(state, len); #endif #ifdef HAVE_UIDNA_IDNTOASCII return parse_uidn(state); #endif #if 0 && defined(PHP_WIN32) return parse_widn(state); #endif } return SUCCESS; } static const char *parse_authority(struct parse_state *state) { const char *tmp = state->ptr, *host = NULL; do { switch (*state->ptr) { case '@': /* userinfo delimiter */ if (host) { TSRMLS_FETCH_FROM_CTX(state->ts); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse userinfo; unexpected '@'"); return NULL; } host = state->ptr + 1; if (tmp != state->ptr && SUCCESS != parse_userinfo(state, tmp)) { return NULL; } tmp = state->ptr + 1; break; case '/': case '?': case '#': case '\0': EOD: /* host delimiter */ if (tmp != state->ptr && SUCCESS != parse_hostinfo(state, tmp)) { return NULL; } return state->ptr; } } while (++state->ptr <= state->end); --state->ptr; goto EOD; } static const char *parse_path(struct parse_state *state) { size_t mb; const char *tmp; TSRMLS_FETCH_FROM_CTX(state->ts); /* is there actually a path to parse? */ if (!*state->ptr) { return state->ptr; } tmp = state->ptr; state->url.path = &state->buffer[state->offset]; do { switch (*state->ptr) { case '#': case '?': goto done; case '%': if (state->ptr[1] != '%' && (state->end - state->ptr <= 2 || !isxdigit(*(state->ptr+1)) || !isxdigit(*(state->ptr+2)))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse path; invalid percent encoding at pos %u in '%s'", (unsigned) (state->ptr - tmp), tmp); return NULL; } state->buffer[state->offset++] = *state->ptr++; state->buffer[state->offset++] = *state->ptr++; state->buffer[state->offset++] = *state->ptr; break; case '/': /* yeah, well */ case '!': case '$': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case ';': case '=': /* sub-delims */ case '-': case '.': case '_': case '~': /* unreserved */ case ':': case '@': /* pchar */ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* allowed */ state->buffer[state->offset++] = *state->ptr; break; default: if (!(mb = parse_mb(state, PARSE_PATH, state->ptr, state->end, tmp, 0))) { return NULL; } state->ptr += mb - 1; } } while (++state->ptr < state->end); done: /* did we have any path component ? */ if (tmp != state->ptr) { state->buffer[state->offset++] = 0; } else { state->url.path = NULL; } return state->ptr; } static const char *parse_query(struct parse_state *state) { size_t mb; const char *tmp = state->ptr + !!*state->ptr; TSRMLS_FETCH_FROM_CTX(state->ts); /* is there actually a query to parse? */ if (*state->ptr != '?') { return state->ptr; } /* skip initial '?' */ tmp = ++state->ptr; state->url.query = &state->buffer[state->offset]; while (state->ptr < state->end) { switch (*state->ptr) { case '#': goto done; case '%': if (state->ptr[1] != '%' && (state->end - state->ptr <= 2 || !isxdigit(*(state->ptr+1)) || !isxdigit(*(state->ptr+2)))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse query; invalid percent encoding at pos %u in '%s'", (unsigned) (state->ptr - tmp), tmp); return NULL; } state->buffer[state->offset++] = *state->ptr++; state->buffer[state->offset++] = *state->ptr++; state->buffer[state->offset++] = *state->ptr; break; /* RFC1738 unsafe */ case '{': case '}': case '<': case '>': case '[': case ']': case '|': case '\\': case '^': case '`': case '"': case ' ': if (state->flags & PHP_HTTP_URL_PARSE_TOPCT) { state->buffer[state->offset++] = '%'; state->buffer[state->offset++] = parse_xdigits[((unsigned char) *state->ptr) >> 4]; state->buffer[state->offset++] = parse_xdigits[((unsigned char) *state->ptr) & 0xf]; break; } /* no break */ case '?': case '/': /* yeah, well */ case '!': case '$': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case ';': case '=': /* sub-delims */ case '-': case '.': case '_': case '~': /* unreserved */ case ':': case '@': /* pchar */ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* allowed */ state->buffer[state->offset++] = *state->ptr; break; default: if (!(mb = parse_mb(state, PARSE_QUERY, state->ptr, state->end, tmp, 0))) { return NULL; } state->ptr += mb - 1; } ++state->ptr; } done: state->buffer[state->offset++] = 0; return state->ptr; } static const char *parse_fragment(struct parse_state *state) { size_t mb; const char *tmp; TSRMLS_FETCH_FROM_CTX(state->ts); /* is there actually a fragment to parse? */ if (*state->ptr != '#') { return state->ptr; } /* skip initial '#' */ tmp = ++state->ptr; state->url.fragment = &state->buffer[state->offset]; do { switch (*state->ptr) { case '%': if (state->ptr[1] != '%' && (state->end - state->ptr <= 2 || !isxdigit(*(state->ptr+1)) || !isxdigit(*(state->ptr+2)))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse fragment; invalid percent encoding at pos %u in '%s'", (unsigned) (state->ptr - tmp), tmp); return NULL; } state->buffer[state->offset++] = *state->ptr++; state->buffer[state->offset++] = *state->ptr++; state->buffer[state->offset++] = *state->ptr; break; /* RFC1738 unsafe */ case '{': case '}': case '<': case '>': case '[': case ']': case '|': case '\\': case '^': case '`': case '"': case ' ': if (state->flags & PHP_HTTP_URL_PARSE_TOPCT) { state->buffer[state->offset++] = '%'; state->buffer[state->offset++] = parse_xdigits[((unsigned char) *state->ptr) >> 4]; state->buffer[state->offset++] = parse_xdigits[((unsigned char) *state->ptr) & 0xf]; break; } /* no break */ case '?': case '/': case '!': case '$': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case ';': case '=': /* sub-delims */ case '-': case '.': case '_': case '~': /* unreserved */ case ':': case '@': /* pchar */ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* allowed */ state->buffer[state->offset++] = *state->ptr; break; default: if (!(mb = parse_mb(state, PARSE_FRAGMENT, state->ptr, state->end, tmp, 0))) { return NULL; } state->ptr += mb - 1; } } while (++state->ptr < state->end); state->buffer[state->offset++] = 0; return state->ptr; } static const char *parse_hier(struct parse_state *state) { if (*state->ptr == '/') { if (state->end - state->ptr > 1) { if (*(state->ptr + 1) == '/') { state->ptr += 2; if (!(state->ptr = parse_authority(state))) { return NULL; } } } } return parse_path(state); } static const char *parse_scheme(struct parse_state *state) { size_t mb; const char *tmp = state->ptr; do { switch (*state->ptr) { case ':': /* scheme delimiter */ state->url.scheme = &state->buffer[0]; state->buffer[state->offset++] = 0; return ++state->ptr; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '+': case '-': case '.': if (state->ptr == tmp) { goto softfail; } /* no break */ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': /* scheme part */ state->buffer[state->offset++] = *state->ptr; break; default: if (!(mb = parse_mb(state, PARSE_SCHEME, state->ptr, state->end, tmp, 1))) { goto softfail; } state->ptr += mb - 1; } } while (++state->ptr != state->end); softfail: state->offset = 0; return state->ptr = tmp; } php_http_url_t *php_http_url_parse(const char *str, size_t len, unsigned flags TSRMLS_DC) { size_t maxlen = 3 * len + 8 /* null bytes for all components */; struct parse_state *state = ecalloc(1, sizeof(*state) + maxlen); state->end = str + len; state->ptr = str; state->flags = flags; state->maxlen = maxlen; TSRMLS_SET_CTX(state->ts); if (!parse_scheme(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL scheme: '%s'", state->ptr); efree(state); return NULL; } if (!parse_hier(state)) { efree(state); return NULL; } if (!parse_query(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL query: '%s'", state->ptr); efree(state); return NULL; } if (!parse_fragment(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL fragment: '%s'", state->ptr); efree(state); return NULL; } return (php_http_url_t *) state; } php_http_url_t *php_http_url_parse_authority(const char *str, size_t len, unsigned flags TSRMLS_DC) { size_t maxlen = 3 * len; struct parse_state *state = ecalloc(1, sizeof(*state) + maxlen); state->end = str + len; state->ptr = str; state->flags = flags; state->maxlen = maxlen; TSRMLS_SET_CTX(state->ts); if (!(state->ptr = parse_authority(state))) { efree(state); return NULL; } if (state->ptr != state->end) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL authority, unexpected character at pos %u in '%s'", (unsigned) (state->ptr - str), str); efree(state); return NULL; } return (php_http_url_t *) state; } ZEND_BEGIN_ARG_INFO_EX(ai_HttpUrl___construct, 0, 0, 0) ZEND_ARG_INFO(0, old_url) ZEND_ARG_INFO(0, new_url) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO(); PHP_METHOD(HttpUrl, __construct) { zval *new_url = NULL, *old_url = NULL; long flags = PHP_HTTP_URL_FROM_ENV; zend_error_handling zeh; php_http_expect(SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z!z!l", &old_url, &new_url, &flags), invalid_arg, return); zend_replace_error_handling(EH_THROW, php_http_exception_bad_url_class_entry, &zeh TSRMLS_CC); { php_http_url_t *res_purl, *new_purl = NULL, *old_purl = NULL; if (new_url) { new_purl = php_http_url_from_zval(new_url, flags TSRMLS_CC); if (!new_purl) { zend_restore_error_handling(&zeh TSRMLS_CC); return; } } if (old_url) { old_purl = php_http_url_from_zval(old_url, flags TSRMLS_CC); if (!old_purl) { if (new_purl) { php_http_url_free(&new_purl); } zend_restore_error_handling(&zeh TSRMLS_CC); return; } } res_purl = php_http_url_mod(old_purl, new_purl, flags TSRMLS_CC); php_http_url_to_struct(res_purl, getThis() TSRMLS_CC); php_http_url_free(&res_purl); if (old_purl) { php_http_url_free(&old_purl); } if (new_purl) { php_http_url_free(&new_purl); } } zend_restore_error_handling(&zeh TSRMLS_CC); } ZEND_BEGIN_ARG_INFO_EX(ai_HttpUrl_mod, 0, 0, 1) ZEND_ARG_INFO(0, more_url_parts) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO(); PHP_METHOD(HttpUrl, mod) { zval *new_url = NULL; long flags = PHP_HTTP_URL_JOIN_PATH | PHP_HTTP_URL_JOIN_QUERY | PHP_HTTP_URL_SANITIZE_PATH; zend_error_handling zeh; php_http_expect(SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z!|l", &new_url, &flags), invalid_arg, return); zend_replace_error_handling(EH_THROW, php_http_exception_bad_url_class_entry, &zeh TSRMLS_CC); { php_http_url_t *new_purl = NULL, *old_purl = NULL; if (new_url) { new_purl = php_http_url_from_zval(new_url, flags TSRMLS_CC); if (!new_purl) { zend_restore_error_handling(&zeh TSRMLS_CC); return; } } if ((old_purl = php_http_url_from_struct(HASH_OF(getThis())))) { php_http_url_t *res_purl; ZVAL_OBJVAL(return_value, zend_objects_clone_obj(getThis() TSRMLS_CC), 0); res_purl = php_http_url_mod(old_purl, new_purl, flags TSRMLS_CC); php_http_url_to_struct(res_purl, return_value TSRMLS_CC); php_http_url_free(&res_purl); php_http_url_free(&old_purl); } if (new_purl) { php_http_url_free(&new_purl); } } zend_restore_error_handling(&zeh TSRMLS_CC); } ZEND_BEGIN_ARG_INFO_EX(ai_HttpUrl_toString, 0, 0, 0) ZEND_END_ARG_INFO(); PHP_METHOD(HttpUrl, toString) { if (SUCCESS == zend_parse_parameters_none()) { php_http_url_t *purl; if ((purl = php_http_url_from_struct(HASH_OF(getThis())))) { char *str; size_t len; php_http_url_to_string(purl, &str, &len, 0); php_http_url_free(&purl); RETURN_STRINGL(str, len, 0); } } RETURN_EMPTY_STRING(); } ZEND_BEGIN_ARG_INFO_EX(ai_HttpUrl_toArray, 0, 0, 0) ZEND_END_ARG_INFO(); PHP_METHOD(HttpUrl, toArray) { php_http_url_t *purl; if (SUCCESS != zend_parse_parameters_none()) { return; } /* strip any non-URL properties */ purl = php_http_url_from_struct(HASH_OF(getThis())); php_http_url_to_struct(purl, return_value TSRMLS_CC); php_http_url_free(&purl); } static zend_function_entry php_http_url_methods[] = { PHP_ME(HttpUrl, __construct, ai_HttpUrl___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(HttpUrl, mod, ai_HttpUrl_mod, ZEND_ACC_PUBLIC) PHP_ME(HttpUrl, toString, ai_HttpUrl_toString, ZEND_ACC_PUBLIC) ZEND_MALIAS(HttpUrl, __toString, toString, ai_HttpUrl_toString, ZEND_ACC_PUBLIC) PHP_ME(HttpUrl, toArray, ai_HttpUrl_toArray, ZEND_ACC_PUBLIC) EMPTY_FUNCTION_ENTRY }; zend_class_entry *php_http_url_class_entry; PHP_MINIT_FUNCTION(http_url) { zend_class_entry ce = {0}; INIT_NS_CLASS_ENTRY(ce, "http", "Url", php_http_url_methods); php_http_url_class_entry = zend_register_internal_class(&ce TSRMLS_CC); zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("scheme"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("user"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("pass"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("host"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("port"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("path"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("query"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_null(php_http_url_class_entry, ZEND_STRL("fragment"), ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("REPLACE"), PHP_HTTP_URL_REPLACE TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("JOIN_PATH"), PHP_HTTP_URL_JOIN_PATH TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("JOIN_QUERY"), PHP_HTTP_URL_JOIN_QUERY TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_USER"), PHP_HTTP_URL_STRIP_USER TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_PASS"), PHP_HTTP_URL_STRIP_PASS TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_AUTH"), PHP_HTTP_URL_STRIP_AUTH TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_PORT"), PHP_HTTP_URL_STRIP_PORT TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_PATH"), PHP_HTTP_URL_STRIP_PATH TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_QUERY"), PHP_HTTP_URL_STRIP_QUERY TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_FRAGMENT"), PHP_HTTP_URL_STRIP_FRAGMENT TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("STRIP_ALL"), PHP_HTTP_URL_STRIP_ALL TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("FROM_ENV"), PHP_HTTP_URL_FROM_ENV TSRMLS_CC); zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("SANITIZE_PATH"), PHP_HTTP_URL_SANITIZE_PATH TSRMLS_CC); #ifdef PHP_HTTP_HAVE_WCHAR zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("PARSE_MBLOC"), PHP_HTTP_URL_PARSE_MBLOC TSRMLS_CC); #endif zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("PARSE_MBUTF8"), PHP_HTTP_URL_PARSE_MBUTF8 TSRMLS_CC); #if defined(PHP_HTTP_HAVE_IDN2) || defined(PHP_HTTP_HAVE_IDN) || defined(HAVE_UIDNA_IDNTOASCII) zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("PARSE_TOIDN"), PHP_HTTP_URL_PARSE_TOIDN TSRMLS_CC); #endif zend_declare_class_constant_long(php_http_url_class_entry, ZEND_STRL("PARSE_TOPCT"), PHP_HTTP_URL_PARSE_TOPCT TSRMLS_CC); return SUCCESS; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-119/c/good_5182_1
crossvul-cpp_data_bad_105_0
#ifndef NGIFLIB_NO_FILE #include <stdio.h> #endif /* NGIFLIB_NO_FILE */ #include "ngiflib.h" /* decodeur GIF en C portable (pas de pb big/little endian) * Thomas BERNARD. janvier 2004. * (c) 2004-2017 Thomas Bernard. All rights reserved */ /* Fonction de debug */ #ifdef DEBUG void fprintf_ngiflib_img(FILE * f, struct ngiflib_img * i) { fprintf(f, " * ngiflib_img @ %p\n", i); fprintf(f, " next = %p\n", i->next); fprintf(f, " parent = %p\n", i->parent); fprintf(f, " palette = %p\n", i->palette); fprintf(f, " %3d couleurs", i->ncolors); if(i->interlaced) fprintf(f, " interlaced"); fprintf(f, "\n taille : %dx%d, pos (%d,%d)\n", i->width, i->height, i->posX, i->posY); fprintf(f, " sort_flag=%x localpalbits=%d\n", i->sort_flag, i->localpalbits); } #endif /* DEBUG */ void GifImgDestroy(struct ngiflib_img * i) { if(i==NULL) return; if(i->next) GifImgDestroy(i->next); if(i->palette && (i->palette != i->parent->palette)) ngiflib_free(i->palette); ngiflib_free(i); } /* Fonction de debug */ #ifdef DEBUG void fprintf_ngiflib_gif(FILE * f, struct ngiflib_gif * g) { struct ngiflib_img * i; fprintf(f, "* ngiflib_gif @ %p %s\n", g, g->signature); fprintf(f, " %dx%d, %d bits, %d couleurs\n", g->width, g->height, g->imgbits, g->ncolors); fprintf(f, " palette = %p, backgroundcolorindex %d\n", g->palette, g->backgroundindex); fprintf(f, " pixelaspectratio = %d\n", g->pixaspectratio); fprintf(f, " frbuff = %p\n", g->frbuff.p8); fprintf(f, " cur_img = %p\n", g->cur_img); fprintf(f, " %d images :\n", g->nimg); i = g->first_img; while(i) { fprintf_ngiflib_img(f, i); i = i->next; } } #endif /* DEBUG */ void GifDestroy(struct ngiflib_gif * g) { if(g==NULL) return; if(g->palette) ngiflib_free(g->palette); if(g->frbuff.p8) ngiflib_free(g->frbuff.p8); GifImgDestroy(g->first_img); ngiflib_free(g); } /* u8 GetByte(struct ngiflib_gif * g); * fonction qui renvoie un octet du fichier .gif * on pourait optimiser en faisant 2 fonctions. */ static u8 GetByte(struct ngiflib_gif * g) { #ifndef NGIFLIB_NO_FILE if(g->mode & NGIFLIB_MODE_FROM_MEM) { #endif /* NGIFLIB_NO_FILE */ return *(g->input.bytes++); #ifndef NGIFLIB_NO_FILE } else { return (u8)(getc(g->input.file)); } #endif /* NGIFLIB_NO_FILE */ } /* u16 GetWord() * Renvoie un mot de 16bits * N'est pas influencee par l'endianess du CPU ! */ static u16 GetWord(struct ngiflib_gif * g) { u16 r = (u16)GetByte(g); r |= ((u16)GetByte(g) << 8); return r; } /* int GetByteStr(struct ngiflib_gif * g, u8 * p, int n); * prend en argument un pointeur sur la destination * et le nombre d'octet a lire. * Renvoie 0 si l'operation a reussi, -1 sinon. */ static int GetByteStr(struct ngiflib_gif * g, u8 * p, int n) { if(!p) return -1; #ifndef NGIFLIB_NO_FILE if(g->mode & NGIFLIB_MODE_FROM_MEM) { #endif /* NGIFLIB_NO_FILE */ ngiflib_memcpy(p, g->input.bytes, n); g->input.bytes += n; return 0; #ifndef NGIFLIB_NO_FILE } else { size_t read; read = fread(p, 1, n, g->input.file); return ((int)read == n) ? 0 : -1; } #endif /* NGIFLIB_NO_FILE */ } /* void WritePixel(struct ngiflib_img * i, u8 v); * ecrit le pixel de valeur v dans le frame buffer */ static void WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) { struct ngiflib_gif * p = i->parent; if(v!=i->gce.transparent_color || !i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ *context->frbuff_p.p8 = v; #ifndef NGIFLIB_INDEXED_ONLY } else *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, v); #endif /* NGIFLIB_INDEXED_ONLY */ } if(--(context->Xtogo) <= 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 4; } break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 2; } break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 1; } break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ context->frbuff_p.p8++; #ifndef NGIFLIB_INDEXED_ONLY } else { context->frbuff_p.p32++; } #endif /* NGIFLIB_INDEXED_ONLY */ } } /* void WritePixels(struct ngiflib_img * i, const u8 * pixels, u16 n); * ecrit les pixels dans le frame buffer */ static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) { u16 tocopy; struct ngiflib_gif * p = i->parent; while(n > 0) { tocopy = (context->Xtogo < n) ? context->Xtogo : n; if(!i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy); pixels += tocopy; context->frbuff_p.p8 += tocopy; #ifndef NGIFLIB_INDEXED_ONLY } else { int j; for(j = (int)tocopy; j > 0; j--) { *(context->frbuff_p.p32++) = GifIndexToTrueColor(i->palette, *pixels++); } } #endif /* NGIFLIB_INDEXED_ONLY */ } else { int j; #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ for(j = (int)tocopy; j > 0; j--) { if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels; pixels++; context->frbuff_p.p8++; } #ifndef NGIFLIB_INDEXED_ONLY } else { for(j = (int)tocopy; j > 0; j--) { if(*pixels != i->gce.transparent_color) { *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels); } pixels++; context->frbuff_p.p32++; } } #endif /* NGIFLIB_INDEXED_ONLY */ } context->Xtogo -= tocopy; if(context->Xtogo == 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 4; } break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 2; } break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 1; } break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } n -= tocopy; } } /* * u16 GetGifWord(struct ngiflib_img * i); * Renvoie un code LZW (taille variable) */ static u16 GetGifWord(struct ngiflib_img * i, struct ngiflib_decode_context * context) { u16 r; int bits_todo; u16 newbyte; bits_todo = (int)context->nbbit - (int)context->restbits; if( bits_todo <= 0) { /* nbbit <= restbits */ r = context->lbyte; context->restbits -= context->nbbit; context->lbyte >>= context->nbbit; } else if( bits_todo > 8 ) { /* nbbit > restbits + 8 */ if(context->restbyte >= 2) { context->restbyte -= 2; r = *context->srcbyte++; } else { if(context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } r = *context->srcbyte++; if(--context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } context->restbyte--; } newbyte = *context->srcbyte++; r |= newbyte << 8; r = (r << context->restbits) | context->lbyte; context->restbits = 16 - bits_todo; context->lbyte = newbyte >> (bits_todo - 8); } else /*if( bits_todo > 0 )*/ { /* nbbit > restbits */ if(context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } newbyte = *context->srcbyte++; context->restbyte--; r = (newbyte << context->restbits) | context->lbyte; context->restbits = 8 - bits_todo; context->lbyte = newbyte >> bits_todo; } return (r & context->max); /* applique le bon masque pour eliminer les bits en trop */ } /* ------------------------------------------------ */ static void FillGifBackGround(struct ngiflib_gif * g) { long n = (long)g->width*g->height; #ifndef NGIFLIB_INDEXED_ONLY u32 bg_truecolor; #endif /* NGIFLIB_INDEXED_ONLY */ if((g->frbuff.p8==NULL)||(g->palette==NULL)) return; #ifndef NGIFLIB_INDEXED_ONLY if(g->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ ngiflib_memset(g->frbuff.p8, g->backgroundindex, n); #ifndef NGIFLIB_INDEXED_ONLY } else { u32 * p = g->frbuff.p32; bg_truecolor = GifIndexToTrueColor(g->palette, g->backgroundindex); while(n-->0) *p++ = bg_truecolor; } #endif /* NGIFLIB_INDEXED_ONLY */ } /* ------------------------------------------------ */ int CheckGif(u8 * b) { return (b[0]=='G')&&(b[1]=='I')&&(b[2]=='F')&&(b[3]=='8'); } /* ------------------------------------------------ */ static int DecodeGifImg(struct ngiflib_img * i) { struct ngiflib_decode_context context; long npix; u8 * stackp; u8 * stack_top; u16 clr; u16 eof; u16 free; u16 act_code = 0; u16 old_code = 0; u16 read_byt; u16 ab_prfx[4096]; u8 ab_suffx[4096]; u8 ab_stack[4096]; u8 flags; u8 casspecial = 0; if(!i) return -1; i->posX = GetWord(i->parent); /* offsetX */ i->posY = GetWord(i->parent); /* offsetY */ i->width = GetWord(i->parent); /* SizeX */ i->height = GetWord(i->parent); /* SizeY */ context.Xtogo = i->width; context.curY = i->posY; #ifdef NGIFLIB_INDEXED_ONLY #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #else if(i->parent->mode & NGIFLIB_MODE_INDEXED) { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width; context.frbuff_p.p32 = context.line_p.p32 + i->posX; #else context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ npix = (long)i->width * i->height; flags = GetByte(i->parent); i->interlaced = (flags & 64) >> 6; context.pass = i->interlaced ? 1 : 0; i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */ i->localpalbits = (flags & 7) + 1; if(flags&128) { /* palette locale */ int k; int localpalsize = 1 << i->localpalbits; #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize); for(k=0; k<localpalsize; k++) { i->palette[k].r = GetByte(i->parent); i->palette[k].g = GetByte(i->parent); i->palette[k].b = GetByte(i->parent); } #ifdef NGIFLIB_ENABLE_CALLBACKS if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { i->palette = i->parent->palette; i->localpalbits = i->parent->imgbits; } i->ncolors = 1 << i->localpalbits; i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */ #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) { if(i->interlaced) fprintf(i->parent->log, "interlaced "); fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n", i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors); } #endif /* !defined(NGIFLIB_NO_FILE) */ if(i->imgbits==1) { /* fix for 1bit images ? */ i->imgbits = 2; } clr = 1 << i->imgbits; eof = clr + 1; free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ stackp = stack_top = ab_stack + 4096; context.restbits = 0; /* initialise le "buffer" de lecture */ context.restbyte = 0; /* des codes LZW */ context.lbyte = 0; for(;;) { act_code = GetGifWord(i, &context); if(act_code==eof) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 0; } if(npix==0) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 1; } if(act_code==clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (free=%hu) npix=%ld\n", free, npix); #endif /* !defined(NGIFLIB_NO_FILE) */ /* clear */ free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ act_code = GetGifWord(i, &context); casspecial = (u8)act_code; old_code = act_code; WritePixel(i, &context, casspecial); npix--; } else { read_byt = act_code; if(act_code >= free) { /* code pas encore dans alphabet */ /* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */ *(--stackp) = casspecial; /* dernier debut de chaine ! */ act_code = old_code; } /* printf("actcode=%d\n", act_code); */ while(act_code > clr) { /* code non concret */ /* fillstackloop empile les suffixes ! */ *(--stackp) = ab_suffx[act_code]; act_code = ab_prfx[act_code]; /* prefixe */ } /* act_code est concret */ casspecial = (u8)act_code; /* dernier debut de chaine ! */ *(--stackp) = casspecial; /* push on stack */ WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */ npix -= (stack_top - stackp); stackp = stack_top; /* putchar('\n'); */ if(free < 4096) { /* la taille du dico est 4096 max ! */ ab_prfx[free] = old_code; ab_suffx[free] = (u8)act_code; free++; if((free > context.max) && (context.nbbit < 12)) { context.nbbit++; /* 1 bit de plus pour les codes LZW */ context.max += context.max + 1; } } old_code = read_byt; } } return 0; } /* ------------------------------------------------ * int LoadGif(struct ngiflib_gif *); * s'assurer que nimg=0 au depart ! * retourne : * 0 si GIF termin� * un nombre negatif si ERREUR * 1 si image Decod�e * rappeler pour decoder les images suivantes * ------------------------------------------------ */ int LoadGif(struct ngiflib_gif * g) { struct ngiflib_gce gce; u8 sign; u8 tmp; int i; if(!g) return -1; gce.gce_present = 0; if(g->nimg==0) { GetByteStr(g, g->signature, 6); g->signature[6] = '\0'; if( g->signature[0] != 'G' || g->signature[1] != 'I' || g->signature[2] != 'F' || g->signature[3] != '8') { return -1; } #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%s\n", g->signature); #endif /* !defined(NGIFLIB_NO_FILE) */ g->width = GetWord(g); g->height = GetWord(g); /* allocate frame buffer */ #ifndef NGIFLIB_INDEXED_ONLY if((g->mode & NGIFLIB_MODE_INDEXED)==0) g->frbuff.p32 = ngiflib_malloc(4*(long)g->height*(long)g->width); else #endif /* NGIFLIB_INDEXED_ONLY */ g->frbuff.p8 = ngiflib_malloc((long)g->height*(long)g->width); tmp = GetByte(g);/* <Packed Fields> = Global Color Table Flag 1 Bit Color Resolution 3 Bits Sort Flag 1 Bit Size of Global Color Table 3 Bits */ g->colorresolution = ((tmp & 0x70) >> 4) + 1; g->sort_flag = (tmp & 8) >> 3; g->imgbits = (tmp & 7) + 1; /* Global Palette color resolution */ g->ncolors = 1 << g->imgbits; g->backgroundindex = GetByte(g); #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%hux%hu %hhubits %hu couleurs bg=%hhu\n", g->width, g->height, g->imgbits, g->ncolors, g->backgroundindex); #endif /* NGIFLIB_INDEXED_ONLY */ g->pixaspectratio = GetByte(g); /* pixel aspect ratio (0 : unspecified) */ if(tmp&0x80) { /* la palette globale suit. */ g->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*g->ncolors); for(i=0; i<g->ncolors; i++) { g->palette[i].r = GetByte(g); g->palette[i].g = GetByte(g); g->palette[i].b = GetByte(g); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%3d %02X %02X %02X\n", i, g->palette[i].r,g->palette[i].g,g->palette[i].b); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ } #ifdef NGIFLIB_ENABLE_CALLBACKS if(g->palette_cb) g->palette_cb(g, g->palette, g->ncolors); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { g->palette = NULL; } g->netscape_loop_count = -1; } for(;;) { char appid_auth[11]; u8 id,size; int blockindex; sign = GetByte(g); /* signature du prochain bloc */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "BLOCK SIGNATURE 0x%02X '%c'\n", sign, (sign >= 32) ? sign : '.'); #endif /* NGIFLIB_INDEXED_ONLY */ switch(sign) { case 0x3B: /* END OF GIF */ return 0; case '!': /* Extension introducer 0x21 */ id = GetByte(g); blockindex = 0; #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "extension (id=0x%02hhx)\n", id); #endif /* NGIFLIB_NO_FILE */ while( (size = GetByte(g)) ) { u8 ext[256]; GetByteStr(g, ext, size); switch(id) { case 0xF9: /* Graphic Control Extension */ /* The scope of this extension is the first graphic * rendering block to follow. */ gce.gce_present = 1; gce.disposal_method = (ext[0] >> 2) & 7; gce.transparent_flag = ext[0] & 1; gce.user_input_flag = (ext[0] >> 1) & 1; gce.delay_time = ext[1] | (ext[2]<<8); gce.transparent_color = ext[3]; #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "disposal_method=%hhu delay_time=%hu (transp=%hhu)transparent_color=0x%02hhX\n", gce.disposal_method, gce.delay_time, gce.transparent_flag, gce.transparent_color); #endif /* NGIFLIB_INDEXED_ONLY */ /* this propably should be adjusted depending on the disposal_method * of the _previous_ image. */ if(gce.transparent_flag && ((g->nimg == 0) || gce.disposal_method == 2)) { FillGifBackGround(g); } break; case 0xFE: /* Comment Extension. */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { if(blockindex==0) fprintf(g->log, "-------------------- Comment extension --------------------\n"); ext[size] = '\0'; fputs((char *)ext, g->log); } #endif /* NGIFLIB_NO_FILE */ break; case 0xFF: /* application extension */ /* NETSCAPE2.0 extension : * http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension */ if(blockindex==0) { ngiflib_memcpy(appid_auth, ext, 11); #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "---------------- Application extension ---------------\n"); fprintf(g->log, "Application identifier : '%.8s', auth code : %02X %02X %02X (", appid_auth, ext[8], ext[9], ext[10]); fputc((ext[8]<32)?' ':ext[8], g->log); fputc((ext[9]<32)?' ':ext[9], g->log); fputc((ext[10]<32)?' ':ext[10], g->log); fprintf(g->log, ")\n"); } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "Datas (as hex) : "); for(i=0; i<size; i++) { fprintf(g->log, "%02x ", ext[i]); } fprintf(g->log, "\nDatas (as text) : '"); for(i=0; i<size; i++) { putc((ext[i]<32)?' ':ext[i], g->log); } fprintf(g->log, "'\n"); } #endif /* NGIFLIB_INDEXED_ONLY */ if(0 == ngiflib_memcmp(appid_auth, "NETSCAPE2.0", 11)) { /* ext[0] : Sub-block ID */ if(ext[0] == 1) { /* 1 : Netscape Looping Extension. */ g->netscape_loop_count = (int)ext[1] | ((int)ext[2] << 8); #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "NETSCAPE loop_count = %d\n", g->netscape_loop_count); } #endif /* NGIFLIB_NO_FILE */ } } } break; case 0x01: /* plain text extension */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "Plain text extension blockindex=%d\n", blockindex); for(i=0; i<size; i++) { putc((ext[i]<32)?' ':ext[i], g->log); } putc('\n', g->log); } #endif /* NGIFLIB_INDEXED_ONLY */ break; } blockindex++; } switch(id) { case 0x01: /* plain text extension */ case 0xFE: /* Comment Extension. */ case 0xFF: /* application extension */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "-----------------------------------------------------------\n"); } #endif /* NGIFLIB_NO_FILE */ break; } break; case 0x2C: /* Image separator */ if(g->nimg==0) { g->cur_img = ngiflib_malloc(sizeof(struct ngiflib_img)); g->first_img = g->cur_img; } else { g->cur_img->next = ngiflib_malloc(sizeof(struct ngiflib_img)); g->cur_img = g->cur_img->next; } g->cur_img->next = NULL; g->cur_img->parent = g; if(gce.gce_present) { ngiflib_memcpy(&g->cur_img->gce, &gce, sizeof(struct ngiflib_gce)); } else { ngiflib_memset(&g->cur_img->gce, 0, sizeof(struct ngiflib_gce)); } DecodeGifImg(g->cur_img); g->nimg++; tmp = GetByte(g);/* 0 final */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "ZERO TERMINATOR 0x%02X\n", tmp); #endif /* NGIFLIB_INDEXED_ONLY */ return 1; /* image decod�e */ default: /* unexpected byte */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "unexpected signature 0x%02X\n", sign); #endif /* NGIFLIB_INDEXED_ONLY */ return -1; } } } u32 GifIndexToTrueColor(struct ngiflib_rgb * palette, u8 v) { return palette[v].b | (palette[v].g << 8) | (palette[v].r << 16); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_105_0
crossvul-cpp_data_good_410_0
/* util.c * * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, * 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others * * You may distribute under the terms of either the GNU General Public * License or the Artistic License, as specified in the README file. * */ /* * 'Very useful, no doubt, that was to Saruman; yet it seems that he was * not content.' --Gandalf to Pippin * * [p.598 of _The Lord of the Rings_, III/xi: "The Palantír"] */ /* This file contains assorted utility routines. * Which is a polite way of saying any stuff that people couldn't think of * a better place for. Amongst other things, it includes the warning and * dieing stuff, plus wrappers for malloc code. */ #include "EXTERN.h" #define PERL_IN_UTIL_C #include "perl.h" #include "reentr.h" #if defined(USE_PERLIO) #include "perliol.h" /* For PerlIOUnix_refcnt */ #endif #ifndef PERL_MICRO #include <signal.h> #ifndef SIG_ERR # define SIG_ERR ((Sighandler_t) -1) #endif #endif #include <math.h> #include <stdlib.h> #ifdef __Lynx__ /* Missing protos on LynxOS */ int putenv(char *); #endif #ifdef __amigaos__ # include "amigaos4/amigaio.h" #endif #ifdef HAS_SELECT # ifdef I_SYS_SELECT # include <sys/select.h> # endif #endif #ifdef USE_C_BACKTRACE # ifdef I_BFD # define USE_BFD # ifdef PERL_DARWIN # undef USE_BFD /* BFD is useless in OS X. */ # endif # ifdef USE_BFD # include <bfd.h> # endif # endif # ifdef I_DLFCN # include <dlfcn.h> # endif # ifdef I_EXECINFO # include <execinfo.h> # endif #endif #ifdef PERL_DEBUG_READONLY_COW # include <sys/mman.h> #endif #define FLUSH /* NOTE: Do not call the next three routines directly. Use the macros * in handy.h, so that we can easily redefine everything to do tracking of * allocated hunks back to the original New to track down any memory leaks. * XXX This advice seems to be widely ignored :-( --AD August 1996. */ #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL) # define ALWAYS_NEED_THX #endif #if defined(PERL_TRACK_MEMPOOL) && defined(PERL_DEBUG_READONLY_COW) static void S_maybe_protect_rw(pTHX_ struct perl_memory_debug_header *header) { if (header->readonly && mprotect(header, header->size, PROT_READ|PROT_WRITE)) Perl_warn(aTHX_ "mprotect for COW string %p %lu failed with %d", header, header->size, errno); } static void S_maybe_protect_ro(pTHX_ struct perl_memory_debug_header *header) { if (header->readonly && mprotect(header, header->size, PROT_READ)) Perl_warn(aTHX_ "mprotect RW for COW string %p %lu failed with %d", header, header->size, errno); } # define maybe_protect_rw(foo) S_maybe_protect_rw(aTHX_ foo) # define maybe_protect_ro(foo) S_maybe_protect_ro(aTHX_ foo) #else # define maybe_protect_rw(foo) NOOP # define maybe_protect_ro(foo) NOOP #endif #if defined(PERL_TRACK_MEMPOOL) || defined(PERL_DEBUG_READONLY_COW) /* Use memory_debug_header */ # define USE_MDH # if (defined(PERL_POISON) && defined(PERL_TRACK_MEMPOOL)) \ || defined(PERL_DEBUG_READONLY_COW) # define MDH_HAS_SIZE # endif #endif /* paranoid version of system's malloc() */ Malloc_t Perl_safesysmalloc(MEM_SIZE size) { #ifdef ALWAYS_NEED_THX dTHX; #endif Malloc_t ptr; #ifdef USE_MDH if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size) goto out_of_memory; size += PERL_MEMORY_DEBUG_HEADER_SIZE; #endif #ifdef DEBUGGING if ((SSize_t)size < 0) Perl_croak_nocontext("panic: malloc, size=%" UVuf, (UV) size); #endif if (!size) size = 1; /* malloc(0) is NASTY on our system */ #ifdef PERL_DEBUG_READONLY_COW if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) { perror("mmap failed"); abort(); } #else ptr = (Malloc_t)PerlMem_malloc(size?size:1); #endif PERL_ALLOC_CHECK(ptr); if (ptr != NULL) { #ifdef USE_MDH struct perl_memory_debug_header *const header = (struct perl_memory_debug_header *)ptr; #endif #ifdef PERL_POISON PoisonNew(((char *)ptr), size, char); #endif #ifdef PERL_TRACK_MEMPOOL header->interpreter = aTHX; /* Link us into the list. */ header->prev = &PL_memory_debug_header; header->next = PL_memory_debug_header.next; PL_memory_debug_header.next = header; maybe_protect_rw(header->next); header->next->prev = header; maybe_protect_ro(header->next); # ifdef PERL_DEBUG_READONLY_COW header->readonly = 0; # endif #endif #ifdef MDH_HAS_SIZE header->size = size; #endif ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE); DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size)); } else { #ifdef USE_MDH out_of_memory: #endif { #ifndef ALWAYS_NEED_THX dTHX; #endif if (PL_nomemok) ptr = NULL; else croak_no_mem(); } } return ptr; } /* paranoid version of system's realloc() */ Malloc_t Perl_safesysrealloc(Malloc_t where,MEM_SIZE size) { #ifdef ALWAYS_NEED_THX dTHX; #endif Malloc_t ptr; #ifdef PERL_DEBUG_READONLY_COW const MEM_SIZE oldsize = where ? ((struct perl_memory_debug_header *)((char *)where - PERL_MEMORY_DEBUG_HEADER_SIZE))->size : 0; #endif if (!size) { safesysfree(where); ptr = NULL; } else if (!where) { ptr = safesysmalloc(size); } else { #ifdef USE_MDH where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE); if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size) goto out_of_memory; size += PERL_MEMORY_DEBUG_HEADER_SIZE; { struct perl_memory_debug_header *const header = (struct perl_memory_debug_header *)where; # ifdef PERL_TRACK_MEMPOOL if (header->interpreter != aTHX) { Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p", header->interpreter, aTHX); } assert(header->next->prev == header); assert(header->prev->next == header); # ifdef PERL_POISON if (header->size > size) { const MEM_SIZE freed_up = header->size - size; char *start_of_freed = ((char *)where) + size; PoisonFree(start_of_freed, freed_up, char); } # endif # endif # ifdef MDH_HAS_SIZE header->size = size; # endif } #endif #ifdef DEBUGGING if ((SSize_t)size < 0) Perl_croak_nocontext("panic: realloc, size=%" UVuf, (UV)size); #endif #ifdef PERL_DEBUG_READONLY_COW if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) { perror("mmap failed"); abort(); } Copy(where,ptr,oldsize < size ? oldsize : size,char); if (munmap(where, oldsize)) { perror("munmap failed"); abort(); } #else ptr = (Malloc_t)PerlMem_realloc(where,size); #endif PERL_ALLOC_CHECK(ptr); /* MUST do this fixup first, before doing ANYTHING else, as anything else might allocate memory/free/move memory, and until we do the fixup, it may well be chasing (and writing to) free memory. */ if (ptr != NULL) { #ifdef PERL_TRACK_MEMPOOL struct perl_memory_debug_header *const header = (struct perl_memory_debug_header *)ptr; # ifdef PERL_POISON if (header->size < size) { const MEM_SIZE fresh = size - header->size; char *start_of_fresh = ((char *)ptr) + size; PoisonNew(start_of_fresh, fresh, char); } # endif maybe_protect_rw(header->next); header->next->prev = header; maybe_protect_ro(header->next); maybe_protect_rw(header->prev); header->prev->next = header; maybe_protect_ro(header->prev); #endif ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE); } /* In particular, must do that fixup above before logging anything via *printf(), as it can reallocate memory, which can cause SEGVs. */ DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++)); DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size)); if (ptr == NULL) { #ifdef USE_MDH out_of_memory: #endif { #ifndef ALWAYS_NEED_THX dTHX; #endif if (PL_nomemok) ptr = NULL; else croak_no_mem(); } } } return ptr; } /* safe version of system's free() */ Free_t Perl_safesysfree(Malloc_t where) { #ifdef ALWAYS_NEED_THX dTHX; #endif DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) free\n",PTR2UV(where),(long)PL_an++)); if (where) { #ifdef USE_MDH Malloc_t where_intrn = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE); { struct perl_memory_debug_header *const header = (struct perl_memory_debug_header *)where_intrn; # ifdef MDH_HAS_SIZE const MEM_SIZE size = header->size; # endif # ifdef PERL_TRACK_MEMPOOL if (header->interpreter != aTHX) { Perl_croak_nocontext("panic: free from wrong pool, %p!=%p", header->interpreter, aTHX); } if (!header->prev) { Perl_croak_nocontext("panic: duplicate free"); } if (!(header->next)) Perl_croak_nocontext("panic: bad free, header->next==NULL"); if (header->next->prev != header || header->prev->next != header) { Perl_croak_nocontext("panic: bad free, ->next->prev=%p, " "header=%p, ->prev->next=%p", header->next->prev, header, header->prev->next); } /* Unlink us from the chain. */ maybe_protect_rw(header->next); header->next->prev = header->prev; maybe_protect_ro(header->next); maybe_protect_rw(header->prev); header->prev->next = header->next; maybe_protect_ro(header->prev); maybe_protect_rw(header); # ifdef PERL_POISON PoisonNew(where_intrn, size, char); # endif /* Trigger the duplicate free warning. */ header->next = NULL; # endif # ifdef PERL_DEBUG_READONLY_COW if (munmap(where_intrn, size)) { perror("munmap failed"); abort(); } # endif } #else Malloc_t where_intrn = where; #endif /* USE_MDH */ #ifndef PERL_DEBUG_READONLY_COW PerlMem_free(where_intrn); #endif } } /* safe version of system's calloc() */ Malloc_t Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size) { #ifdef ALWAYS_NEED_THX dTHX; #endif Malloc_t ptr; #if defined(USE_MDH) || defined(DEBUGGING) MEM_SIZE total_size = 0; #endif /* Even though calloc() for zero bytes is strange, be robust. */ if (size && (count <= MEM_SIZE_MAX / size)) { #if defined(USE_MDH) || defined(DEBUGGING) total_size = size * count; #endif } else croak_memory_wrap(); #ifdef USE_MDH if (PERL_MEMORY_DEBUG_HEADER_SIZE <= MEM_SIZE_MAX - (MEM_SIZE)total_size) total_size += PERL_MEMORY_DEBUG_HEADER_SIZE; else croak_memory_wrap(); #endif #ifdef DEBUGGING if ((SSize_t)size < 0 || (SSize_t)count < 0) Perl_croak_nocontext("panic: calloc, size=%" UVuf ", count=%" UVuf, (UV)size, (UV)count); #endif #ifdef PERL_DEBUG_READONLY_COW if ((ptr = mmap(0, total_size ? total_size : 1, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) { perror("mmap failed"); abort(); } #elif defined(PERL_TRACK_MEMPOOL) /* Have to use malloc() because we've added some space for our tracking header. */ /* malloc(0) is non-portable. */ ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1); #else /* Use calloc() because it might save a memset() if the memory is fresh and clean from the OS. */ if (count && size) ptr = (Malloc_t)PerlMem_calloc(count, size); else /* calloc(0) is non-portable. */ ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1); #endif PERL_ALLOC_CHECK(ptr); DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)total_size)); if (ptr != NULL) { #ifdef USE_MDH { struct perl_memory_debug_header *const header = (struct perl_memory_debug_header *)ptr; # ifndef PERL_DEBUG_READONLY_COW memset((void*)ptr, 0, total_size); # endif # ifdef PERL_TRACK_MEMPOOL header->interpreter = aTHX; /* Link us into the list. */ header->prev = &PL_memory_debug_header; header->next = PL_memory_debug_header.next; PL_memory_debug_header.next = header; maybe_protect_rw(header->next); header->next->prev = header; maybe_protect_ro(header->next); # ifdef PERL_DEBUG_READONLY_COW header->readonly = 0; # endif # endif # ifdef MDH_HAS_SIZE header->size = total_size; # endif ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE); } #endif return ptr; } else { #ifndef ALWAYS_NEED_THX dTHX; #endif if (PL_nomemok) return NULL; croak_no_mem(); } } /* These must be defined when not using Perl's malloc for binary * compatibility */ #ifndef MYMALLOC Malloc_t Perl_malloc (MEM_SIZE nbytes) { #ifdef PERL_IMPLICIT_SYS dTHX; #endif return (Malloc_t)PerlMem_malloc(nbytes); } Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size) { #ifdef PERL_IMPLICIT_SYS dTHX; #endif return (Malloc_t)PerlMem_calloc(elements, size); } Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes) { #ifdef PERL_IMPLICIT_SYS dTHX; #endif return (Malloc_t)PerlMem_realloc(where, nbytes); } Free_t Perl_mfree (Malloc_t where) { #ifdef PERL_IMPLICIT_SYS dTHX; #endif PerlMem_free(where); } #endif /* copy a string up to some (non-backslashed) delimiter, if any. * With allow_escape, converts \<delimiter> to <delimiter>, while leaves * \<non-delimiter> as-is. * Returns the position in the src string of the closing delimiter, if * any, or returns fromend otherwise. * This is the internal implementation for Perl_delimcpy and * Perl_delimcpy_no_escape. */ static char * S_delimcpy_intern(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen, const bool allow_escape) { I32 tolen; PERL_ARGS_ASSERT_DELIMCPY; for (tolen = 0; from < fromend; from++, tolen++) { if (allow_escape && *from == '\\' && from + 1 < fromend) { if (from[1] != delim) { if (to < toend) *to++ = *from; tolen++; } from++; } else if (*from == delim) break; if (to < toend) *to++ = *from; } if (to < toend) *to = '\0'; *retlen = tolen; return (char *)from; } char * Perl_delimcpy(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen) { PERL_ARGS_ASSERT_DELIMCPY; return S_delimcpy_intern(to, toend, from, fromend, delim, retlen, 1); } char * Perl_delimcpy_no_escape(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen) { PERL_ARGS_ASSERT_DELIMCPY_NO_ESCAPE; return S_delimcpy_intern(to, toend, from, fromend, delim, retlen, 0); } /* =head1 Miscellaneous Functions =for apidoc Am|char *|ninstr|char * big|char * bigend|char * little|char * little_end Find the first (leftmost) occurrence of a sequence of bytes within another sequence. This is the Perl version of C<strstr()>, extended to handle arbitrary sequences, potentially containing embedded C<NUL> characters (C<NUL> is what the initial C<n> in the function name stands for; some systems have an equivalent, C<memmem()>, but with a somewhat different API). Another way of thinking about this function is finding a needle in a haystack. C<big> points to the first byte in the haystack. C<big_end> points to one byte beyond the final byte in the haystack. C<little> points to the first byte in the needle. C<little_end> points to one byte beyond the final byte in the needle. All the parameters must be non-C<NULL>. The function returns C<NULL> if there is no occurrence of C<little> within C<big>. If C<little> is the empty string, C<big> is returned. Because this function operates at the byte level, and because of the inherent characteristics of UTF-8 (or UTF-EBCDIC), it will work properly if both the needle and the haystack are strings with the same UTF-8ness, but not if the UTF-8ness differs. =cut */ char * Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend) { PERL_ARGS_ASSERT_NINSTR; #ifdef HAS_MEMMEM return ninstr(big, bigend, little, lend); #else if (little >= lend) return (char*)big; { const char first = *little; bigend -= lend - little++; OUTER: while (big <= bigend) { if (*big++ == first) { const char *s, *x; for (x=big,s=little; s < lend; x++,s++) { if (*s != *x) goto OUTER; } return (char*)(big-1); } } } return NULL; #endif } /* =head1 Miscellaneous Functions =for apidoc Am|char *|rninstr|char * big|char * bigend|char * little|char * little_end Like C<L</ninstr>>, but instead finds the final (rightmost) occurrence of a sequence of bytes within another sequence, returning C<NULL> if there is no such occurrence. =cut */ char * Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend) { const char *bigbeg; const I32 first = *little; const char * const littleend = lend; PERL_ARGS_ASSERT_RNINSTR; if (little >= littleend) return (char*)bigend; bigbeg = big; big = bigend - (littleend - little++); while (big >= bigbeg) { const char *s, *x; if (*big-- != first) continue; for (x=big+2,s=little; s < littleend; /**/ ) { if (*s != *x) break; else { x++; s++; } } if (s >= littleend) return (char*)(big+1); } return NULL; } /* As a space optimization, we do not compile tables for strings of length 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are special-cased in fbm_instr(). If FBMcf_TAIL, the table is created as if the string has a trailing \n. */ /* =head1 Miscellaneous Functions =for apidoc fbm_compile Analyzes the string in order to make fast searches on it using C<fbm_instr()> -- the Boyer-Moore algorithm. =cut */ void Perl_fbm_compile(pTHX_ SV *sv, U32 flags) { const U8 *s; STRLEN i; STRLEN len; U32 frequency = 256; MAGIC *mg; PERL_DEB( STRLEN rarest = 0 ); PERL_ARGS_ASSERT_FBM_COMPILE; if (isGV_with_GP(sv) || SvROK(sv)) return; if (SvVALID(sv)) return; if (flags & FBMcf_TAIL) { MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */ if (mg && mg->mg_len >= 0) mg->mg_len++; } if (!SvPOK(sv) || SvNIOKp(sv)) s = (U8*)SvPV_force_mutable(sv, len); else s = (U8 *)SvPV_mutable(sv, len); if (len == 0) /* TAIL might be on a zero-length string. */ return; SvUPGRADE(sv, SVt_PVMG); SvIOK_off(sv); SvNOK_off(sv); /* add PERL_MAGIC_bm magic holding the FBM lookup table */ assert(!mg_find(sv, PERL_MAGIC_bm)); mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0); assert(mg); if (len > 2) { /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use the BM table. */ const U8 mlen = (len>255) ? 255 : (U8)len; const unsigned char *const sb = s + len - mlen; /* first char (maybe) */ U8 *table; Newx(table, 256, U8); memset((void*)table, mlen, 256); mg->mg_ptr = (char *)table; mg->mg_len = 256; s += len - 1; /* last char */ i = 0; while (s >= sb) { if (table[*s] == mlen) table[*s] = (U8)i; s--, i++; } } s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */ for (i = 0; i < len; i++) { if (PL_freq[s[i]] < frequency) { PERL_DEB( rarest = i ); frequency = PL_freq[s[i]]; } } BmUSEFUL(sv) = 100; /* Initial value */ ((XPVNV*)SvANY(sv))->xnv_u.xnv_bm_tail = cBOOL(flags & FBMcf_TAIL); DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %" UVuf "\n", s[rarest], (UV)rarest)); } /* =for apidoc fbm_instr Returns the location of the SV in the string delimited by C<big> and C<bigend> (C<bigend>) is the char following the last char). It returns C<NULL> if the string can't be found. The C<sv> does not have to be C<fbm_compiled>, but the search will not be as fast then. =cut If SvTAIL(littlestr) is true, a fake "\n" was appended to to the string during FBM compilation due to FBMcf_TAIL in flags. It indicates that the littlestr must be anchored to the end of bigstr (or to any \n if FBMrf_MULTILINE). E.g. The regex compiler would compile /abc/ to a littlestr of "abc", while /abc$/ compiles to "abc\n" with SvTAIL() true. A littlestr of "abc", !SvTAIL matches as /abc/; a littlestr of "ab\n", SvTAIL matches as: without FBMrf_MULTILINE: /ab\n?\z/ with FBMrf_MULTILINE: /ab\n/ || /ab\z/; (According to Ilya from 1999; I don't know if this is still true, DAPM 2015): "If SvTAIL is actually due to \Z or \z, this gives false positives if multiline". */ char * Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags) { unsigned char *s; STRLEN l; const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l); STRLEN littlelen = l; const I32 multiline = flags & FBMrf_MULTILINE; bool valid = SvVALID(littlestr); bool tail = valid ? cBOOL(SvTAIL(littlestr)) : FALSE; PERL_ARGS_ASSERT_FBM_INSTR; assert(bigend >= big); if ((STRLEN)(bigend - big) < littlelen) { if ( tail && ((STRLEN)(bigend - big) == littlelen - 1) && (littlelen == 1 || (*big == *little && memEQ((char *)big, (char *)little, littlelen - 1)))) return (char*)big; return NULL; } switch (littlelen) { /* Special cases for 0, 1 and 2 */ case 0: return (char*)big; /* Cannot be SvTAIL! */ case 1: if (tail && !multiline) /* Anchor only! */ /* [-1] is safe because we know that bigend != big. */ return (char *) (bigend - (bigend[-1] == '\n')); s = (unsigned char *)memchr((void*)big, *little, bigend-big); if (s) return (char *)s; if (tail) return (char *) bigend; return NULL; case 2: if (tail && !multiline) { /* a littlestr with SvTAIL must be of the form "X\n" (where X * is a single char). It is anchored, and can only match * "....X\n" or "....X" */ if (bigend[-2] == *little && bigend[-1] == '\n') return (char*)bigend - 2; if (bigend[-1] == *little) return (char*)bigend - 1; return NULL; } { /* memchr() is likely to be very fast, possibly using whatever * hardware support is available, such as checking a whole * cache line in one instruction. * So for a 2 char pattern, calling memchr() is likely to be * faster than running FBM, or rolling our own. The previous * version of this code was roll-your-own which typically * only needed to read every 2nd char, which was good back in * the day, but no longer. */ unsigned char c1 = little[0]; unsigned char c2 = little[1]; /* *** for all this case, bigend points to the last char, * not the trailing \0: this makes the conditions slightly * simpler */ bigend--; s = big; if (c1 != c2) { while (s < bigend) { /* do a quick test for c1 before calling memchr(); * this avoids the expensive fn call overhead when * there are lots of c1's */ if (LIKELY(*s != c1)) { s++; s = (unsigned char *)memchr((void*)s, c1, bigend - s); if (!s) break; } if (s[1] == c2) return (char*)s; /* failed; try searching for c2 this time; that way * we don't go pathologically slow when the string * consists mostly of c1's or vice versa. */ s += 2; if (s > bigend) break; s = (unsigned char *)memchr((void*)s, c2, bigend - s + 1); if (!s) break; if (s[-1] == c1) return (char*)s - 1; } } else { /* c1, c2 the same */ while (s < bigend) { if (s[0] == c1) { got_1char: if (s[1] == c1) return (char*)s; s += 2; } else { s++; s = (unsigned char *)memchr((void*)s, c1, bigend - s); if (!s || s >= bigend) break; goto got_1char; } } } /* failed to find 2 chars; try anchored match at end without * the \n */ if (tail && bigend[0] == little[0]) return (char *)bigend; return NULL; } default: break; /* Only lengths 0 1 and 2 have special-case code. */ } if (tail && !multiline) { /* tail anchored? */ s = bigend - littlelen; if (s >= big && bigend[-1] == '\n' && *s == *little /* Automatically of length > 2 */ && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2)) { return (char*)s; /* how sweet it is */ } if (s[1] == *little && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2)) { return (char*)s + 1; /* how sweet it is */ } return NULL; } if (!valid) { /* not compiled; use Perl_ninstr() instead */ char * const b = ninstr((char*)big,(char*)bigend, (char*)little, (char*)little + littlelen); assert(!tail); /* valid => FBM; tail only set on SvVALID SVs */ return b; } /* Do actual FBM. */ if (littlelen > (STRLEN)(bigend - big)) return NULL; { const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm); const unsigned char *oldlittle; assert(mg); --littlelen; /* Last char found by table lookup */ s = big + littlelen; little += littlelen; /* last char */ oldlittle = little; if (s < bigend) { const unsigned char * const table = (const unsigned char *) mg->mg_ptr; const unsigned char lastc = *little; I32 tmp; top2: if ((tmp = table[*s])) { /* *s != lastc; earliest position it could match now is * tmp slots further on */ if ((s += tmp) >= bigend) goto check_end; if (LIKELY(*s != lastc)) { s++; s = (unsigned char *)memchr((void*)s, lastc, bigend - s); if (!s) { s = bigend; goto check_end; } goto top2; } } /* hand-rolled strncmp(): less expensive than calling the * real function (maybe???) */ { unsigned char * const olds = s; tmp = littlelen; while (tmp--) { if (*--s == *--little) continue; s = olds + 1; /* here we pay the price for failure */ little = oldlittle; if (s < bigend) /* fake up continue to outer loop */ goto top2; goto check_end; } return (char *)s; } } check_end: if ( s == bigend && tail && memEQ((char *)(bigend - littlelen), (char *)(oldlittle - littlelen), littlelen) ) return (char*)bigend - littlelen; return NULL; } } /* copy a string to a safe spot */ /* =head1 Memory Management =for apidoc savepv Perl's version of C<strdup()>. Returns a pointer to a newly allocated string which is a duplicate of C<pv>. The size of the string is determined by C<strlen()>, which means it may not contain embedded C<NUL> characters and must have a trailing C<NUL>. The memory allocated for the new string can be freed with the C<Safefree()> function. On some platforms, Windows for example, all allocated memory owned by a thread is deallocated when that thread ends. So if you need that not to happen, you need to use the shared memory functions, such as C<L</savesharedpv>>. =cut */ char * Perl_savepv(pTHX_ const char *pv) { PERL_UNUSED_CONTEXT; if (!pv) return NULL; else { char *newaddr; const STRLEN pvlen = strlen(pv)+1; Newx(newaddr, pvlen, char); return (char*)memcpy(newaddr, pv, pvlen); } } /* same thing but with a known length */ /* =for apidoc savepvn Perl's version of what C<strndup()> would be if it existed. Returns a pointer to a newly allocated string which is a duplicate of the first C<len> bytes from C<pv>, plus a trailing C<NUL> byte. The memory allocated for the new string can be freed with the C<Safefree()> function. On some platforms, Windows for example, all allocated memory owned by a thread is deallocated when that thread ends. So if you need that not to happen, you need to use the shared memory functions, such as C<L</savesharedpvn>>. =cut */ char * Perl_savepvn(pTHX_ const char *pv, I32 len) { char *newaddr; PERL_UNUSED_CONTEXT; assert(len >= 0); Newx(newaddr,len+1,char); /* Give a meaning to NULL pointer mainly for the use in sv_magic() */ if (pv) { /* might not be null terminated */ newaddr[len] = '\0'; return (char *) CopyD(pv,newaddr,len,char); } else { return (char *) ZeroD(newaddr,len+1,char); } } /* =for apidoc savesharedpv A version of C<savepv()> which allocates the duplicate string in memory which is shared between threads. =cut */ char * Perl_savesharedpv(pTHX_ const char *pv) { char *newaddr; STRLEN pvlen; PERL_UNUSED_CONTEXT; if (!pv) return NULL; pvlen = strlen(pv)+1; newaddr = (char*)PerlMemShared_malloc(pvlen); if (!newaddr) { croak_no_mem(); } return (char*)memcpy(newaddr, pv, pvlen); } /* =for apidoc savesharedpvn A version of C<savepvn()> which allocates the duplicate string in memory which is shared between threads. (With the specific difference that a C<NULL> pointer is not acceptable) =cut */ char * Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len) { char *const newaddr = (char*)PerlMemShared_malloc(len + 1); PERL_UNUSED_CONTEXT; /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */ if (!newaddr) { croak_no_mem(); } newaddr[len] = '\0'; return (char*)memcpy(newaddr, pv, len); } /* =for apidoc savesvpv A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from the passed in SV using C<SvPV()> On some platforms, Windows for example, all allocated memory owned by a thread is deallocated when that thread ends. So if you need that not to happen, you need to use the shared memory functions, such as C<L</savesharedsvpv>>. =cut */ char * Perl_savesvpv(pTHX_ SV *sv) { STRLEN len; const char * const pv = SvPV_const(sv, len); char *newaddr; PERL_ARGS_ASSERT_SAVESVPV; ++len; Newx(newaddr,len,char); return (char *) CopyD(pv,newaddr,len,char); } /* =for apidoc savesharedsvpv A version of C<savesharedpv()> which allocates the duplicate string in memory which is shared between threads. =cut */ char * Perl_savesharedsvpv(pTHX_ SV *sv) { STRLEN len; const char * const pv = SvPV_const(sv, len); PERL_ARGS_ASSERT_SAVESHAREDSVPV; return savesharedpvn(pv, len); } /* the SV for Perl_form() and mess() is not kept in an arena */ STATIC SV * S_mess_alloc(pTHX) { SV *sv; XPVMG *any; if (PL_phase != PERL_PHASE_DESTRUCT) return newSVpvs_flags("", SVs_TEMP); if (PL_mess_sv) return PL_mess_sv; /* Create as PVMG now, to avoid any upgrading later */ Newx(sv, 1, SV); Newxz(any, 1, XPVMG); SvFLAGS(sv) = SVt_PVMG; SvANY(sv) = (void*)any; SvPV_set(sv, NULL); SvREFCNT(sv) = 1 << 30; /* practically infinite */ PL_mess_sv = sv; return sv; } #if defined(PERL_IMPLICIT_CONTEXT) char * Perl_form_nocontext(const char* pat, ...) { dTHX; char *retval; va_list args; PERL_ARGS_ASSERT_FORM_NOCONTEXT; va_start(args, pat); retval = vform(pat, &args); va_end(args); return retval; } #endif /* PERL_IMPLICIT_CONTEXT */ /* =head1 Miscellaneous Functions =for apidoc form Takes a sprintf-style format pattern and conventional (non-SV) arguments and returns the formatted string. (char *) Perl_form(pTHX_ const char* pat, ...) can be used any place a string (char *) is required: char * s = Perl_form("%d.%d",major,minor); Uses a single private buffer so if you want to format several strings you must explicitly copy the earlier strings away (and free the copies when you are done). =cut */ char * Perl_form(pTHX_ const char* pat, ...) { char *retval; va_list args; PERL_ARGS_ASSERT_FORM; va_start(args, pat); retval = vform(pat, &args); va_end(args); return retval; } char * Perl_vform(pTHX_ const char *pat, va_list *args) { SV * const sv = mess_alloc(); PERL_ARGS_ASSERT_VFORM; sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL); return SvPVX(sv); } /* =for apidoc Am|SV *|mess|const char *pat|... Take a sprintf-style format pattern and argument list. These are used to generate a string message. If the message does not end with a newline, then it will be extended with some indication of the current location in the code, as described for L</mess_sv>. Normally, the resulting message is returned in a new mortal SV. During global destruction a single SV may be shared between uses of this function. =cut */ #if defined(PERL_IMPLICIT_CONTEXT) SV * Perl_mess_nocontext(const char *pat, ...) { dTHX; SV *retval; va_list args; PERL_ARGS_ASSERT_MESS_NOCONTEXT; va_start(args, pat); retval = vmess(pat, &args); va_end(args); return retval; } #endif /* PERL_IMPLICIT_CONTEXT */ SV * Perl_mess(pTHX_ const char *pat, ...) { SV *retval; va_list args; PERL_ARGS_ASSERT_MESS; va_start(args, pat); retval = vmess(pat, &args); va_end(args); return retval; } const COP* Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop, bool opnext) { /* Look for curop starting from o. cop is the last COP we've seen. */ /* opnext means that curop is actually the ->op_next of the op we are seeking. */ PERL_ARGS_ASSERT_CLOSEST_COP; if (!o || !curop || ( opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop )) return cop; if (o->op_flags & OPf_KIDS) { const OP *kid; for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) { const COP *new_cop; /* If the OP_NEXTSTATE has been optimised away we can still use it * the get the file and line number. */ if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE) cop = (const COP *)kid; /* Keep searching, and return when we've found something. */ new_cop = closest_cop(cop, kid, curop, opnext); if (new_cop) return new_cop; } } /* Nothing found. */ return NULL; } /* =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume Expands a message, intended for the user, to include an indication of the current location in the code, if the message does not already appear to be complete. C<basemsg> is the initial message or object. If it is a reference, it will be used as-is and will be the result of this function. Otherwise it is used as a string, and if it already ends with a newline, it is taken to be complete, and the result of this function will be the same string. If the message does not end with a newline, then a segment such as C<at foo.pl line 37> will be appended, and possibly other clauses indicating the current state of execution. The resulting message will end with a dot and a newline. Normally, the resulting message is returned in a new mortal SV. During global destruction a single SV may be shared between uses of this function. If C<consume> is true, then the function is permitted (but not required) to modify and return C<basemsg> instead of allocating a new SV. =cut */ SV * Perl_mess_sv(pTHX_ SV *basemsg, bool consume) { SV *sv; #if defined(USE_C_BACKTRACE) && defined(USE_C_BACKTRACE_ON_ERROR) { char *ws; UV wi; /* The PERL_C_BACKTRACE_ON_WARN must be an integer of one or more. */ if ((ws = PerlEnv_getenv("PERL_C_BACKTRACE_ON_ERROR")) && grok_atoUV(ws, &wi, NULL) && wi <= PERL_INT_MAX ) { Perl_dump_c_backtrace(aTHX_ Perl_debug_log, (int)wi, 1); } } #endif PERL_ARGS_ASSERT_MESS_SV; if (SvROK(basemsg)) { if (consume) { sv = basemsg; } else { sv = mess_alloc(); sv_setsv(sv, basemsg); } return sv; } if (SvPOK(basemsg) && consume) { sv = basemsg; } else { sv = mess_alloc(); sv_copypv(sv, basemsg); } if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') { /* * Try and find the file and line for PL_op. This will usually be * PL_curcop, but it might be a cop that has been optimised away. We * can try to find such a cop by searching through the optree starting * from the sibling of PL_curcop. */ if (PL_curcop) { const COP *cop = closest_cop(PL_curcop, OpSIBLING(PL_curcop), PL_op, FALSE); if (!cop) cop = PL_curcop; if (CopLINE(cop)) Perl_sv_catpvf(aTHX_ sv, " at %s line %" IVdf, OutCopFILE(cop), (IV)CopLINE(cop)); } /* Seems that GvIO() can be untrustworthy during global destruction. */ if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO) && IoLINES(GvIOp(PL_last_in_gv))) { STRLEN l; const bool line_mode = (RsSIMPLE(PL_rs) && *SvPV_const(PL_rs,l) == '\n' && l == 1); Perl_sv_catpvf(aTHX_ sv, ", <%" SVf "> %s %" IVdf, SVfARG(PL_last_in_gv == PL_argvgv ? &PL_sv_no : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))), line_mode ? "line" : "chunk", (IV)IoLINES(GvIOp(PL_last_in_gv))); } if (PL_phase == PERL_PHASE_DESTRUCT) sv_catpvs(sv, " during global destruction"); sv_catpvs(sv, ".\n"); } return sv; } /* =for apidoc Am|SV *|vmess|const char *pat|va_list *args C<pat> and C<args> are a sprintf-style format pattern and encapsulated argument list, respectively. These are used to generate a string message. If the message does not end with a newline, then it will be extended with some indication of the current location in the code, as described for L</mess_sv>. Normally, the resulting message is returned in a new mortal SV. During global destruction a single SV may be shared between uses of this function. =cut */ SV * Perl_vmess(pTHX_ const char *pat, va_list *args) { SV * const sv = mess_alloc(); PERL_ARGS_ASSERT_VMESS; sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL); return mess_sv(sv, 1); } void Perl_write_to_stderr(pTHX_ SV* msv) { IO *io; MAGIC *mg; PERL_ARGS_ASSERT_WRITE_TO_STDERR; if (PL_stderrgv && SvREFCNT(PL_stderrgv) && (io = GvIO(PL_stderrgv)) && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar))) Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT), G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv); else { PerlIO * const serr = Perl_error_log; do_print(msv, serr); (void)PerlIO_flush(serr); } } /* =head1 Warning and Dieing */ /* Common code used in dieing and warning */ STATIC SV * S_with_queued_errors(pTHX_ SV *ex) { PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS; if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) { sv_catsv(PL_errors, ex); ex = sv_mortalcopy(PL_errors); SvCUR_set(PL_errors, 0); } return ex; } STATIC bool S_invoke_exception_hook(pTHX_ SV *ex, bool warn) { HV *stash; GV *gv; CV *cv; SV **const hook = warn ? &PL_warnhook : &PL_diehook; /* sv_2cv might call Perl_croak() or Perl_warner() */ SV * const oldhook = *hook; if (!oldhook) return FALSE; ENTER; SAVESPTR(*hook); *hook = NULL; cv = sv_2cv(oldhook, &stash, &gv, 0); LEAVE; if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) { dSP; SV *exarg; ENTER; save_re_context(); if (warn) { SAVESPTR(*hook); *hook = NULL; } exarg = newSVsv(ex); SvREADONLY_on(exarg); SAVEFREESV(exarg); PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK); PUSHMARK(SP); XPUSHs(exarg); PUTBACK; call_sv(MUTABLE_SV(cv), G_DISCARD); POPSTACK; LEAVE; return TRUE; } return FALSE; } /* =for apidoc Am|OP *|die_sv|SV *baseex Behaves the same as L</croak_sv>, except for the return type. It should be used only where the C<OP *> return type is required. The function never actually returns. =cut */ #ifdef _MSC_VER # pragma warning( push ) # pragma warning( disable : 4646 ) /* warning C4646: function declared with __declspec(noreturn) has non-void return type */ # pragma warning( disable : 4645 ) /* warning C4645: function declared with __declspec(noreturn) has a return statement */ #endif OP * Perl_die_sv(pTHX_ SV *baseex) { PERL_ARGS_ASSERT_DIE_SV; croak_sv(baseex); /* NOTREACHED */ NORETURN_FUNCTION_END; } #ifdef _MSC_VER # pragma warning( pop ) #endif /* =for apidoc Am|OP *|die|const char *pat|... Behaves the same as L</croak>, except for the return type. It should be used only where the C<OP *> return type is required. The function never actually returns. =cut */ #if defined(PERL_IMPLICIT_CONTEXT) #ifdef _MSC_VER # pragma warning( push ) # pragma warning( disable : 4646 ) /* warning C4646: function declared with __declspec(noreturn) has non-void return type */ # pragma warning( disable : 4645 ) /* warning C4645: function declared with __declspec(noreturn) has a return statement */ #endif OP * Perl_die_nocontext(const char* pat, ...) { dTHX; va_list args; va_start(args, pat); vcroak(pat, &args); NOT_REACHED; /* NOTREACHED */ va_end(args); NORETURN_FUNCTION_END; } #ifdef _MSC_VER # pragma warning( pop ) #endif #endif /* PERL_IMPLICIT_CONTEXT */ #ifdef _MSC_VER # pragma warning( push ) # pragma warning( disable : 4646 ) /* warning C4646: function declared with __declspec(noreturn) has non-void return type */ # pragma warning( disable : 4645 ) /* warning C4645: function declared with __declspec(noreturn) has a return statement */ #endif OP * Perl_die(pTHX_ const char* pat, ...) { va_list args; va_start(args, pat); vcroak(pat, &args); NOT_REACHED; /* NOTREACHED */ va_end(args); NORETURN_FUNCTION_END; } #ifdef _MSC_VER # pragma warning( pop ) #endif /* =for apidoc Am|void|croak_sv|SV *baseex This is an XS interface to Perl's C<die> function. C<baseex> is the error message or object. If it is a reference, it will be used as-is. Otherwise it is used as a string, and if it does not end with a newline then it will be extended with some indication of the current location in the code, as described for L</mess_sv>. The error message or object will be used as an exception, by default returning control to the nearest enclosing C<eval>, but subject to modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv> function never returns normally. To die with a simple string message, the L</croak> function may be more convenient. =cut */ void Perl_croak_sv(pTHX_ SV *baseex) { SV *ex = with_queued_errors(mess_sv(baseex, 0)); PERL_ARGS_ASSERT_CROAK_SV; invoke_exception_hook(ex, FALSE); die_unwind(ex); } /* =for apidoc Am|void|vcroak|const char *pat|va_list *args This is an XS interface to Perl's C<die> function. C<pat> and C<args> are a sprintf-style format pattern and encapsulated argument list. These are used to generate a string message. If the message does not end with a newline, then it will be extended with some indication of the current location in the code, as described for L</mess_sv>. The error message will be used as an exception, by default returning control to the nearest enclosing C<eval>, but subject to modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak> function never returns normally. For historical reasons, if C<pat> is null then the contents of C<ERRSV> (C<$@>) will be used as an error message or object instead of building an error message from arguments. If you want to throw a non-string object, or build an error message in an SV yourself, it is preferable to use the L</croak_sv> function, which does not involve clobbering C<ERRSV>. =cut */ void Perl_vcroak(pTHX_ const char* pat, va_list *args) { SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0)); invoke_exception_hook(ex, FALSE); die_unwind(ex); } /* =for apidoc Am|void|croak|const char *pat|... This is an XS interface to Perl's C<die> function. Take a sprintf-style format pattern and argument list. These are used to generate a string message. If the message does not end with a newline, then it will be extended with some indication of the current location in the code, as described for L</mess_sv>. The error message will be used as an exception, by default returning control to the nearest enclosing C<eval>, but subject to modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak> function never returns normally. For historical reasons, if C<pat> is null then the contents of C<ERRSV> (C<$@>) will be used as an error message or object instead of building an error message from arguments. If you want to throw a non-string object, or build an error message in an SV yourself, it is preferable to use the L</croak_sv> function, which does not involve clobbering C<ERRSV>. =cut */ #if defined(PERL_IMPLICIT_CONTEXT) void Perl_croak_nocontext(const char *pat, ...) { dTHX; va_list args; va_start(args, pat); vcroak(pat, &args); NOT_REACHED; /* NOTREACHED */ va_end(args); } #endif /* PERL_IMPLICIT_CONTEXT */ void Perl_croak(pTHX_ const char *pat, ...) { va_list args; va_start(args, pat); vcroak(pat, &args); NOT_REACHED; /* NOTREACHED */ va_end(args); } /* =for apidoc Am|void|croak_no_modify Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates terser object code than using C<Perl_croak>. Less code used on exception code paths reduces CPU cache pressure. =cut */ void Perl_croak_no_modify(void) { Perl_croak_nocontext( "%s", PL_no_modify); } /* does not return, used in util.c perlio.c and win32.c This is typically called when malloc returns NULL. */ void Perl_croak_no_mem(void) { dTHX; int fd = PerlIO_fileno(Perl_error_log); if (fd < 0) SETERRNO(EBADF,RMS_IFI); else { /* Can't use PerlIO to write as it allocates memory */ PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1)); } my_exit(1); } /* does not return, used only in POPSTACK */ void Perl_croak_popstack(void) { dTHX; PerlIO_printf(Perl_error_log, "panic: POPSTACK\n"); my_exit(1); } /* =for apidoc Am|void|warn_sv|SV *baseex This is an XS interface to Perl's C<warn> function. C<baseex> is the error message or object. If it is a reference, it will be used as-is. Otherwise it is used as a string, and if it does not end with a newline then it will be extended with some indication of the current location in the code, as described for L</mess_sv>. The error message or object will by default be written to standard error, but this is subject to modification by a C<$SIG{__WARN__}> handler. To warn with a simple string message, the L</warn> function may be more convenient. =cut */ void Perl_warn_sv(pTHX_ SV *baseex) { SV *ex = mess_sv(baseex, 0); PERL_ARGS_ASSERT_WARN_SV; if (!invoke_exception_hook(ex, TRUE)) write_to_stderr(ex); } /* =for apidoc Am|void|vwarn|const char *pat|va_list *args This is an XS interface to Perl's C<warn> function. C<pat> and C<args> are a sprintf-style format pattern and encapsulated argument list. These are used to generate a string message. If the message does not end with a newline, then it will be extended with some indication of the current location in the code, as described for L</mess_sv>. The error message or object will by default be written to standard error, but this is subject to modification by a C<$SIG{__WARN__}> handler. Unlike with L</vcroak>, C<pat> is not permitted to be null. =cut */ void Perl_vwarn(pTHX_ const char* pat, va_list *args) { SV *ex = vmess(pat, args); PERL_ARGS_ASSERT_VWARN; if (!invoke_exception_hook(ex, TRUE)) write_to_stderr(ex); } /* =for apidoc Am|void|warn|const char *pat|... This is an XS interface to Perl's C<warn> function. Take a sprintf-style format pattern and argument list. These are used to generate a string message. If the message does not end with a newline, then it will be extended with some indication of the current location in the code, as described for L</mess_sv>. The error message or object will by default be written to standard error, but this is subject to modification by a C<$SIG{__WARN__}> handler. Unlike with L</croak>, C<pat> is not permitted to be null. =cut */ #if defined(PERL_IMPLICIT_CONTEXT) void Perl_warn_nocontext(const char *pat, ...) { dTHX; va_list args; PERL_ARGS_ASSERT_WARN_NOCONTEXT; va_start(args, pat); vwarn(pat, &args); va_end(args); } #endif /* PERL_IMPLICIT_CONTEXT */ void Perl_warn(pTHX_ const char *pat, ...) { va_list args; PERL_ARGS_ASSERT_WARN; va_start(args, pat); vwarn(pat, &args); va_end(args); } #if defined(PERL_IMPLICIT_CONTEXT) void Perl_warner_nocontext(U32 err, const char *pat, ...) { dTHX; va_list args; PERL_ARGS_ASSERT_WARNER_NOCONTEXT; va_start(args, pat); vwarner(err, pat, &args); va_end(args); } #endif /* PERL_IMPLICIT_CONTEXT */ void Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...) { PERL_ARGS_ASSERT_CK_WARNER_D; if (Perl_ckwarn_d(aTHX_ err)) { va_list args; va_start(args, pat); vwarner(err, pat, &args); va_end(args); } } void Perl_ck_warner(pTHX_ U32 err, const char* pat, ...) { PERL_ARGS_ASSERT_CK_WARNER; if (Perl_ckwarn(aTHX_ err)) { va_list args; va_start(args, pat); vwarner(err, pat, &args); va_end(args); } } void Perl_warner(pTHX_ U32 err, const char* pat,...) { va_list args; PERL_ARGS_ASSERT_WARNER; va_start(args, pat); vwarner(err, pat, &args); va_end(args); } void Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args) { dVAR; PERL_ARGS_ASSERT_VWARNER; if ( (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) && !(PL_in_eval & EVAL_KEEPERR) ) { SV * const msv = vmess(pat, args); if (PL_parser && PL_parser->error_count) { qerror(msv); } else { invoke_exception_hook(msv, FALSE); die_unwind(msv); } } else { Perl_vwarn(aTHX_ pat, args); } } /* implements the ckWARN? macros */ bool Perl_ckwarn(pTHX_ U32 w) { /* If lexical warnings have not been set, use $^W. */ if (isLEXWARN_off) return PL_dowarn & G_WARN_ON; return ckwarn_common(w); } /* implements the ckWARN?_d macro */ bool Perl_ckwarn_d(pTHX_ U32 w) { /* If lexical warnings have not been set then default classes warn. */ if (isLEXWARN_off) return TRUE; return ckwarn_common(w); } static bool S_ckwarn_common(pTHX_ U32 w) { if (PL_curcop->cop_warnings == pWARN_ALL) return TRUE; if (PL_curcop->cop_warnings == pWARN_NONE) return FALSE; /* Check the assumption that at least the first slot is non-zero. */ assert(unpackWARN1(w)); /* Check the assumption that it is valid to stop as soon as a zero slot is seen. */ if (!unpackWARN2(w)) { assert(!unpackWARN3(w)); assert(!unpackWARN4(w)); } else if (!unpackWARN3(w)) { assert(!unpackWARN4(w)); } /* Right, dealt with all the special cases, which are implemented as non- pointers, so there is a pointer to a real warnings mask. */ do { if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))) return TRUE; } while (w >>= WARNshift); return FALSE; } /* Set buffer=NULL to get a new one. */ STRLEN * Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits, STRLEN size) { const MEM_SIZE len_wanted = sizeof(STRLEN) + (size > WARNsize ? size : WARNsize); PERL_UNUSED_CONTEXT; PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD; buffer = (STRLEN*) (specialWARN(buffer) ? PerlMemShared_malloc(len_wanted) : PerlMemShared_realloc(buffer, len_wanted)); buffer[0] = size; Copy(bits, (buffer + 1), size, char); if (size < WARNsize) Zero((char *)(buffer + 1) + size, WARNsize - size, char); return buffer; } /* since we've already done strlen() for both nam and val * we can use that info to make things faster than * sprintf(s, "%s=%s", nam, val) */ #define my_setenv_format(s, nam, nlen, val, vlen) \ Copy(nam, s, nlen, char); \ *(s+nlen) = '='; \ Copy(val, s+(nlen+1), vlen, char); \ *(s+(nlen+1+vlen)) = '\0' #ifdef USE_ENVIRON_ARRAY /* small wrapper for use by Perl_my_setenv that mallocs, or reallocs if * 'current' is non-null, with up to three sizes that are added together. * It handles integer overflow. */ static char * S_env_alloc(void *current, Size_t l1, Size_t l2, Size_t l3, Size_t size) { void *p; Size_t sl, l = l1 + l2; if (l < l2) goto panic; l += l3; if (l < l3) goto panic; sl = l * size; if (sl < l) goto panic; p = current ? safesysrealloc(current, sl) : safesysmalloc(sl); if (p) return (char*)p; panic: croak_memory_wrap(); } /* VMS' my_setenv() is in vms.c */ #if !defined(WIN32) && !defined(NETWARE) void Perl_my_setenv(pTHX_ const char *nam, const char *val) { dVAR; #ifdef __amigaos4__ amigaos4_obtain_environ(__FUNCTION__); #endif #ifdef USE_ITHREADS /* only parent thread can modify process environment */ if (PL_curinterp == aTHX) #endif { #ifndef PERL_USE_SAFE_PUTENV if (!PL_use_safe_putenv) { /* most putenv()s leak, so we manipulate environ directly */ UV i; Size_t vlen, nlen = strlen(nam); /* where does it go? */ for (i = 0; environ[i]; i++) { if (strnEQ(environ[i], nam, nlen) && environ[i][nlen] == '=') break; } if (environ == PL_origenviron) { /* need we copy environment? */ UV j, max; char **tmpenv; max = i; while (environ[max]) max++; /* XXX shouldn't that be max+1 rather than max+2 ??? - DAPM */ tmpenv = (char**)S_env_alloc(NULL, max, 2, 0, sizeof(char*)); for (j=0; j<max; j++) { /* copy environment */ const Size_t len = strlen(environ[j]); tmpenv[j] = S_env_alloc(NULL, len, 1, 0, 1); Copy(environ[j], tmpenv[j], len+1, char); } tmpenv[max] = NULL; environ = tmpenv; /* tell exec where it is now */ } if (!val) { safesysfree(environ[i]); while (environ[i]) { environ[i] = environ[i+1]; i++; } #ifdef __amigaos4__ goto my_setenv_out; #else return; #endif } if (!environ[i]) { /* does not exist yet */ environ = (char**)S_env_alloc(environ, i, 2, 0, sizeof(char*)); environ[i+1] = NULL; /* make sure it's null terminated */ } else safesysfree(environ[i]); vlen = strlen(val); environ[i] = S_env_alloc(NULL, nlen, vlen, 2, 1); /* all that work just for this */ my_setenv_format(environ[i], nam, nlen, val, vlen); } else { # endif /* This next branch should only be called #if defined(HAS_SETENV), but Configure doesn't test for that yet. For Solaris, setenv() and unsetenv() were introduced in Solaris 9, so testing for HAS UNSETENV is sufficient. */ # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__) || (defined(__sun) && defined(HAS_UNSETENV)) || defined(PERL_DARWIN) # if defined(HAS_UNSETENV) if (val == NULL) { (void)unsetenv(nam); } else { (void)setenv(nam, val, 1); } # else /* ! HAS_UNSETENV */ (void)setenv(nam, val, 1); # endif /* HAS_UNSETENV */ # elif defined(HAS_UNSETENV) if (val == NULL) { if (environ) /* old glibc can crash with null environ */ (void)unsetenv(nam); } else { const Size_t nlen = strlen(nam); const Size_t vlen = strlen(val); char * const new_env = S_env_alloc(NULL, nlen, vlen, 2, 1); my_setenv_format(new_env, nam, nlen, val, vlen); (void)putenv(new_env); } # else /* ! HAS_UNSETENV */ char *new_env; const Size_t nlen = strlen(nam); Size_t vlen; if (!val) { val = ""; } vlen = strlen(val); new_env = S_env_alloc(NULL, nlen, vlen, 2, 1); /* all that work just for this */ my_setenv_format(new_env, nam, nlen, val, vlen); (void)putenv(new_env); # endif /* __CYGWIN__ */ #ifndef PERL_USE_SAFE_PUTENV } #endif } #ifdef __amigaos4__ my_setenv_out: amigaos4_release_environ(__FUNCTION__); #endif } #else /* WIN32 || NETWARE */ void Perl_my_setenv(pTHX_ const char *nam, const char *val) { dVAR; char *envstr; const Size_t nlen = strlen(nam); Size_t vlen; if (!val) { val = ""; } vlen = strlen(val); envstr = S_env_alloc(NULL, nlen, vlen, 2, 1); my_setenv_format(envstr, nam, nlen, val, vlen); (void)PerlEnv_putenv(envstr); Safefree(envstr); } #endif /* WIN32 || NETWARE */ #endif /* !VMS */ #ifdef UNLINK_ALL_VERSIONS I32 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */ { I32 retries = 0; PERL_ARGS_ASSERT_UNLNK; while (PerlLIO_unlink(f) >= 0) retries++; return retries ? 0 : -1; } #endif PerlIO * Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args) { #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__) int p[2]; I32 This, that; Pid_t pid; SV *sv; I32 did_pipes = 0; int pp[2]; PERL_ARGS_ASSERT_MY_POPEN_LIST; PERL_FLUSHALL_FOR_CHILD; This = (*mode == 'w'); that = !This; if (TAINTING_get) { taint_env(); taint_proper("Insecure %s%s", "EXEC"); } if (PerlProc_pipe_cloexec(p) < 0) return NULL; /* Try for another pipe pair for error return */ if (PerlProc_pipe_cloexec(pp) >= 0) did_pipes = 1; while ((pid = PerlProc_fork()) < 0) { if (errno != EAGAIN) { PerlLIO_close(p[This]); PerlLIO_close(p[that]); if (did_pipes) { PerlLIO_close(pp[0]); PerlLIO_close(pp[1]); } return NULL; } Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds"); sleep(5); } if (pid == 0) { /* Child */ #undef THIS #undef THAT #define THIS that #define THAT This /* Close parent's end of error status pipe (if any) */ if (did_pipes) PerlLIO_close(pp[0]); /* Now dup our end of _the_ pipe to right position */ if (p[THIS] != (*mode == 'r')) { PerlLIO_dup2(p[THIS], *mode == 'r'); PerlLIO_close(p[THIS]); if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */ PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */ } else PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */ #if !defined(HAS_FCNTL) || !defined(F_SETFD) /* No automatic close - do it by hand */ # ifndef NOFILE # define NOFILE 20 # endif { int fd; for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) { if (fd != pp[1]) PerlLIO_close(fd); } } #endif do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes); PerlProc__exit(1); #undef THIS #undef THAT } /* Parent */ if (did_pipes) PerlLIO_close(pp[1]); /* Keep the lower of the two fd numbers */ if (p[that] < p[This]) { PerlLIO_dup2_cloexec(p[This], p[that]); PerlLIO_close(p[This]); p[This] = p[that]; } else PerlLIO_close(p[that]); /* close child's end of pipe */ sv = *av_fetch(PL_fdpid,p[This],TRUE); SvUPGRADE(sv,SVt_IV); SvIV_set(sv, pid); PL_forkprocess = pid; /* If we managed to get status pipe check for exec fail */ if (did_pipes && pid > 0) { int errkid; unsigned n = 0; while (n < sizeof(int)) { const SSize_t n1 = PerlLIO_read(pp[0], (void*)(((char*)&errkid)+n), (sizeof(int)) - n); if (n1 <= 0) break; n += n1; } PerlLIO_close(pp[0]); did_pipes = 0; if (n) { /* Error */ int pid2, status; PerlLIO_close(p[This]); if (n != sizeof(int)) Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n); do { pid2 = wait4pid(pid, &status, 0); } while (pid2 == -1 && errno == EINTR); errno = errkid; /* Propagate errno from kid */ return NULL; } } if (did_pipes) PerlLIO_close(pp[0]); return PerlIO_fdopen(p[This], mode); #else # if defined(OS2) /* Same, without fork()ing and all extra overhead... */ return my_syspopen4(aTHX_ NULL, mode, n, args); # elif defined(WIN32) return win32_popenlist(mode, n, args); # else Perl_croak(aTHX_ "List form of piped open not implemented"); return (PerlIO *) NULL; # endif #endif } /* VMS' my_popen() is in VMS.c, same with OS/2 and AmigaOS 4. */ #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__) PerlIO * Perl_my_popen(pTHX_ const char *cmd, const char *mode) { int p[2]; I32 This, that; Pid_t pid; SV *sv; const I32 doexec = !(*cmd == '-' && cmd[1] == '\0'); I32 did_pipes = 0; int pp[2]; PERL_ARGS_ASSERT_MY_POPEN; PERL_FLUSHALL_FOR_CHILD; #ifdef OS2 if (doexec) { return my_syspopen(aTHX_ cmd,mode); } #endif This = (*mode == 'w'); that = !This; if (doexec && TAINTING_get) { taint_env(); taint_proper("Insecure %s%s", "EXEC"); } if (PerlProc_pipe_cloexec(p) < 0) return NULL; if (doexec && PerlProc_pipe_cloexec(pp) >= 0) did_pipes = 1; while ((pid = PerlProc_fork()) < 0) { if (errno != EAGAIN) { PerlLIO_close(p[This]); PerlLIO_close(p[that]); if (did_pipes) { PerlLIO_close(pp[0]); PerlLIO_close(pp[1]); } if (!doexec) Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno)); return NULL; } Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds"); sleep(5); } if (pid == 0) { #undef THIS #undef THAT #define THIS that #define THAT This if (did_pipes) PerlLIO_close(pp[0]); if (p[THIS] != (*mode == 'r')) { PerlLIO_dup2(p[THIS], *mode == 'r'); PerlLIO_close(p[THIS]); if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */ PerlLIO_close(p[THAT]); } else PerlLIO_close(p[THAT]); #ifndef OS2 if (doexec) { #if !defined(HAS_FCNTL) || !defined(F_SETFD) #ifndef NOFILE #define NOFILE 20 #endif { int fd; for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) if (fd != pp[1]) PerlLIO_close(fd); } #endif /* may or may not use the shell */ do_exec3(cmd, pp[1], did_pipes); PerlProc__exit(1); } #endif /* defined OS2 */ #ifdef PERLIO_USING_CRLF /* Since we circumvent IO layers when we manipulate low-level filedescriptors directly, need to manually switch to the default, binary, low-level mode; see PerlIOBuf_open(). */ PerlLIO_setmode((*mode == 'r'), O_BINARY); #endif PL_forkprocess = 0; #ifdef PERL_USES_PL_PIDSTATUS hv_clear(PL_pidstatus); /* we have no children */ #endif return NULL; #undef THIS #undef THAT } if (did_pipes) PerlLIO_close(pp[1]); if (p[that] < p[This]) { PerlLIO_dup2_cloexec(p[This], p[that]); PerlLIO_close(p[This]); p[This] = p[that]; } else PerlLIO_close(p[that]); sv = *av_fetch(PL_fdpid,p[This],TRUE); SvUPGRADE(sv,SVt_IV); SvIV_set(sv, pid); PL_forkprocess = pid; if (did_pipes && pid > 0) { int errkid; unsigned n = 0; while (n < sizeof(int)) { const SSize_t n1 = PerlLIO_read(pp[0], (void*)(((char*)&errkid)+n), (sizeof(int)) - n); if (n1 <= 0) break; n += n1; } PerlLIO_close(pp[0]); did_pipes = 0; if (n) { /* Error */ int pid2, status; PerlLIO_close(p[This]); if (n != sizeof(int)) Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n); do { pid2 = wait4pid(pid, &status, 0); } while (pid2 == -1 && errno == EINTR); errno = errkid; /* Propagate errno from kid */ return NULL; } } if (did_pipes) PerlLIO_close(pp[0]); return PerlIO_fdopen(p[This], mode); } #elif defined(DJGPP) FILE *djgpp_popen(); PerlIO * Perl_my_popen(pTHX_ const char *cmd, const char *mode) { PERL_FLUSHALL_FOR_CHILD; /* Call system's popen() to get a FILE *, then import it. used 0 for 2nd parameter to PerlIO_importFILE; apparently not used */ return PerlIO_importFILE(djgpp_popen(cmd, mode), 0); } #elif defined(__LIBCATAMOUNT__) PerlIO * Perl_my_popen(pTHX_ const char *cmd, const char *mode) { return NULL; } #endif /* !DOSISH */ /* this is called in parent before the fork() */ void Perl_atfork_lock(void) #if defined(USE_ITHREADS) # ifdef USE_PERLIO PERL_TSA_ACQUIRE(PL_perlio_mutex) # endif # ifdef MYMALLOC PERL_TSA_ACQUIRE(PL_malloc_mutex) # endif PERL_TSA_ACQUIRE(PL_op_mutex) #endif { #if defined(USE_ITHREADS) dVAR; /* locks must be held in locking order (if any) */ # ifdef USE_PERLIO MUTEX_LOCK(&PL_perlio_mutex); # endif # ifdef MYMALLOC MUTEX_LOCK(&PL_malloc_mutex); # endif OP_REFCNT_LOCK; #endif } /* this is called in both parent and child after the fork() */ void Perl_atfork_unlock(void) #if defined(USE_ITHREADS) # ifdef USE_PERLIO PERL_TSA_RELEASE(PL_perlio_mutex) # endif # ifdef MYMALLOC PERL_TSA_RELEASE(PL_malloc_mutex) # endif PERL_TSA_RELEASE(PL_op_mutex) #endif { #if defined(USE_ITHREADS) dVAR; /* locks must be released in same order as in atfork_lock() */ # ifdef USE_PERLIO MUTEX_UNLOCK(&PL_perlio_mutex); # endif # ifdef MYMALLOC MUTEX_UNLOCK(&PL_malloc_mutex); # endif OP_REFCNT_UNLOCK; #endif } Pid_t Perl_my_fork(void) { #if defined(HAS_FORK) Pid_t pid; #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK) atfork_lock(); pid = fork(); atfork_unlock(); #else /* atfork_lock() and atfork_unlock() are installed as pthread_atfork() * handlers elsewhere in the code */ pid = fork(); #endif return pid; #elif defined(__amigaos4__) return amigaos_fork(); #else /* this "canna happen" since nothing should be calling here if !HAS_FORK */ Perl_croak_nocontext("fork() not available"); return 0; #endif /* HAS_FORK */ } #ifndef HAS_DUP2 int dup2(int oldfd, int newfd) { #if defined(HAS_FCNTL) && defined(F_DUPFD) if (oldfd == newfd) return oldfd; PerlLIO_close(newfd); return fcntl(oldfd, F_DUPFD, newfd); #else #define DUP2_MAX_FDS 256 int fdtmp[DUP2_MAX_FDS]; I32 fdx = 0; int fd; if (oldfd == newfd) return oldfd; PerlLIO_close(newfd); /* good enough for low fd's... */ while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) { if (fdx >= DUP2_MAX_FDS) { PerlLIO_close(fd); fd = -1; break; } fdtmp[fdx++] = fd; } while (fdx > 0) PerlLIO_close(fdtmp[--fdx]); return fd; #endif } #endif #ifndef PERL_MICRO #ifdef HAS_SIGACTION Sighandler_t Perl_rsignal(pTHX_ int signo, Sighandler_t handler) { struct sigaction act, oact; #ifdef USE_ITHREADS dVAR; /* only "parent" interpreter can diddle signals */ if (PL_curinterp != aTHX) return (Sighandler_t) SIG_ERR; #endif act.sa_handler = (void(*)(int))handler; sigemptyset(&act.sa_mask); act.sa_flags = 0; #ifdef SA_RESTART if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */ #endif #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */ if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN) act.sa_flags |= SA_NOCLDWAIT; #endif if (sigaction(signo, &act, &oact) == -1) return (Sighandler_t) SIG_ERR; else return (Sighandler_t) oact.sa_handler; } Sighandler_t Perl_rsignal_state(pTHX_ int signo) { struct sigaction oact; PERL_UNUSED_CONTEXT; if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1) return (Sighandler_t) SIG_ERR; else return (Sighandler_t) oact.sa_handler; } int Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save) { #ifdef USE_ITHREADS dVAR; #endif struct sigaction act; PERL_ARGS_ASSERT_RSIGNAL_SAVE; #ifdef USE_ITHREADS /* only "parent" interpreter can diddle signals */ if (PL_curinterp != aTHX) return -1; #endif act.sa_handler = (void(*)(int))handler; sigemptyset(&act.sa_mask); act.sa_flags = 0; #ifdef SA_RESTART if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */ #endif #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */ if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN) act.sa_flags |= SA_NOCLDWAIT; #endif return sigaction(signo, &act, save); } int Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save) { #ifdef USE_ITHREADS dVAR; #endif PERL_UNUSED_CONTEXT; #ifdef USE_ITHREADS /* only "parent" interpreter can diddle signals */ if (PL_curinterp != aTHX) return -1; #endif return sigaction(signo, save, (struct sigaction *)NULL); } #else /* !HAS_SIGACTION */ Sighandler_t Perl_rsignal(pTHX_ int signo, Sighandler_t handler) { #if defined(USE_ITHREADS) && !defined(WIN32) /* only "parent" interpreter can diddle signals */ if (PL_curinterp != aTHX) return (Sighandler_t) SIG_ERR; #endif return PerlProc_signal(signo, handler); } static Signal_t sig_trap(int signo) { dVAR; PL_sig_trapped++; } Sighandler_t Perl_rsignal_state(pTHX_ int signo) { dVAR; Sighandler_t oldsig; #if defined(USE_ITHREADS) && !defined(WIN32) /* only "parent" interpreter can diddle signals */ if (PL_curinterp != aTHX) return (Sighandler_t) SIG_ERR; #endif PL_sig_trapped = 0; oldsig = PerlProc_signal(signo, sig_trap); PerlProc_signal(signo, oldsig); if (PL_sig_trapped) PerlProc_kill(PerlProc_getpid(), signo); return oldsig; } int Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save) { #if defined(USE_ITHREADS) && !defined(WIN32) /* only "parent" interpreter can diddle signals */ if (PL_curinterp != aTHX) return -1; #endif *save = PerlProc_signal(signo, handler); return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0; } int Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save) { #if defined(USE_ITHREADS) && !defined(WIN32) /* only "parent" interpreter can diddle signals */ if (PL_curinterp != aTHX) return -1; #endif return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0; } #endif /* !HAS_SIGACTION */ #endif /* !PERL_MICRO */ /* VMS' my_pclose() is in VMS.c; same with OS/2 */ #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__) I32 Perl_my_pclose(pTHX_ PerlIO *ptr) { int status; SV **svp; Pid_t pid; Pid_t pid2 = 0; bool close_failed; dSAVEDERRNO; const int fd = PerlIO_fileno(ptr); bool should_wait; svp = av_fetch(PL_fdpid,fd,TRUE); pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1; SvREFCNT_dec(*svp); *svp = NULL; #if defined(USE_PERLIO) /* Find out whether the refcount is low enough for us to wait for the child proc without blocking. */ should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0; #else should_wait = pid > 0; #endif #ifdef OS2 if (pid == -1) { /* Opened by popen. */ return my_syspclose(ptr); } #endif close_failed = (PerlIO_close(ptr) == EOF); SAVE_ERRNO; if (should_wait) do { pid2 = wait4pid(pid, &status, 0); } while (pid2 == -1 && errno == EINTR); if (close_failed) { RESTORE_ERRNO; return -1; } return( should_wait ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status) : 0 ); } #elif defined(__LIBCATAMOUNT__) I32 Perl_my_pclose(pTHX_ PerlIO *ptr) { return -1; } #endif /* !DOSISH */ #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__) I32 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags) { I32 result = 0; PERL_ARGS_ASSERT_WAIT4PID; #ifdef PERL_USES_PL_PIDSTATUS if (!pid) { /* PERL_USES_PL_PIDSTATUS is only defined when neither waitpid() nor wait4() is available, or on OS/2, which doesn't appear to support waiting for a progress group member, so we can only treat a 0 pid as an unknown child. */ errno = ECHILD; return -1; } { if (pid > 0) { /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the pid, rather than a string form. */ SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE); if (svp && *svp != &PL_sv_undef) { *statusp = SvIVX(*svp); (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t), G_DISCARD); return pid; } } else { HE *entry; hv_iterinit(PL_pidstatus); if ((entry = hv_iternext(PL_pidstatus))) { SV * const sv = hv_iterval(PL_pidstatus,entry); I32 len; const char * const spid = hv_iterkey(entry,&len); assert (len == sizeof(Pid_t)); memcpy((char *)&pid, spid, len); *statusp = SvIVX(sv); /* The hash iterator is currently on this entry, so simply calling hv_delete would trigger the lazy delete, which on aggregate does more work, because next call to hv_iterinit() would spot the flag, and have to call the delete routine, while in the meantime any new entries can't re-use that memory. */ hv_iterinit(PL_pidstatus); (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD); return pid; } } } #endif #ifdef HAS_WAITPID # ifdef HAS_WAITPID_RUNTIME if (!HAS_WAITPID_RUNTIME) goto hard_way; # endif result = PerlProc_waitpid(pid,statusp,flags); goto finish; #endif #if !defined(HAS_WAITPID) && defined(HAS_WAIT4) result = wait4(pid,statusp,flags,NULL); goto finish; #endif #ifdef PERL_USES_PL_PIDSTATUS #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME) hard_way: #endif { if (flags) Perl_croak(aTHX_ "Can't do waitpid with flags"); else { while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0) pidgone(result,*statusp); if (result < 0) *statusp = -1; } } #endif #if defined(HAS_WAITPID) || defined(HAS_WAIT4) finish: #endif if (result < 0 && errno == EINTR) { PERL_ASYNC_CHECK(); errno = EINTR; /* reset in case a signal handler changed $! */ } return result; } #endif /* !DOSISH || OS2 || WIN32 || NETWARE */ #ifdef PERL_USES_PL_PIDSTATUS void S_pidgone(pTHX_ Pid_t pid, int status) { SV *sv; sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE); SvUPGRADE(sv,SVt_IV); SvIV_set(sv, status); return; } #endif #if defined(OS2) int pclose(); #ifdef HAS_FORK int /* Cannot prototype with I32 in os2ish.h. */ my_syspclose(PerlIO *ptr) #else I32 Perl_my_pclose(pTHX_ PerlIO *ptr) #endif { /* Needs work for PerlIO ! */ FILE * const f = PerlIO_findFILE(ptr); const I32 result = pclose(f); PerlIO_releaseFILE(ptr,f); return result; } #endif #if defined(DJGPP) int djgpp_pclose(); I32 Perl_my_pclose(pTHX_ PerlIO *ptr) { /* Needs work for PerlIO ! */ FILE * const f = PerlIO_findFILE(ptr); I32 result = djgpp_pclose(f); result = (result << 8) & 0xff00; PerlIO_releaseFILE(ptr,f); return result; } #endif #define PERL_REPEATCPY_LINEAR 4 void Perl_repeatcpy(char *to, const char *from, I32 len, IV count) { PERL_ARGS_ASSERT_REPEATCPY; assert(len >= 0); if (count < 0) croak_memory_wrap(); if (len == 1) memset(to, *from, count); else if (count) { char *p = to; IV items, linear, half; linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR; for (items = 0; items < linear; ++items) { const char *q = from; IV todo; for (todo = len; todo > 0; todo--) *p++ = *q++; } half = count / 2; while (items <= half) { IV size = items * len; memcpy(p, to, size); p += size; items *= 2; } if (count > items) memcpy(p, to, (count - items) * len); } } #ifndef HAS_RENAME I32 Perl_same_dirent(pTHX_ const char *a, const char *b) { char *fa = strrchr(a,'/'); char *fb = strrchr(b,'/'); Stat_t tmpstatbuf1; Stat_t tmpstatbuf2; SV * const tmpsv = sv_newmortal(); PERL_ARGS_ASSERT_SAME_DIRENT; if (fa) fa++; else fa = a; if (fb) fb++; else fb = b; if (strNE(a,b)) return FALSE; if (fa == a) sv_setpvs(tmpsv, "."); else sv_setpvn(tmpsv, a, fa - a); if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0) return FALSE; if (fb == b) sv_setpvs(tmpsv, "."); else sv_setpvn(tmpsv, b, fb - b); if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0) return FALSE; return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev && tmpstatbuf1.st_ino == tmpstatbuf2.st_ino; } #endif /* !HAS_RENAME */ char* Perl_find_script(pTHX_ const char *scriptname, bool dosearch, const char *const *const search_ext, I32 flags) { const char *xfound = NULL; char *xfailed = NULL; char tmpbuf[MAXPATHLEN]; char *s; I32 len = 0; int retval; char *bufend; #if defined(DOSISH) && !defined(OS2) # define SEARCH_EXTS ".bat", ".cmd", NULL # define MAX_EXT_LEN 4 #endif #ifdef OS2 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL # define MAX_EXT_LEN 4 #endif #ifdef VMS # define SEARCH_EXTS ".pl", ".com", NULL # define MAX_EXT_LEN 4 #endif /* additional extensions to try in each dir if scriptname not found */ #ifdef SEARCH_EXTS static const char *const exts[] = { SEARCH_EXTS }; const char *const *const ext = search_ext ? search_ext : exts; int extidx = 0, i = 0; const char *curext = NULL; #else PERL_UNUSED_ARG(search_ext); # define MAX_EXT_LEN 0 #endif PERL_ARGS_ASSERT_FIND_SCRIPT; /* * If dosearch is true and if scriptname does not contain path * delimiters, search the PATH for scriptname. * * If SEARCH_EXTS is also defined, will look for each * scriptname{SEARCH_EXTS} whenever scriptname is not found * while searching the PATH. * * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search * proceeds as follows: * If DOSISH or VMSISH: * + look for ./scriptname{,.foo,.bar} * + search the PATH for scriptname{,.foo,.bar} * * If !DOSISH: * + look *only* in the PATH for scriptname{,.foo,.bar} (note * this will not look in '.' if it's not in the PATH) */ tmpbuf[0] = '\0'; #ifdef VMS # ifdef ALWAYS_DEFTYPES len = strlen(scriptname); if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') { int idx = 0, deftypes = 1; bool seen_dot = 1; const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL); # else if (dosearch) { int idx = 0, deftypes = 1; bool seen_dot = 1; const int hasdir = (strpbrk(scriptname,":[</") != NULL); # endif /* The first time through, just add SEARCH_EXTS to whatever we * already have, so we can check for default file types. */ while (deftypes || (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) ) { Stat_t statbuf; if (deftypes) { deftypes = 0; *tmpbuf = '\0'; } if ((strlen(tmpbuf) + strlen(scriptname) + MAX_EXT_LEN) >= sizeof tmpbuf) continue; /* don't search dir with too-long name */ my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf)); #else /* !VMS */ #ifdef DOSISH if (strEQ(scriptname, "-")) dosearch = 0; if (dosearch) { /* Look in '.' first. */ const char *cur = scriptname; #ifdef SEARCH_EXTS if ((curext = strrchr(scriptname,'.'))) /* possible current ext */ while (ext[i]) if (strEQ(ext[i++],curext)) { extidx = -1; /* already has an ext */ break; } do { #endif DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",cur)); { Stat_t statbuf; if (PerlLIO_stat(cur,&statbuf) >= 0 && !S_ISDIR(statbuf.st_mode)) { dosearch = 0; scriptname = cur; #ifdef SEARCH_EXTS break; #endif } } #ifdef SEARCH_EXTS if (cur == scriptname) { len = strlen(scriptname); if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf)) break; my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf)); cur = tmpbuf; } } while (extidx >= 0 && ext[extidx] /* try an extension? */ && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)); #endif } #endif if (dosearch && !strchr(scriptname, '/') #ifdef DOSISH && !strchr(scriptname, '\\') #endif && (s = PerlEnv_getenv("PATH"))) { bool seen_dot = 0; bufend = s + strlen(s); while (s < bufend) { Stat_t statbuf; # ifdef DOSISH for (len = 0; *s && *s != ';'; len++, s++) { if (len < sizeof tmpbuf) tmpbuf[len] = *s; } if (len < sizeof tmpbuf) tmpbuf[len] = '\0'; # else s = delimcpy_no_escape(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend, ':', &len); # endif if (s < bufend) s++; if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf) continue; /* don't search dir with too-long name */ if (len # ifdef DOSISH && tmpbuf[len - 1] != '/' && tmpbuf[len - 1] != '\\' # endif ) tmpbuf[len++] = '/'; if (len == 2 && tmpbuf[0] == '.') seen_dot = 1; (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len); #endif /* !VMS */ #ifdef SEARCH_EXTS len = strlen(tmpbuf); if (extidx > 0) /* reset after previous loop */ extidx = 0; do { #endif DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf)); retval = PerlLIO_stat(tmpbuf,&statbuf); if (S_ISDIR(statbuf.st_mode)) { retval = -1; } #ifdef SEARCH_EXTS } while ( retval < 0 /* not there */ && extidx>=0 && ext[extidx] /* try an extension? */ && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len) ); #endif if (retval < 0) continue; if (S_ISREG(statbuf.st_mode) && cando(S_IRUSR,TRUE,&statbuf) #if !defined(DOSISH) && cando(S_IXUSR,TRUE,&statbuf) #endif ) { xfound = tmpbuf; /* bingo! */ break; } if (!xfailed) xfailed = savepv(tmpbuf); } #ifndef DOSISH { Stat_t statbuf; if (!xfound && !seen_dot && !xfailed && (PerlLIO_stat(scriptname,&statbuf) < 0 || S_ISDIR(statbuf.st_mode))) #endif seen_dot = 1; /* Disable message. */ #ifndef DOSISH } #endif if (!xfound) { if (flags & 1) { /* do or die? */ /* diag_listed_as: Can't execute %s */ Perl_croak(aTHX_ "Can't %s %s%s%s", (xfailed ? "execute" : "find"), (xfailed ? xfailed : scriptname), (xfailed ? "" : " on PATH"), (xfailed || seen_dot) ? "" : ", '.' not in PATH"); } scriptname = NULL; } Safefree(xfailed); scriptname = xfound; } return (scriptname ? savepv(scriptname) : NULL); } #ifndef PERL_GET_CONTEXT_DEFINED void * Perl_get_context(void) { #if defined(USE_ITHREADS) dVAR; # ifdef OLD_PTHREADS_API pthread_addr_t t; int error = pthread_getspecific(PL_thr_key, &t) if (error) Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error); return (void*)t; # elif defined(I_MACH_CTHREADS) return (void*)cthread_data(cthread_self()); # else return (void*)PTHREAD_GETSPECIFIC(PL_thr_key); # endif #else return (void*)NULL; #endif } void Perl_set_context(void *t) { #if defined(USE_ITHREADS) dVAR; #endif PERL_ARGS_ASSERT_SET_CONTEXT; #if defined(USE_ITHREADS) # ifdef I_MACH_CTHREADS cthread_set_data(cthread_self(), t); # else { const int error = pthread_setspecific(PL_thr_key, t); if (error) Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error); } # endif #else PERL_UNUSED_ARG(t); #endif } #endif /* !PERL_GET_CONTEXT_DEFINED */ #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE) struct perl_vars * Perl_GetVars(pTHX) { PERL_UNUSED_CONTEXT; return &PL_Vars; } #endif char ** Perl_get_op_names(pTHX) { PERL_UNUSED_CONTEXT; return (char **)PL_op_name; } char ** Perl_get_op_descs(pTHX) { PERL_UNUSED_CONTEXT; return (char **)PL_op_desc; } const char * Perl_get_no_modify(pTHX) { PERL_UNUSED_CONTEXT; return PL_no_modify; } U32 * Perl_get_opargs(pTHX) { PERL_UNUSED_CONTEXT; return (U32 *)PL_opargs; } PPADDR_t* Perl_get_ppaddr(pTHX) { dVAR; PERL_UNUSED_CONTEXT; return (PPADDR_t*)PL_ppaddr; } #ifndef HAS_GETENV_LEN char * Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len) { char * const env_trans = PerlEnv_getenv(env_elem); PERL_UNUSED_CONTEXT; PERL_ARGS_ASSERT_GETENV_LEN; if (env_trans) *len = strlen(env_trans); return env_trans; } #endif MGVTBL* Perl_get_vtbl(pTHX_ int vtbl_id) { PERL_UNUSED_CONTEXT; return (vtbl_id < 0 || vtbl_id >= magic_vtable_max) ? NULL : (MGVTBL*)PL_magic_vtables + vtbl_id; } I32 Perl_my_fflush_all(pTHX) { #if defined(USE_PERLIO) || defined(FFLUSH_NULL) return PerlIO_flush(NULL); #else # if defined(HAS__FWALK) extern int fflush(FILE *); /* undocumented, unprototyped, but very useful BSDism */ extern void _fwalk(int (*)(FILE *)); _fwalk(&fflush); return 0; # else # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY) long open_max = -1; # ifdef PERL_FFLUSH_ALL_FOPEN_MAX open_max = PERL_FFLUSH_ALL_FOPEN_MAX; # elif defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX) open_max = sysconf(_SC_OPEN_MAX); # elif defined(FOPEN_MAX) open_max = FOPEN_MAX; # elif defined(OPEN_MAX) open_max = OPEN_MAX; # elif defined(_NFILE) open_max = _NFILE; # endif if (open_max > 0) { long i; for (i = 0; i < open_max; i++) if (STDIO_STREAM_ARRAY[i]._file >= 0 && STDIO_STREAM_ARRAY[i]._file < open_max && STDIO_STREAM_ARRAY[i]._flag) PerlIO_flush(&STDIO_STREAM_ARRAY[i]); return 0; } # endif SETERRNO(EBADF,RMS_IFI); return EOF; # endif #endif } void Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have) { if (ckWARN(WARN_IO)) { HEK * const name = gv && (isGV_with_GP(gv)) ? GvENAME_HEK((gv)) : NULL; const char * const direction = have == '>' ? "out" : "in"; if (name && HEK_LEN(name)) Perl_warner(aTHX_ packWARN(WARN_IO), "Filehandle %" HEKf " opened only for %sput", HEKfARG(name), direction); else Perl_warner(aTHX_ packWARN(WARN_IO), "Filehandle opened only for %sput", direction); } } void Perl_report_evil_fh(pTHX_ const GV *gv) { const IO *io = gv ? GvIO(gv) : NULL; const PERL_BITFIELD16 op = PL_op->op_type; const char *vile; I32 warn_type; if (io && IoTYPE(io) == IoTYPE_CLOSED) { vile = "closed"; warn_type = WARN_CLOSED; } else { vile = "unopened"; warn_type = WARN_UNOPENED; } if (ckWARN(warn_type)) { SV * const name = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ? sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL; const char * const pars = (const char *)(OP_IS_FILETEST(op) ? "" : "()"); const char * const func = (const char *) (op == OP_READLINE || op == OP_RCATLINE ? "readline" : /* "<HANDLE>" not nice */ op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */ PL_op_desc[op]); const char * const type = (const char *) (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET) ? "socket" : "filehandle"); const bool have_name = name && SvCUR(name); Perl_warner(aTHX_ packWARN(warn_type), "%s%s on %s %s%s%" SVf, func, pars, vile, type, have_name ? " " : "", SVfARG(have_name ? name : &PL_sv_no)); if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP)) Perl_warner( aTHX_ packWARN(warn_type), "\t(Are you trying to call %s%s on dirhandle%s%" SVf "?)\n", func, pars, have_name ? " " : "", SVfARG(have_name ? name : &PL_sv_no) ); } } /* To workaround core dumps from the uninitialised tm_zone we get the * system to give us a reasonable struct to copy. This fix means that * strftime uses the tm_zone and tm_gmtoff values returned by * localtime(time()). That should give the desired result most of the * time. But probably not always! * * This does not address tzname aspects of NETaa14816. * */ #ifdef __GLIBC__ # ifndef STRUCT_TM_HASZONE # define STRUCT_TM_HASZONE # endif #endif #ifdef STRUCT_TM_HASZONE /* Backward compat */ # ifndef HAS_TM_TM_ZONE # define HAS_TM_TM_ZONE # endif #endif void Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */ { #ifdef HAS_TM_TM_ZONE Time_t now; const struct tm* my_tm; PERL_UNUSED_CONTEXT; PERL_ARGS_ASSERT_INIT_TM; (void)time(&now); my_tm = localtime(&now); if (my_tm) Copy(my_tm, ptm, 1, struct tm); #else PERL_UNUSED_CONTEXT; PERL_ARGS_ASSERT_INIT_TM; PERL_UNUSED_ARG(ptm); #endif } /* * mini_mktime - normalise struct tm values without the localtime() * semantics (and overhead) of mktime(). */ void Perl_mini_mktime(struct tm *ptm) { int yearday; int secs; int month, mday, year, jday; int odd_cent, odd_year; PERL_ARGS_ASSERT_MINI_MKTIME; #define DAYS_PER_YEAR 365 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1) #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1) #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1) #define SECS_PER_HOUR (60*60) #define SECS_PER_DAY (24*SECS_PER_HOUR) /* parentheses deliberately absent on these two, otherwise they don't work */ #define MONTH_TO_DAYS 153/5 #define DAYS_TO_MONTH 5/153 /* offset to bias by March (month 4) 1st between month/mday & year finding */ #define YEAR_ADJUST (4*MONTH_TO_DAYS+1) /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */ #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */ /* * Year/day algorithm notes: * * With a suitable offset for numeric value of the month, one can find * an offset into the year by considering months to have 30.6 (153/5) days, * using integer arithmetic (i.e., with truncation). To avoid too much * messing about with leap days, we consider January and February to be * the 13th and 14th month of the previous year. After that transformation, * we need the month index we use to be high by 1 from 'normal human' usage, * so the month index values we use run from 4 through 15. * * Given that, and the rules for the Gregorian calendar (leap years are those * divisible by 4 unless also divisible by 100, when they must be divisible * by 400 instead), we can simply calculate the number of days since some * arbitrary 'beginning of time' by futzing with the (adjusted) year number, * the days we derive from our month index, and adding in the day of the * month. The value used here is not adjusted for the actual origin which * it normally would use (1 January A.D. 1), since we're not exposing it. * We're only building the value so we can turn around and get the * normalised values for the year, month, day-of-month, and day-of-year. * * For going backward, we need to bias the value we're using so that we find * the right year value. (Basically, we don't want the contribution of * March 1st to the number to apply while deriving the year). Having done * that, we 'count up' the contribution to the year number by accounting for * full quadracenturies (400-year periods) with their extra leap days, plus * the contribution from full centuries (to avoid counting in the lost leap * days), plus the contribution from full quad-years (to count in the normal * leap days), plus the leftover contribution from any non-leap years. * At this point, if we were working with an actual leap day, we'll have 0 * days left over. This is also true for March 1st, however. So, we have * to special-case that result, and (earlier) keep track of the 'odd' * century and year contributions. If we got 4 extra centuries in a qcent, * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb. * Otherwise, we add back in the earlier bias we removed (the 123 from * figuring in March 1st), find the month index (integer division by 30.6), * and the remainder is the day-of-month. We then have to convert back to * 'real' months (including fixing January and February from being 14/15 in * the previous year to being in the proper year). After that, to get * tm_yday, we work with the normalised year and get a new yearday value for * January 1st, which we subtract from the yearday value we had earlier, * representing the date we've re-built. This is done from January 1 * because tm_yday is 0-origin. * * Since POSIX time routines are only guaranteed to work for times since the * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm * applies Gregorian calendar rules even to dates before the 16th century * doesn't bother me. Besides, you'd need cultural context for a given * date to know whether it was Julian or Gregorian calendar, and that's * outside the scope for this routine. Since we convert back based on the * same rules we used to build the yearday, you'll only get strange results * for input which needed normalising, or for the 'odd' century years which * were leap years in the Julian calendar but not in the Gregorian one. * I can live with that. * * This algorithm also fails to handle years before A.D. 1 gracefully, but * that's still outside the scope for POSIX time manipulation, so I don't * care. * * - lwall */ year = 1900 + ptm->tm_year; month = ptm->tm_mon; mday = ptm->tm_mday; jday = 0; if (month >= 2) month+=2; else month+=14, year--; yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400; yearday += month*MONTH_TO_DAYS + mday + jday; /* * Note that we don't know when leap-seconds were or will be, * so we have to trust the user if we get something which looks * like a sensible leap-second. Wild values for seconds will * be rationalised, however. */ if ((unsigned) ptm->tm_sec <= 60) { secs = 0; } else { secs = ptm->tm_sec; ptm->tm_sec = 0; } secs += 60 * ptm->tm_min; secs += SECS_PER_HOUR * ptm->tm_hour; if (secs < 0) { if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) { /* got negative remainder, but need positive time */ /* back off an extra day to compensate */ yearday += (secs/SECS_PER_DAY)-1; secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1); } else { yearday += (secs/SECS_PER_DAY); secs -= SECS_PER_DAY * (secs/SECS_PER_DAY); } } else if (secs >= SECS_PER_DAY) { yearday += (secs/SECS_PER_DAY); secs %= SECS_PER_DAY; } ptm->tm_hour = secs/SECS_PER_HOUR; secs %= SECS_PER_HOUR; ptm->tm_min = secs/60; secs %= 60; ptm->tm_sec += secs; /* done with time of day effects */ /* * The algorithm for yearday has (so far) left it high by 428. * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to * bias it by 123 while trying to figure out what year it * really represents. Even with this tweak, the reverse * translation fails for years before A.D. 0001. * It would still fail for Feb 29, but we catch that one below. */ jday = yearday; /* save for later fixup vis-a-vis Jan 1 */ yearday -= YEAR_ADJUST; year = (yearday / DAYS_PER_QCENT) * 400; yearday %= DAYS_PER_QCENT; odd_cent = yearday / DAYS_PER_CENT; year += odd_cent * 100; yearday %= DAYS_PER_CENT; year += (yearday / DAYS_PER_QYEAR) * 4; yearday %= DAYS_PER_QYEAR; odd_year = yearday / DAYS_PER_YEAR; year += odd_year; yearday %= DAYS_PER_YEAR; if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */ month = 1; yearday = 29; } else { yearday += YEAR_ADJUST; /* recover March 1st crock */ month = yearday*DAYS_TO_MONTH; yearday -= month*MONTH_TO_DAYS; /* recover other leap-year adjustment */ if (month > 13) { month-=14; year++; } else { month-=2; } } ptm->tm_year = year - 1900; if (yearday) { ptm->tm_mday = yearday; ptm->tm_mon = month; } else { ptm->tm_mday = 31; ptm->tm_mon = month - 1; } /* re-build yearday based on Jan 1 to get tm_yday */ year--; yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400; yearday += 14*MONTH_TO_DAYS + 1; ptm->tm_yday = jday - yearday; ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7; } char * Perl_my_strftime(pTHX_ const char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst) { #ifdef HAS_STRFTIME /* strftime(), but with a different API so that the return value is a pointer * to the formatted result (which MUST be arranged to be FREED BY THE * CALLER). This allows this function to increase the buffer size as needed, * so that the caller doesn't have to worry about that. * * Note that yday and wday effectively are ignored by this function, as * mini_mktime() overwrites them */ char *buf; int buflen; struct tm mytm; int len; PERL_ARGS_ASSERT_MY_STRFTIME; init_tm(&mytm); /* XXX workaround - see init_tm() above */ mytm.tm_sec = sec; mytm.tm_min = min; mytm.tm_hour = hour; mytm.tm_mday = mday; mytm.tm_mon = mon; mytm.tm_year = year; mytm.tm_wday = wday; mytm.tm_yday = yday; mytm.tm_isdst = isdst; mini_mktime(&mytm); /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */ #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE)) STMT_START { struct tm mytm2; mytm2 = mytm; mktime(&mytm2); #ifdef HAS_TM_TM_GMTOFF mytm.tm_gmtoff = mytm2.tm_gmtoff; #endif #ifdef HAS_TM_TM_ZONE mytm.tm_zone = mytm2.tm_zone; #endif } STMT_END; #endif buflen = 64; Newx(buf, buflen, char); GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* fmt checked by caller */ len = strftime(buf, buflen, fmt, &mytm); GCC_DIAG_RESTORE_STMT; /* ** The following is needed to handle to the situation where ** tmpbuf overflows. Basically we want to allocate a buffer ** and try repeatedly. The reason why it is so complicated ** is that getting a return value of 0 from strftime can indicate ** one of the following: ** 1. buffer overflowed, ** 2. illegal conversion specifier, or ** 3. the format string specifies nothing to be returned(not ** an error). This could be because format is an empty string ** or it specifies %p that yields an empty string in some locale. ** If there is a better way to make it portable, go ahead by ** all means. */ if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0')) return buf; else { /* Possibly buf overflowed - try again with a bigger buf */ const int fmtlen = strlen(fmt); int bufsize = fmtlen + buflen; Renew(buf, bufsize, char); while (buf) { GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* fmt checked by caller */ buflen = strftime(buf, bufsize, fmt, &mytm); GCC_DIAG_RESTORE_STMT; if (buflen > 0 && buflen < bufsize) break; /* heuristic to prevent out-of-memory errors */ if (bufsize > 100*fmtlen) { Safefree(buf); buf = NULL; break; } bufsize *= 2; Renew(buf, bufsize, char); } return buf; } #else Perl_croak(aTHX_ "panic: no strftime"); return NULL; #endif } #define SV_CWD_RETURN_UNDEF \ sv_set_undef(sv); \ return FALSE #define SV_CWD_ISDOT(dp) \ (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \ (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))) /* =head1 Miscellaneous Functions =for apidoc getcwd_sv Fill C<sv> with current working directory =cut */ /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars. * rewritten again by dougm, optimized for use with xs TARG, and to prefer * getcwd(3) if available * Comments from the original: * This is a faster version of getcwd. It's also more dangerous * because you might chdir out of a directory that you can't chdir * back into. */ int Perl_getcwd_sv(pTHX_ SV *sv) { #ifndef PERL_MICRO SvTAINTED_on(sv); PERL_ARGS_ASSERT_GETCWD_SV; #ifdef HAS_GETCWD { char buf[MAXPATHLEN]; /* Some getcwd()s automatically allocate a buffer of the given * size from the heap if they are given a NULL buffer pointer. * The problem is that this behaviour is not portable. */ if (getcwd(buf, sizeof(buf) - 1)) { sv_setpv(sv, buf); return TRUE; } else { SV_CWD_RETURN_UNDEF; } } #else Stat_t statbuf; int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino; int pathlen=0; Direntry_t *dp; SvUPGRADE(sv, SVt_PV); if (PerlLIO_lstat(".", &statbuf) < 0) { SV_CWD_RETURN_UNDEF; } orig_cdev = statbuf.st_dev; orig_cino = statbuf.st_ino; cdev = orig_cdev; cino = orig_cino; for (;;) { DIR *dir; int namelen; odev = cdev; oino = cino; if (PerlDir_chdir("..") < 0) { SV_CWD_RETURN_UNDEF; } if (PerlLIO_stat(".", &statbuf) < 0) { SV_CWD_RETURN_UNDEF; } cdev = statbuf.st_dev; cino = statbuf.st_ino; if (odev == cdev && oino == cino) { break; } if (!(dir = PerlDir_open("."))) { SV_CWD_RETURN_UNDEF; } while ((dp = PerlDir_read(dir)) != NULL) { #ifdef DIRNAMLEN namelen = dp->d_namlen; #else namelen = strlen(dp->d_name); #endif /* skip . and .. */ if (SV_CWD_ISDOT(dp)) { continue; } if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) { SV_CWD_RETURN_UNDEF; } tdev = statbuf.st_dev; tino = statbuf.st_ino; if (tino == oino && tdev == odev) { break; } } if (!dp) { SV_CWD_RETURN_UNDEF; } if (pathlen + namelen + 1 >= MAXPATHLEN) { SV_CWD_RETURN_UNDEF; } SvGROW(sv, pathlen + namelen + 1); if (pathlen) { /* shift down */ Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char); } /* prepend current directory to the front */ *SvPVX(sv) = '/'; Move(dp->d_name, SvPVX(sv)+1, namelen, char); pathlen += (namelen + 1); #ifdef VOID_CLOSEDIR PerlDir_close(dir); #else if (PerlDir_close(dir) < 0) { SV_CWD_RETURN_UNDEF; } #endif } if (pathlen) { SvCUR_set(sv, pathlen); *SvEND(sv) = '\0'; SvPOK_only(sv); if (PerlDir_chdir(SvPVX_const(sv)) < 0) { SV_CWD_RETURN_UNDEF; } } if (PerlLIO_stat(".", &statbuf) < 0) { SV_CWD_RETURN_UNDEF; } cdev = statbuf.st_dev; cino = statbuf.st_ino; if (cdev != orig_cdev || cino != orig_cino) { Perl_croak(aTHX_ "Unstable directory path, " "current directory changed unexpectedly"); } return TRUE; #endif #else return FALSE; #endif } #include "vutil.c" #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT) # define EMULATE_SOCKETPAIR_UDP #endif #ifdef EMULATE_SOCKETPAIR_UDP static int S_socketpair_udp (int fd[2]) { dTHX; /* Fake a datagram socketpair using UDP to localhost. */ int sockets[2] = {-1, -1}; struct sockaddr_in addresses[2]; int i; Sock_size_t size = sizeof(struct sockaddr_in); unsigned short port; int got; memset(&addresses, 0, sizeof(addresses)); i = 1; do { sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET); if (sockets[i] == -1) goto tidy_up_and_fail; addresses[i].sin_family = AF_INET; addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK); addresses[i].sin_port = 0; /* kernel choses port. */ if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i], sizeof(struct sockaddr_in)) == -1) goto tidy_up_and_fail; } while (i--); /* Now have 2 UDP sockets. Find out which port each is connected to, and for each connect the other socket to it. */ i = 1; do { if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i], &size) == -1) goto tidy_up_and_fail; if (size != sizeof(struct sockaddr_in)) goto abort_tidy_up_and_fail; /* !1 is 0, !0 is 1 */ if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i], sizeof(struct sockaddr_in)) == -1) goto tidy_up_and_fail; } while (i--); /* Now we have 2 sockets connected to each other. I don't trust some other process not to have already sent a packet to us (by random) so send a packet from each to the other. */ i = 1; do { /* I'm going to send my own port number. As a short. (Who knows if someone somewhere has sin_port as a bitfield and needs this routine. (I'm assuming crays have socketpair)) */ port = addresses[i].sin_port; got = PerlLIO_write(sockets[i], &port, sizeof(port)); if (got != sizeof(port)) { if (got == -1) goto tidy_up_and_fail; goto abort_tidy_up_and_fail; } } while (i--); /* Packets sent. I don't trust them to have arrived though. (As I understand it Solaris TCP stack is multithreaded. Non-blocking connect to localhost will use a second kernel thread. In 2.6 the first thread running the connect() returns before the second completes, so EINPROGRESS> In 2.7 the improved stack is faster and connect() returns 0. Poor programs have tripped up. One poor program's authors' had a 50-1 reverse stock split. Not sure how connected these were.) So I don't trust someone not to have an unpredictable UDP stack. */ { struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */ int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0]; fd_set rset; FD_ZERO(&rset); FD_SET((unsigned int)sockets[0], &rset); FD_SET((unsigned int)sockets[1], &rset); got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor); if (got != 2 || !FD_ISSET(sockets[0], &rset) || !FD_ISSET(sockets[1], &rset)) { /* I hope this is portable and appropriate. */ if (got == -1) goto tidy_up_and_fail; goto abort_tidy_up_and_fail; } } /* And the paranoia department even now doesn't trust it to have arrive (hence MSG_DONTWAIT). Or that what arrives was sent by us. */ { struct sockaddr_in readfrom; unsigned short buffer[2]; i = 1; do { #ifdef MSG_DONTWAIT got = PerlSock_recvfrom(sockets[i], (char *) &buffer, sizeof(buffer), MSG_DONTWAIT, (struct sockaddr *) &readfrom, &size); #else got = PerlSock_recvfrom(sockets[i], (char *) &buffer, sizeof(buffer), 0, (struct sockaddr *) &readfrom, &size); #endif if (got == -1) goto tidy_up_and_fail; if (got != sizeof(port) || size != sizeof(struct sockaddr_in) /* Check other socket sent us its port. */ || buffer[0] != (unsigned short) addresses[!i].sin_port /* Check kernel says we got the datagram from that socket */ || readfrom.sin_family != addresses[!i].sin_family || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr || readfrom.sin_port != addresses[!i].sin_port) goto abort_tidy_up_and_fail; } while (i--); } /* My caller (my_socketpair) has validated that this is non-NULL */ fd[0] = sockets[0]; fd[1] = sockets[1]; /* I hereby declare this connection open. May God bless all who cross her. */ return 0; abort_tidy_up_and_fail: errno = ECONNABORTED; tidy_up_and_fail: { dSAVE_ERRNO; if (sockets[0] != -1) PerlLIO_close(sockets[0]); if (sockets[1] != -1) PerlLIO_close(sockets[1]); RESTORE_ERRNO; return -1; } } #endif /* EMULATE_SOCKETPAIR_UDP */ #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) int Perl_my_socketpair (int family, int type, int protocol, int fd[2]) { /* Stevens says that family must be AF_LOCAL, protocol 0. I'm going to enforce that, then ignore it, and use TCP (or UDP). */ dTHXa(NULL); int listener = -1; int connector = -1; int acceptor = -1; struct sockaddr_in listen_addr; struct sockaddr_in connect_addr; Sock_size_t size; if (protocol #ifdef AF_UNIX || family != AF_UNIX #endif ) { errno = EAFNOSUPPORT; return -1; } if (!fd) { errno = EINVAL; return -1; } #ifdef SOCK_CLOEXEC type &= ~SOCK_CLOEXEC; #endif #ifdef EMULATE_SOCKETPAIR_UDP if (type == SOCK_DGRAM) return S_socketpair_udp(fd); #endif aTHXa(PERL_GET_THX); listener = PerlSock_socket(AF_INET, type, 0); if (listener == -1) return -1; memset(&listen_addr, 0, sizeof(listen_addr)); listen_addr.sin_family = AF_INET; listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); listen_addr.sin_port = 0; /* kernel choses port. */ if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr, sizeof(listen_addr)) == -1) goto tidy_up_and_fail; if (PerlSock_listen(listener, 1) == -1) goto tidy_up_and_fail; connector = PerlSock_socket(AF_INET, type, 0); if (connector == -1) goto tidy_up_and_fail; /* We want to find out the port number to connect to. */ size = sizeof(connect_addr); if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1) goto tidy_up_and_fail; if (size != sizeof(connect_addr)) goto abort_tidy_up_and_fail; if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr, sizeof(connect_addr)) == -1) goto tidy_up_and_fail; size = sizeof(listen_addr); acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr, &size); if (acceptor == -1) goto tidy_up_and_fail; if (size != sizeof(listen_addr)) goto abort_tidy_up_and_fail; PerlLIO_close(listener); /* Now check we are talking to ourself by matching port and host on the two sockets. */ if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1) goto tidy_up_and_fail; if (size != sizeof(connect_addr) || listen_addr.sin_family != connect_addr.sin_family || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr || listen_addr.sin_port != connect_addr.sin_port) { goto abort_tidy_up_and_fail; } fd[0] = connector; fd[1] = acceptor; return 0; abort_tidy_up_and_fail: #ifdef ECONNABORTED errno = ECONNABORTED; /* This would be the standard thing to do. */ #elif defined(ECONNREFUSED) errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */ #else errno = ETIMEDOUT; /* Desperation time. */ #endif tidy_up_and_fail: { dSAVE_ERRNO; if (listener != -1) PerlLIO_close(listener); if (connector != -1) PerlLIO_close(connector); if (acceptor != -1) PerlLIO_close(acceptor); RESTORE_ERRNO; return -1; } } #else /* In any case have a stub so that there's code corresponding * to the my_socketpair in embed.fnc. */ int Perl_my_socketpair (int family, int type, int protocol, int fd[2]) { #ifdef HAS_SOCKETPAIR return socketpair(family, type, protocol, fd); #else return -1; #endif } #endif /* =for apidoc sv_nosharing Dummy routine which "shares" an SV when there is no sharing module present. Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument. Exists to avoid test for a C<NULL> function pointer and because it could potentially warn under some level of strict-ness. =cut */ void Perl_sv_nosharing(pTHX_ SV *sv) { PERL_UNUSED_CONTEXT; PERL_UNUSED_ARG(sv); } /* =for apidoc sv_destroyable Dummy routine which reports that object can be destroyed when there is no sharing module present. It ignores its single SV argument, and returns 'true'. Exists to avoid test for a C<NULL> function pointer and because it could potentially warn under some level of strict-ness. =cut */ bool Perl_sv_destroyable(pTHX_ SV *sv) { PERL_UNUSED_CONTEXT; PERL_UNUSED_ARG(sv); return TRUE; } U32 Perl_parse_unicode_opts(pTHX_ const char **popt) { const char *p = *popt; U32 opt = 0; PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS; if (*p) { if (isDIGIT(*p)) { const char* endptr = p + strlen(p); UV uv; if (grok_atoUV(p, &uv, &endptr) && uv <= U32_MAX) { opt = (U32)uv; p = endptr; if (p && *p && *p != '\n' && *p != '\r') { if (isSPACE(*p)) goto the_end_of_the_opts_parser; else Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p); } } else { Perl_croak(aTHX_ "Invalid number '%s' for -C option.\n", p); } } else { for (; *p; p++) { switch (*p) { case PERL_UNICODE_STDIN: opt |= PERL_UNICODE_STDIN_FLAG; break; case PERL_UNICODE_STDOUT: opt |= PERL_UNICODE_STDOUT_FLAG; break; case PERL_UNICODE_STDERR: opt |= PERL_UNICODE_STDERR_FLAG; break; case PERL_UNICODE_STD: opt |= PERL_UNICODE_STD_FLAG; break; case PERL_UNICODE_IN: opt |= PERL_UNICODE_IN_FLAG; break; case PERL_UNICODE_OUT: opt |= PERL_UNICODE_OUT_FLAG; break; case PERL_UNICODE_INOUT: opt |= PERL_UNICODE_INOUT_FLAG; break; case PERL_UNICODE_LOCALE: opt |= PERL_UNICODE_LOCALE_FLAG; break; case PERL_UNICODE_ARGV: opt |= PERL_UNICODE_ARGV_FLAG; break; case PERL_UNICODE_UTF8CACHEASSERT: opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break; default: if (*p != '\n' && *p != '\r') { if(isSPACE(*p)) goto the_end_of_the_opts_parser; else Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p); } } } } } else opt = PERL_UNICODE_DEFAULT_FLAGS; the_end_of_the_opts_parser: if (opt & ~PERL_UNICODE_ALL_FLAGS) Perl_croak(aTHX_ "Unknown Unicode option value %" UVuf, (UV) (opt & ~PERL_UNICODE_ALL_FLAGS)); *popt = p; return opt; } #ifdef VMS # include <starlet.h> #endif U32 Perl_seed(pTHX) { /* * This is really just a quick hack which grabs various garbage * values. It really should be a real hash algorithm which * spreads the effect of every input bit onto every output bit, * if someone who knows about such things would bother to write it. * Might be a good idea to add that function to CORE as well. * No numbers below come from careful analysis or anything here, * except they are primes and SEED_C1 > 1E6 to get a full-width * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should * probably be bigger too. */ #if RANDBITS > 16 # define SEED_C1 1000003 #define SEED_C4 73819 #else # define SEED_C1 25747 #define SEED_C4 20639 #endif #define SEED_C2 3 #define SEED_C3 269 #define SEED_C5 26107 #ifndef PERL_NO_DEV_RANDOM int fd; #endif U32 u; #ifdef HAS_GETTIMEOFDAY struct timeval when; #else Time_t when; #endif /* This test is an escape hatch, this symbol isn't set by Configure. */ #ifndef PERL_NO_DEV_RANDOM #ifndef PERL_RANDOM_DEVICE /* /dev/random isn't used by default because reads from it will block * if there isn't enough entropy available. You can compile with * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there * is enough real entropy to fill the seed. */ # ifdef __amigaos4__ # define PERL_RANDOM_DEVICE "RANDOM:SIZE=4" # else # define PERL_RANDOM_DEVICE "/dev/urandom" # endif #endif fd = PerlLIO_open_cloexec(PERL_RANDOM_DEVICE, 0); if (fd != -1) { if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u) u = 0; PerlLIO_close(fd); if (u) return u; } #endif #ifdef HAS_GETTIMEOFDAY PerlProc_gettimeofday(&when,NULL); u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec; #else (void)time(&when); u = (U32)SEED_C1 * when; #endif u += SEED_C3 * (U32)PerlProc_getpid(); u += SEED_C4 * (U32)PTR2UV(PL_stack_sp); #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */ u += SEED_C5 * (U32)PTR2UV(&when); #endif return u; } void Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer) { #ifndef NO_PERL_HASH_ENV const char *env_pv; #endif unsigned long i; PERL_ARGS_ASSERT_GET_HASH_SEED; #ifndef NO_PERL_HASH_ENV env_pv= PerlEnv_getenv("PERL_HASH_SEED"); if ( env_pv ) { /* ignore leading spaces */ while (isSPACE(*env_pv)) env_pv++; # ifdef USE_PERL_PERTURB_KEYS /* if they set it to "0" we disable key traversal randomization completely */ if (strEQ(env_pv,"0")) { PL_hash_rand_bits_enabled= 0; } else { /* otherwise switch to deterministic mode */ PL_hash_rand_bits_enabled= 2; } # endif /* ignore a leading 0x... if it is there */ if (env_pv[0] == '0' && env_pv[1] == 'x') env_pv += 2; for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) { seed_buffer[i] = READ_XDIGIT(env_pv) << 4; if ( isXDIGIT(*env_pv)) { seed_buffer[i] |= READ_XDIGIT(env_pv); } } while (isSPACE(*env_pv)) env_pv++; if (*env_pv && !isXDIGIT(*env_pv)) { Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n"); } /* should we check for unparsed crap? */ /* should we warn about unused hex? */ /* should we warn about insufficient hex? */ } else #endif /* NO_PERL_HASH_ENV */ { for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) { seed_buffer[i] = (unsigned char)(Perl_internal_drand48() * (U8_MAX+1)); } } #ifdef USE_PERL_PERTURB_KEYS { /* initialize PL_hash_rand_bits from the hash seed. * This value is highly volatile, it is updated every * hash insert, and is used as part of hash bucket chain * randomization and hash iterator randomization. */ PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */ for( i = 0; i < sizeof(UV) ; i++ ) { PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES]; PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8); } } # ifndef NO_PERL_HASH_ENV env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS"); if (env_pv) { if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) { PL_hash_rand_bits_enabled= 0; } else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) { PL_hash_rand_bits_enabled= 1; } else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) { PL_hash_rand_bits_enabled= 2; } else { Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv); } } # endif #endif } #ifdef PERL_GLOBAL_STRUCT #define PERL_GLOBAL_STRUCT_INIT #include "opcode.h" /* the ppaddr and check */ struct perl_vars * Perl_init_global_struct(pTHX) { struct perl_vars *plvarsp = NULL; # ifdef PERL_GLOBAL_STRUCT const IV nppaddr = C_ARRAY_LENGTH(Gppaddr); const IV ncheck = C_ARRAY_LENGTH(Gcheck); PERL_UNUSED_CONTEXT; # ifdef PERL_GLOBAL_STRUCT_PRIVATE /* PerlMem_malloc() because can't use even safesysmalloc() this early. */ plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars)); if (!plvarsp) exit(1); # else plvarsp = PL_VarsPtr; # endif /* PERL_GLOBAL_STRUCT_PRIVATE */ # undef PERLVAR # undef PERLVARA # undef PERLVARI # undef PERLVARIC # define PERLVAR(prefix,var,type) /**/ # define PERLVARA(prefix,var,n,type) /**/ # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init; # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init; # include "perlvars.h" # undef PERLVAR # undef PERLVARA # undef PERLVARI # undef PERLVARIC # ifdef PERL_GLOBAL_STRUCT plvarsp->Gppaddr = (Perl_ppaddr_t*) PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t)); if (!plvarsp->Gppaddr) exit(1); plvarsp->Gcheck = (Perl_check_t*) PerlMem_malloc(ncheck * sizeof(Perl_check_t)); if (!plvarsp->Gcheck) exit(1); Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t); Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t); # endif # ifdef PERL_SET_VARS PERL_SET_VARS(plvarsp); # endif # ifdef PERL_GLOBAL_STRUCT_PRIVATE plvarsp->Gsv_placeholder.sv_flags = 0; memset(plvarsp->Ghash_seed, 0, sizeof(plvarsp->Ghash_seed)); # endif # undef PERL_GLOBAL_STRUCT_INIT # endif return plvarsp; } #endif /* PERL_GLOBAL_STRUCT */ #ifdef PERL_GLOBAL_STRUCT void Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp) { int veto = plvarsp->Gveto_cleanup; PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT; PERL_UNUSED_CONTEXT; # ifdef PERL_GLOBAL_STRUCT # ifdef PERL_UNSET_VARS PERL_UNSET_VARS(plvarsp); # endif if (veto) return; free(plvarsp->Gppaddr); free(plvarsp->Gcheck); # ifdef PERL_GLOBAL_STRUCT_PRIVATE free(plvarsp); # endif # endif } #endif /* PERL_GLOBAL_STRUCT */ #ifdef PERL_MEM_LOG /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also * given, and you supply your own implementation. * * The default implementation reads a single env var, PERL_MEM_LOG, * expecting one or more of the following: * * \d+ - fd fd to write to : must be 1st (grok_atoUV) * 'm' - memlog was PERL_MEM_LOG=1 * 's' - svlog was PERL_SV_LOG=1 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1 * * This makes the logger controllable enough that it can reasonably be * added to the system perl. */ /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer * the Perl_mem_log_...() will use (either via sprintf or snprintf). */ #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...() * writes to. In the default logger, this is settable at runtime. */ #ifndef PERL_MEM_LOG_FD # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */ #endif #ifndef PERL_MEM_LOG_NOIMPL # ifdef DEBUG_LEAKING_SCALARS # define SV_LOG_SERIAL_FMT " [%lu]" # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial # else # define SV_LOG_SERIAL_FMT # define _SV_LOG_SERIAL_ARG(sv) # endif static void S_mem_log_common(enum mem_log_type mlt, const UV n, const UV typesize, const char *type_name, const SV *sv, Malloc_t oldalloc, Malloc_t newalloc, const char *filename, const int linenumber, const char *funcname) { const char *pmlenv; PERL_ARGS_ASSERT_MEM_LOG_COMMON; pmlenv = PerlEnv_getenv("PERL_MEM_LOG"); if (!pmlenv) return; if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s')) { /* We can't use SVs or PerlIO for obvious reasons, * so we'll use stdio and low-level IO instead. */ char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE]; # ifdef HAS_GETTIMEOFDAY # define MEM_LOG_TIME_FMT "%10d.%06d: " # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec struct timeval tv; gettimeofday(&tv, 0); # else # define MEM_LOG_TIME_FMT "%10d: " # define MEM_LOG_TIME_ARG (int)when Time_t when; (void)time(&when); # endif /* If there are other OS specific ways of hires time than * gettimeofday() (see dist/Time-HiRes), the easiest way is * probably that they would be used to fill in the struct * timeval. */ { STRLEN len; const char* endptr = pmlenv + stren(pmlenv); int fd; UV uv; if (grok_atoUV(pmlenv, &uv, &endptr) /* Ignore endptr. */ && uv && uv <= PERL_INT_MAX ) { fd = (int)uv; } else { fd = PERL_MEM_LOG_FD; } if (strchr(pmlenv, 't')) { len = my_snprintf(buf, sizeof(buf), MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG); PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len)); } switch (mlt) { case MLT_ALLOC: len = my_snprintf(buf, sizeof(buf), "alloc: %s:%d:%s: %" IVdf " %" UVuf " %s = %" IVdf ": %" UVxf "\n", filename, linenumber, funcname, n, typesize, type_name, n * typesize, PTR2UV(newalloc)); break; case MLT_REALLOC: len = my_snprintf(buf, sizeof(buf), "realloc: %s:%d:%s: %" IVdf " %" UVuf " %s = %" IVdf ": %" UVxf " -> %" UVxf "\n", filename, linenumber, funcname, n, typesize, type_name, n * typesize, PTR2UV(oldalloc), PTR2UV(newalloc)); break; case MLT_FREE: len = my_snprintf(buf, sizeof(buf), "free: %s:%d:%s: %" UVxf "\n", filename, linenumber, funcname, PTR2UV(oldalloc)); break; case MLT_NEW_SV: case MLT_DEL_SV: len = my_snprintf(buf, sizeof(buf), "%s_SV: %s:%d:%s: %" UVxf SV_LOG_SERIAL_FMT "\n", mlt == MLT_NEW_SV ? "new" : "del", filename, linenumber, funcname, PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv)); break; default: len = 0; } PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len)); } } } #endif /* !PERL_MEM_LOG_NOIMPL */ #ifndef PERL_MEM_LOG_NOIMPL # define \ mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \ mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) #else /* this is suboptimal, but bug compatible. User is providing their own implementation, but is getting these functions anyway, and they do nothing. But _NOIMPL users should be able to cope or fix */ # define \ mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \ /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */ #endif Malloc_t Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name, Malloc_t newalloc, const char *filename, const int linenumber, const char *funcname) { PERL_ARGS_ASSERT_MEM_LOG_ALLOC; mem_log_common_if(MLT_ALLOC, n, typesize, type_name, NULL, NULL, newalloc, filename, linenumber, funcname); return newalloc; } Malloc_t Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name, Malloc_t oldalloc, Malloc_t newalloc, const char *filename, const int linenumber, const char *funcname) { PERL_ARGS_ASSERT_MEM_LOG_REALLOC; mem_log_common_if(MLT_REALLOC, n, typesize, type_name, NULL, oldalloc, newalloc, filename, linenumber, funcname); return newalloc; } Malloc_t Perl_mem_log_free(Malloc_t oldalloc, const char *filename, const int linenumber, const char *funcname) { PERL_ARGS_ASSERT_MEM_LOG_FREE; mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL, filename, linenumber, funcname); return oldalloc; } void Perl_mem_log_new_sv(const SV *sv, const char *filename, const int linenumber, const char *funcname) { mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL, filename, linenumber, funcname); } void Perl_mem_log_del_sv(const SV *sv, const char *filename, const int linenumber, const char *funcname) { mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL, filename, linenumber, funcname); } #endif /* PERL_MEM_LOG */ /* =for apidoc quadmath_format_single C<quadmath_snprintf()> is very strict about its C<format> string and will fail, returning -1, if the format is invalid. It accepts exactly one format spec. C<quadmath_format_single()> checks that the intended single spec looks sane: begins with C<%>, has only one C<%>, ends with C<[efgaEFGA]>, and has C<Q> before it. This is not a full "printf syntax check", just the basics. Returns the format if it is valid, NULL if not. C<quadmath_format_single()> can and will actually patch in the missing C<Q>, if necessary. In this case it will return the modified copy of the format, B<which the caller will need to free.> See also L</quadmath_format_needed>. =cut */ #ifdef USE_QUADMATH const char* Perl_quadmath_format_single(const char* format) { STRLEN len; PERL_ARGS_ASSERT_QUADMATH_FORMAT_SINGLE; if (format[0] != '%' || strchr(format + 1, '%')) return NULL; len = strlen(format); /* minimum length three: %Qg */ if (len < 3 || strchr("efgaEFGA", format[len - 1]) == NULL) return NULL; if (format[len - 2] != 'Q') { char* fixed; Newx(fixed, len + 1, char); memcpy(fixed, format, len - 1); fixed[len - 1] = 'Q'; fixed[len ] = format[len - 1]; fixed[len + 1] = 0; return (const char*)fixed; } return format; } #endif /* =for apidoc quadmath_format_needed C<quadmath_format_needed()> returns true if the C<format> string seems to contain at least one non-Q-prefixed C<%[efgaEFGA]> format specifier, or returns false otherwise. The format specifier detection is not complete printf-syntax detection, but it should catch most common cases. If true is returned, those arguments B<should> in theory be processed with C<quadmath_snprintf()>, but in case there is more than one such format specifier (see L</quadmath_format_single>), and if there is anything else beyond that one (even just a single byte), they B<cannot> be processed because C<quadmath_snprintf()> is very strict, accepting only one format spec, and nothing else. In this case, the code should probably fail. =cut */ #ifdef USE_QUADMATH bool Perl_quadmath_format_needed(const char* format) { const char *p = format; const char *q; PERL_ARGS_ASSERT_QUADMATH_FORMAT_NEEDED; while ((q = strchr(p, '%'))) { q++; if (*q == '+') /* plus */ q++; if (*q == '#') /* alt */ q++; if (*q == '*') /* width */ q++; else { if (isDIGIT(*q)) { while (isDIGIT(*q)) q++; } } if (*q == '.' && (q[1] == '*' || isDIGIT(q[1]))) { /* prec */ q++; if (*q == '*') q++; else while (isDIGIT(*q)) q++; } if (strchr("efgaEFGA", *q)) /* Would have needed 'Q' in front. */ return TRUE; p = q + 1; } return FALSE; } #endif /* =for apidoc my_snprintf The C library C<snprintf> functionality, if available and standards-compliant (uses C<vsnprintf>, actually). However, if the C<vsnprintf> is not available, will unfortunately use the unsafe C<vsprintf> which can overrun the buffer (there is an overrun check, but that may be too late). Consider using C<sv_vcatpvf> instead, or getting C<vsnprintf>. =cut */ int Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...) { int retval = -1; va_list ap; PERL_ARGS_ASSERT_MY_SNPRINTF; #ifndef HAS_VSNPRINTF PERL_UNUSED_VAR(len); #endif va_start(ap, format); #ifdef USE_QUADMATH { const char* qfmt = quadmath_format_single(format); bool quadmath_valid = FALSE; if (qfmt) { /* If the format looked promising, use it as quadmath. */ retval = quadmath_snprintf(buffer, len, qfmt, va_arg(ap, NV)); if (retval == -1) { if (qfmt != format) { dTHX; SAVEFREEPV(qfmt); } Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", qfmt); } quadmath_valid = TRUE; if (qfmt != format) Safefree(qfmt); qfmt = NULL; } assert(qfmt == NULL); /* quadmath_format_single() will return false for example for * "foo = %g", or simply "%g". We could handle the %g by * using quadmath for the NV args. More complex cases of * course exist: "foo = %g, bar = %g", or "foo=%Qg" (otherwise * quadmath-valid but has stuff in front). * * Handling the "Q-less" cases right would require walking * through the va_list and rewriting the format, calling * quadmath for the NVs, building a new va_list, and then * letting vsnprintf/vsprintf to take care of the other * arguments. This may be doable. * * We do not attempt that now. But for paranoia, we here try * to detect some common (but not all) cases where the * "Q-less" %[efgaEFGA] formats are present, and die if * detected. This doesn't fix the problem, but it stops the * vsnprintf/vsprintf pulling doubles off the va_list when * __float128 NVs should be pulled off instead. * * If quadmath_format_needed() returns false, we are reasonably * certain that we can call vnsprintf() or vsprintf() safely. */ if (!quadmath_valid && quadmath_format_needed(format)) Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", format); } #endif if (retval == -1) #ifdef HAS_VSNPRINTF retval = vsnprintf(buffer, len, format, ap); #else retval = vsprintf(buffer, format, ap); #endif va_end(ap); /* vsprintf() shows failure with < 0 */ if (retval < 0 #ifdef HAS_VSNPRINTF /* vsnprintf() shows failure with >= len */ || (len > 0 && (Size_t)retval >= len) #endif ) Perl_croak_nocontext("panic: my_snprintf buffer overflow"); return retval; } /* =for apidoc my_vsnprintf The C library C<vsnprintf> if available and standards-compliant. However, if if the C<vsnprintf> is not available, will unfortunately use the unsafe C<vsprintf> which can overrun the buffer (there is an overrun check, but that may be too late). Consider using C<sv_vcatpvf> instead, or getting C<vsnprintf>. =cut */ int Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap) { #ifdef USE_QUADMATH PERL_UNUSED_ARG(buffer); PERL_UNUSED_ARG(len); PERL_UNUSED_ARG(format); /* the cast is to avoid gcc -Wsizeof-array-argument complaining */ PERL_UNUSED_ARG((void*)ap); Perl_croak_nocontext("panic: my_vsnprintf not available with quadmath"); return 0; #else int retval; #ifdef NEED_VA_COPY va_list apc; PERL_ARGS_ASSERT_MY_VSNPRINTF; Perl_va_copy(ap, apc); # ifdef HAS_VSNPRINTF retval = vsnprintf(buffer, len, format, apc); # else PERL_UNUSED_ARG(len); retval = vsprintf(buffer, format, apc); # endif va_end(apc); #else # ifdef HAS_VSNPRINTF retval = vsnprintf(buffer, len, format, ap); # else PERL_UNUSED_ARG(len); retval = vsprintf(buffer, format, ap); # endif #endif /* #ifdef NEED_VA_COPY */ /* vsprintf() shows failure with < 0 */ if (retval < 0 #ifdef HAS_VSNPRINTF /* vsnprintf() shows failure with >= len */ || (len > 0 && (Size_t)retval >= len) #endif ) Perl_croak_nocontext("panic: my_vsnprintf buffer overflow"); return retval; #endif } void Perl_my_clearenv(pTHX) { dVAR; #if ! defined(PERL_MICRO) # if defined(PERL_IMPLICIT_SYS) || defined(WIN32) PerlEnv_clearenv(); # else /* ! (PERL_IMPLICIT_SYS || WIN32) */ # if defined(USE_ENVIRON_ARRAY) # if defined(USE_ITHREADS) /* only the parent thread can clobber the process environment */ if (PL_curinterp == aTHX) # endif /* USE_ITHREADS */ { # if ! defined(PERL_USE_SAFE_PUTENV) if ( !PL_use_safe_putenv) { I32 i; if (environ == PL_origenviron) environ = (char**)safesysmalloc(sizeof(char*)); else for (i = 0; environ[i]; i++) (void)safesysfree(environ[i]); } environ[0] = NULL; # else /* PERL_USE_SAFE_PUTENV */ # if defined(HAS_CLEARENV) (void)clearenv(); # elif defined(HAS_UNSETENV) int bsiz = 80; /* Most envvar names will be shorter than this. */ char *buf = (char*)safesysmalloc(bsiz); while (*environ != NULL) { char *e = strchr(*environ, '='); int l = e ? e - *environ : (int)strlen(*environ); if (bsiz < l + 1) { (void)safesysfree(buf); bsiz = l + 1; /* + 1 for the \0. */ buf = (char*)safesysmalloc(bsiz); } memcpy(buf, *environ, l); buf[l] = '\0'; (void)unsetenv(buf); } (void)safesysfree(buf); # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */ /* Just null environ and accept the leakage. */ *environ = NULL; # endif /* HAS_CLEARENV || HAS_UNSETENV */ # endif /* ! PERL_USE_SAFE_PUTENV */ } # endif /* USE_ENVIRON_ARRAY */ # endif /* PERL_IMPLICIT_SYS || WIN32 */ #endif /* PERL_MICRO */ } #ifdef PERL_IMPLICIT_CONTEXT /* Implements the MY_CXT_INIT macro. The first time a module is loaded, the global PL_my_cxt_index is incremented, and that value is assigned to that module's static my_cxt_index (who's address is passed as an arg). Then, for each interpreter this function is called for, it makes sure a void* slot is available to hang the static data off, by allocating or extending the interpreter's PL_my_cxt_list array */ #ifndef PERL_GLOBAL_STRUCT_PRIVATE void * Perl_my_cxt_init(pTHX_ int *index, size_t size) { dVAR; void *p; PERL_ARGS_ASSERT_MY_CXT_INIT; if (*index == -1) { /* this module hasn't been allocated an index yet */ MUTEX_LOCK(&PL_my_ctx_mutex); *index = PL_my_cxt_index++; MUTEX_UNLOCK(&PL_my_ctx_mutex); } /* make sure the array is big enough */ if (PL_my_cxt_size <= *index) { if (PL_my_cxt_size) { IV new_size = PL_my_cxt_size; while (new_size <= *index) new_size *= 2; Renew(PL_my_cxt_list, new_size, void *); PL_my_cxt_size = new_size; } else { PL_my_cxt_size = 16; Newx(PL_my_cxt_list, PL_my_cxt_size, void *); } } /* newSV() allocates one more than needed */ p = (void*)SvPVX(newSV(size-1)); PL_my_cxt_list[*index] = p; Zero(p, size, char); return p; } #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */ int Perl_my_cxt_index(pTHX_ const char *my_cxt_key) { dVAR; int index; PERL_ARGS_ASSERT_MY_CXT_INDEX; for (index = 0; index < PL_my_cxt_index; index++) { const char *key = PL_my_cxt_keys[index]; /* try direct pointer compare first - there are chances to success, * and it's much faster. */ if ((key == my_cxt_key) || strEQ(key, my_cxt_key)) return index; } return -1; } void * Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size) { dVAR; void *p; int index; PERL_ARGS_ASSERT_MY_CXT_INIT; index = Perl_my_cxt_index(aTHX_ my_cxt_key); if (index == -1) { /* this module hasn't been allocated an index yet */ MUTEX_LOCK(&PL_my_ctx_mutex); index = PL_my_cxt_index++; MUTEX_UNLOCK(&PL_my_ctx_mutex); } /* make sure the array is big enough */ if (PL_my_cxt_size <= index) { int old_size = PL_my_cxt_size; int i; if (PL_my_cxt_size) { IV new_size = PL_my_cxt_size; while (new_size <= index) new_size *= 2; Renew(PL_my_cxt_list, new_size, void *); Renew(PL_my_cxt_keys, new_size, const char *); PL_my_cxt_size = new_size; } else { PL_my_cxt_size = 16; Newx(PL_my_cxt_list, PL_my_cxt_size, void *); Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *); } for (i = old_size; i < PL_my_cxt_size; i++) { PL_my_cxt_keys[i] = 0; PL_my_cxt_list[i] = 0; } } PL_my_cxt_keys[index] = my_cxt_key; /* newSV() allocates one more than needed */ p = (void*)SvPVX(newSV(size-1)); PL_my_cxt_list[index] = p; Zero(p, size, char); return p; } #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */ #endif /* PERL_IMPLICIT_CONTEXT */ /* Perl_xs_handshake(): implement the various XS_*_BOOTCHECK macros, which are added to .c files by ExtUtils::ParseXS, to check that the perl the module was built with is binary compatible with the running perl. usage: Perl_xs_handshake(U32 key, void * v_my_perl, const char * file, [U32 items, U32 ax], [char * api_version], [char * xs_version]) The meaning of the varargs is determined the U32 key arg (which is not a format string). The fields of key are assembled by using HS_KEY(). Under PERL_IMPLICIT_CONTEX, the v_my_perl arg is of type "PerlInterpreter *" and represents the callers context; otherwise it is of type "CV *", and is the boot xsub's CV. v_my_perl will catch where a threaded future perl526.dll calling IO.dll for example, and IO.dll was linked with threaded perl524.dll, and both perl526.dll and perl524.dll are in %PATH and the Win32 DLL loader successfully can load IO.dll into the process but simultaneously it loaded an interpreter of a different version into the process, and XS code will naturally pass SV*s created by perl524.dll for perl526.dll to use through perl526.dll's my_perl->Istack_base. v_my_perl cannot be the first arg, since then 'key' will be out of place in a threaded vs non-threaded mixup; and analyzing the key number's bitfields won't reveal the problem, since it will be a valid key (unthreaded perl) on interp side, but croak will report the XS mod's key as gibberish (it is really a my_perl ptr) (threaded XS mod); or if it's a threaded perl and an unthreaded XS module, threaded perl will look at an uninit C stack or an uninit register to get 'key' (remember that it assumes that the 1st arg is the interp cxt). 'file' is the source filename of the caller. */ I32 Perl_xs_handshake(const U32 key, void * v_my_perl, const char * file, ...) { va_list args; U32 items, ax; void * got; void * need; #ifdef PERL_IMPLICIT_CONTEXT dTHX; tTHX xs_interp; #else CV* cv; SV *** xs_spp; #endif PERL_ARGS_ASSERT_XS_HANDSHAKE; va_start(args, file); got = INT2PTR(void*, (UV)(key & HSm_KEY_MATCH)); need = (void *)(HS_KEY(FALSE, FALSE, "", "") & HSm_KEY_MATCH); if (UNLIKELY(got != need)) goto bad_handshake; /* try to catch where a 2nd threaded perl interp DLL is loaded into a process by a XS DLL compiled against the wrong interl DLL b/c of bad @INC, and the 2nd threaded perl interp DLL never initialized its TLS/PERL_SYS_INIT3 so dTHX call from 2nd interp DLL can't return the my_perl that pp_entersub passed to the XS DLL */ #ifdef PERL_IMPLICIT_CONTEXT xs_interp = (tTHX)v_my_perl; got = xs_interp; need = my_perl; #else /* try to catch where an unthreaded perl interp DLL (for ex. perl522.dll) is loaded into a process by a XS DLL built by an unthreaded perl522.dll perl, but the DynaLoder/Perl that started the process and loaded the XS DLL is unthreaded perl524.dll, since unthreadeds don't pass my_perl (a unique *) through pp_entersub, use a unique value (which is a pointer to PL_stack_sp's location in the unthreaded perl binary) stored in CV * to figure out if this Perl_xs_handshake was called by the same pp_entersub */ cv = (CV*)v_my_perl; xs_spp = (SV***)CvHSCXT(cv); got = xs_spp; need = &PL_stack_sp; #endif if(UNLIKELY(got != need)) { bad_handshake:/* recycle branch and string from above */ if(got != (void *)HSf_NOCHK) noperl_die("%s: loadable library and perl binaries are mismatched" " (got handshake key %p, needed %p)\n", file, got, need); } if(key & HSf_SETXSUBFN) { /* this might be called from a module bootstrap */ SAVEPPTR(PL_xsubfilename);/* which was require'd from a XSUB BEGIN */ PL_xsubfilename = file; /* so the old name must be restored for additional XSUBs to register themselves */ /* XSUBs can't be perl lang/perl5db.pl debugged if (PERLDB_LINE_OR_SAVESRC) (void)gv_fetchfile(file); */ } if(key & HSf_POPMARK) { ax = POPMARK; { SV **mark = PL_stack_base + ax++; { dSP; items = (I32)(SP - MARK); } } } else { items = va_arg(args, U32); ax = va_arg(args, U32); } { U32 apiverlen; assert(HS_GETAPIVERLEN(key) <= UCHAR_MAX); if((apiverlen = HS_GETAPIVERLEN(key))) { char * api_p = va_arg(args, char*); if(apiverlen != sizeof("v" PERL_API_VERSION_STRING)-1 || memNE(api_p, "v" PERL_API_VERSION_STRING, sizeof("v" PERL_API_VERSION_STRING)-1)) Perl_croak_nocontext("Perl API version %s of %" SVf " does not match %s", api_p, SVfARG(PL_stack_base[ax + 0]), "v" PERL_API_VERSION_STRING); } } { U32 xsverlen; assert(HS_GETXSVERLEN(key) <= UCHAR_MAX && HS_GETXSVERLEN(key) <= HS_APIVERLEN_MAX); if((xsverlen = HS_GETXSVERLEN(key))) S_xs_version_bootcheck(aTHX_ items, ax, va_arg(args, char*), xsverlen); } va_end(args); return ax; } STATIC void S_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p, STRLEN xs_len) { SV *sv; const char *vn = NULL; SV *const module = PL_stack_base[ax]; PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK; if (items >= 2) /* version supplied as bootstrap arg */ sv = PL_stack_base[ax + 1]; else { /* XXX GV_ADDWARN */ vn = "XS_VERSION"; sv = get_sv(Perl_form(aTHX_ "%" SVf "::%s", SVfARG(module), vn), 0); if (!sv || !SvOK(sv)) { vn = "VERSION"; sv = get_sv(Perl_form(aTHX_ "%" SVf "::%s", SVfARG(module), vn), 0); } } if (sv) { SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP); SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version") ? sv : sv_2mortal(new_version(sv)); xssv = upg_version(xssv, 0); if ( vcmp(pmsv,xssv) ) { SV *string = vstringify(xssv); SV *xpt = Perl_newSVpvf(aTHX_ "%" SVf " object version %" SVf " does not match ", SVfARG(module), SVfARG(string)); SvREFCNT_dec(string); string = vstringify(pmsv); if (vn) { Perl_sv_catpvf(aTHX_ xpt, "$%" SVf "::%s %" SVf, SVfARG(module), vn, SVfARG(string)); } else { Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %" SVf, SVfARG(string)); } SvREFCNT_dec(string); Perl_sv_2mortal(aTHX_ xpt); Perl_croak_sv(aTHX_ xpt); } } } /* =for apidoc my_strlcat The C library C<strlcat> if available, or a Perl implementation of it. This operates on C C<NUL>-terminated strings. C<my_strlcat()> appends string C<src> to the end of C<dst>. It will append at most S<C<size - strlen(dst) - 1>> characters. It will then C<NUL>-terminate, unless C<size> is 0 or the original C<dst> string was longer than C<size> (in practice this should not happen as it means that either C<size> is incorrect or that C<dst> is not a proper C<NUL>-terminated string). Note that C<size> is the full size of the destination buffer and the result is guaranteed to be C<NUL>-terminated if there is room. Note that room for the C<NUL> should be included in C<size>. The return value is the total length that C<dst> would have if C<size> is sufficiently large. Thus it is the initial length of C<dst> plus the length of C<src>. If C<size> is smaller than the return, the excess was not appended. =cut Description stolen from http://man.openbsd.org/strlcat.3 */ #ifndef HAS_STRLCAT Size_t Perl_my_strlcat(char *dst, const char *src, Size_t size) { Size_t used, length, copy; used = strlen(dst); length = strlen(src); if (size > 0 && used < size - 1) { copy = (length >= size - used) ? size - used - 1 : length; memcpy(dst + used, src, copy); dst[used + copy] = '\0'; } return used + length; } #endif /* =for apidoc my_strlcpy The C library C<strlcpy> if available, or a Perl implementation of it. This operates on C C<NUL>-terminated strings. C<my_strlcpy()> copies up to S<C<size - 1>> characters from the string C<src> to C<dst>, C<NUL>-terminating the result if C<size> is not 0. The return value is the total length C<src> would be if the copy completely succeeded. If it is larger than C<size>, the excess was not copied. =cut Description stolen from http://man.openbsd.org/strlcpy.3 */ #ifndef HAS_STRLCPY Size_t Perl_my_strlcpy(char *dst, const char *src, Size_t size) { Size_t length, copy; length = strlen(src); if (size > 0) { copy = (length >= size) ? size - 1 : length; memcpy(dst, src, copy); dst[copy] = '\0'; } return length; } #endif /* =for apidoc my_strnlen The C library C<strnlen> if available, or a Perl implementation of it. C<my_strnlen()> computes the length of the string, up to C<maxlen> characters. It will will never attempt to address more than C<maxlen> characters, making it suitable for use with strings that are not guaranteed to be NUL-terminated. =cut Description stolen from http://man.openbsd.org/strnlen.3, implementation stolen from PostgreSQL. */ #ifndef HAS_STRNLEN Size_t Perl_my_strnlen(const char *str, Size_t maxlen) { const char *p = str; PERL_ARGS_ASSERT_MY_STRNLEN; while(maxlen-- && *p) p++; return p - str; } #endif #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500) /* VC7 or 7.1, building with pre-VC7 runtime libraries. */ long _ftol( double ); /* Defined by VC6 C libs. */ long _ftol2( double dblSource ) { return _ftol( dblSource ); } #endif PERL_STATIC_INLINE bool S_gv_has_usable_name(pTHX_ GV *gv) { GV **gvp; return GvSTASH(gv) && HvENAME(GvSTASH(gv)) && (gvp = (GV **)hv_fetchhek( GvSTASH(gv), GvNAME_HEK(gv), 0 )) && *gvp == gv; } void Perl_get_db_sub(pTHX_ SV **svp, CV *cv) { SV * const dbsv = GvSVn(PL_DBsub); const bool save_taint = TAINT_get; /* When we are called from pp_goto (svp is null), * we do not care about using dbsv to call CV; * it's for informational purposes only. */ PERL_ARGS_ASSERT_GET_DB_SUB; TAINT_set(FALSE); save_item(dbsv); if (!PERLDB_SUB_NN) { GV *gv = CvGV(cv); if (!svp && !CvLEXICAL(cv)) { gv_efullname3(dbsv, gv, NULL); } else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED)) || CvLEXICAL(cv) || strEQ(GvNAME(gv), "END") || ( /* Could be imported, and old sub redefined. */ (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv)) && !( (SvTYPE(*svp) == SVt_PVGV) && (GvCV((const GV *)*svp) == cv) /* Use GV from the stack as a fallback. */ && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp) ) ) ) { /* GV is potentially non-unique, or contain different CV. */ SV * const tmp = newRV(MUTABLE_SV(cv)); sv_setsv(dbsv, tmp); SvREFCNT_dec(tmp); } else { sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv))); sv_catpvs(dbsv, "::"); sv_cathek(dbsv, GvNAME_HEK(gv)); } } else { const int type = SvTYPE(dbsv); if (type < SVt_PVIV && type != SVt_IV) sv_upgrade(dbsv, SVt_PVIV); (void)SvIOK_on(dbsv); SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */ } SvSETMAGIC(dbsv); TAINT_IF(save_taint); #ifdef NO_TAINT_SUPPORT PERL_UNUSED_VAR(save_taint); #endif } int Perl_my_dirfd(DIR * dir) { /* Most dirfd implementations have problems when passed NULL. */ if(!dir) return -1; #ifdef HAS_DIRFD return dirfd(dir); #elif defined(HAS_DIR_DD_FD) return dir->dd_fd; #else Perl_croak_nocontext(PL_no_func, "dirfd"); NOT_REACHED; /* NOTREACHED */ return 0; #endif } #if !defined(HAS_MKOSTEMP) || !defined(HAS_MKSTEMP) #define TEMP_FILE_CH "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789" #define TEMP_FILE_CH_COUNT (sizeof(TEMP_FILE_CH)-1) static int S_my_mkostemp(char *templte, int flags) { dTHX; STRLEN len = strlen(templte); int fd; int attempts = 0; if (len < 6 || templte[len-1] != 'X' || templte[len-2] != 'X' || templte[len-3] != 'X' || templte[len-4] != 'X' || templte[len-5] != 'X' || templte[len-6] != 'X') { SETERRNO(EINVAL, LIB_INVARG); return -1; } do { int i; for (i = 1; i <= 6; ++i) { templte[len-i] = TEMP_FILE_CH[(int)(Perl_internal_drand48() * TEMP_FILE_CH_COUNT)]; } fd = PerlLIO_open3(templte, O_RDWR | O_CREAT | O_EXCL | flags, 0600); } while (fd == -1 && errno == EEXIST && ++attempts <= 100); return fd; } #endif #ifndef HAS_MKOSTEMP int Perl_my_mkostemp(char *templte, int flags) { PERL_ARGS_ASSERT_MY_MKOSTEMP; return S_my_mkostemp(templte, flags); } #endif #ifndef HAS_MKSTEMP int Perl_my_mkstemp(char *templte) { PERL_ARGS_ASSERT_MY_MKSTEMP; return S_my_mkostemp(templte, 0); } #endif REGEXP * Perl_get_re_arg(pTHX_ SV *sv) { if (sv) { if (SvMAGICAL(sv)) mg_get(sv); if (SvROK(sv)) sv = MUTABLE_SV(SvRV(sv)); if (SvTYPE(sv) == SVt_REGEXP) return (REGEXP*) sv; } return NULL; } /* * This code is derived from drand48() implementation from FreeBSD, * found in lib/libc/gen/_rand48.c. * * The U64 implementation is original, based on the POSIX * specification for drand48(). */ /* * Copyright (c) 1993 Martin Birgmeier * All rights reserved. * * You may redistribute unmodified or modified versions of this source * code provided that the above copyright notice and this and the * following conditions are retained. * * This software is provided ``as is'', and comes with no warranties * of any kind. I shall in no event be liable for anything that happens * to anyone/anything when using this software. */ #define FREEBSD_DRAND48_SEED_0 (0x330e) #ifdef PERL_DRAND48_QUAD #define DRAND48_MULT UINT64_C(0x5deece66d) #define DRAND48_ADD 0xb #define DRAND48_MASK UINT64_C(0xffffffffffff) #else #define FREEBSD_DRAND48_SEED_1 (0xabcd) #define FREEBSD_DRAND48_SEED_2 (0x1234) #define FREEBSD_DRAND48_MULT_0 (0xe66d) #define FREEBSD_DRAND48_MULT_1 (0xdeec) #define FREEBSD_DRAND48_MULT_2 (0x0005) #define FREEBSD_DRAND48_ADD (0x000b) const unsigned short _rand48_mult[3] = { FREEBSD_DRAND48_MULT_0, FREEBSD_DRAND48_MULT_1, FREEBSD_DRAND48_MULT_2 }; const unsigned short _rand48_add = FREEBSD_DRAND48_ADD; #endif void Perl_drand48_init_r(perl_drand48_t *random_state, U32 seed) { PERL_ARGS_ASSERT_DRAND48_INIT_R; #ifdef PERL_DRAND48_QUAD *random_state = FREEBSD_DRAND48_SEED_0 + ((U64)seed << 16); #else random_state->seed[0] = FREEBSD_DRAND48_SEED_0; random_state->seed[1] = (U16) seed; random_state->seed[2] = (U16) (seed >> 16); #endif } double Perl_drand48_r(perl_drand48_t *random_state) { PERL_ARGS_ASSERT_DRAND48_R; #ifdef PERL_DRAND48_QUAD *random_state = (*random_state * DRAND48_MULT + DRAND48_ADD) & DRAND48_MASK; return ldexp((double)*random_state, -48); #else { U32 accu; U16 temp[2]; accu = (U32) _rand48_mult[0] * (U32) random_state->seed[0] + (U32) _rand48_add; temp[0] = (U16) accu; /* lower 16 bits */ accu >>= sizeof(U16) * 8; accu += (U32) _rand48_mult[0] * (U32) random_state->seed[1] + (U32) _rand48_mult[1] * (U32) random_state->seed[0]; temp[1] = (U16) accu; /* middle 16 bits */ accu >>= sizeof(U16) * 8; accu += _rand48_mult[0] * random_state->seed[2] + _rand48_mult[1] * random_state->seed[1] + _rand48_mult[2] * random_state->seed[0]; random_state->seed[0] = temp[0]; random_state->seed[1] = temp[1]; random_state->seed[2] = (U16) accu; return ldexp((double) random_state->seed[0], -48) + ldexp((double) random_state->seed[1], -32) + ldexp((double) random_state->seed[2], -16); } #endif } #ifdef USE_C_BACKTRACE /* Possibly move all this USE_C_BACKTRACE code into a new file. */ #ifdef USE_BFD typedef struct { /* abfd is the BFD handle. */ bfd* abfd; /* bfd_syms is the BFD symbol table. */ asymbol** bfd_syms; /* bfd_text is handle to the the ".text" section of the object file. */ asection* bfd_text; /* Since opening the executable and scanning its symbols is quite * heavy operation, we remember the filename we used the last time, * and do the opening and scanning only if the filename changes. * This removes most (but not all) open+scan cycles. */ const char* fname_prev; } bfd_context; /* Given a dl_info, update the BFD context if necessary. */ static void bfd_update(bfd_context* ctx, Dl_info* dl_info) { /* BFD open and scan only if the filename changed. */ if (ctx->fname_prev == NULL || strNE(dl_info->dli_fname, ctx->fname_prev)) { if (ctx->abfd) { bfd_close(ctx->abfd); } ctx->abfd = bfd_openr(dl_info->dli_fname, 0); if (ctx->abfd) { if (bfd_check_format(ctx->abfd, bfd_object)) { IV symbol_size = bfd_get_symtab_upper_bound(ctx->abfd); if (symbol_size > 0) { Safefree(ctx->bfd_syms); Newx(ctx->bfd_syms, symbol_size, asymbol*); ctx->bfd_text = bfd_get_section_by_name(ctx->abfd, ".text"); } else ctx->abfd = NULL; } else ctx->abfd = NULL; } ctx->fname_prev = dl_info->dli_fname; } } /* Given a raw frame, try to symbolize it and store * symbol information (source file, line number) away. */ static void bfd_symbolize(bfd_context* ctx, void* raw_frame, char** symbol_name, STRLEN* symbol_name_size, char** source_name, STRLEN* source_name_size, STRLEN* source_line) { *symbol_name = NULL; *symbol_name_size = 0; if (ctx->abfd) { IV offset = PTR2IV(raw_frame) - PTR2IV(ctx->bfd_text->vma); if (offset > 0 && bfd_canonicalize_symtab(ctx->abfd, ctx->bfd_syms) > 0) { const char *file; const char *func; unsigned int line = 0; if (bfd_find_nearest_line(ctx->abfd, ctx->bfd_text, ctx->bfd_syms, offset, &file, &func, &line) && file && func && line > 0) { /* Size and copy the source file, use only * the basename of the source file. * * NOTE: the basenames are fine for the * Perl source files, but may not always * be the best idea for XS files. */ const char *p, *b = NULL; /* Look for the last slash. */ for (p = file; *p; p++) { if (*p == '/') b = p + 1; } if (b == NULL || *b == 0) { b = file; } *source_name_size = p - b + 1; Newx(*source_name, *source_name_size + 1, char); Copy(b, *source_name, *source_name_size + 1, char); *symbol_name_size = strlen(func); Newx(*symbol_name, *symbol_name_size + 1, char); Copy(func, *symbol_name, *symbol_name_size + 1, char); *source_line = line; } } } } #endif /* #ifdef USE_BFD */ #ifdef PERL_DARWIN /* OS X has no public API for for 'symbolicating' (Apple official term) * stack addresses to {function_name, source_file, line_number}. * Good news: there is command line utility atos(1) which does that. * Bad news 1: it's a command line utility. * Bad news 2: one needs to have the Developer Tools installed. * Bad news 3: in newer releases it needs to be run as 'xcrun atos'. * * To recap: we need to open a pipe for reading for a utility which * might not exist, or exists in different locations, and then parse * the output. And since this is all for a low-level API, we cannot * use high-level stuff. Thanks, Apple. */ typedef struct { /* tool is set to the absolute pathname of the tool to use: * xcrun or atos. */ const char* tool; /* format is set to a printf format string used for building * the external command to run. */ const char* format; /* unavail is set if e.g. xcrun cannot be found, or something * else happens that makes getting the backtrace dubious. Note, * however, that the context isn't persistent, the next call to * get_c_backtrace() will start from scratch. */ bool unavail; /* fname is the current object file name. */ const char* fname; /* object_base_addr is the base address of the shared object. */ void* object_base_addr; } atos_context; /* Given |dl_info|, updates the context. If the context has been * marked unavailable, return immediately. If not but the tool has * not been set, set it to either "xcrun atos" or "atos" (also set the * format to use for creating commands for piping), or if neither is * unavailable (one needs the Developer Tools installed), mark the context * an unavailable. Finally, update the filename (object name), * and its base address. */ static void atos_update(atos_context* ctx, Dl_info* dl_info) { if (ctx->unavail) return; if (ctx->tool == NULL) { const char* tools[] = { "/usr/bin/xcrun", "/usr/bin/atos" }; const char* formats[] = { "/usr/bin/xcrun atos -o '%s' -l %08x %08x 2>&1", "/usr/bin/atos -d -o '%s' -l %08x %08x 2>&1" }; struct stat st; UV i; for (i = 0; i < C_ARRAY_LENGTH(tools); i++) { if (stat(tools[i], &st) == 0 && S_ISREG(st.st_mode)) { ctx->tool = tools[i]; ctx->format = formats[i]; break; } } if (ctx->tool == NULL) { ctx->unavail = TRUE; return; } } if (ctx->fname == NULL || strNE(dl_info->dli_fname, ctx->fname)) { ctx->fname = dl_info->dli_fname; ctx->object_base_addr = dl_info->dli_fbase; } } /* Given an output buffer end |p| and its |start|, matches * for the atos output, extracting the source code location * and returning non-NULL if possible, returning NULL otherwise. */ static const char* atos_parse(const char* p, const char* start, STRLEN* source_name_size, STRLEN* source_line) { /* atos() output is something like: * perl_parse (in miniperl) (perl.c:2314)\n\n". * We cannot use Perl regular expressions, because we need to * stay low-level. Therefore here we have a rolled-out version * of a state machine which matches _backwards_from_the_end_ and * if there's a success, returns the starts of the filename, * also setting the filename size and the source line number. * The matched regular expression is roughly "\(.*:\d+\)\s*$" */ const char* source_number_start; const char* source_name_end; const char* source_line_end = start; const char* close_paren; UV uv; /* Skip trailing whitespace. */ while (p > start && isSPACE(*p)) p--; /* Now we should be at the close paren. */ if (p == start || *p != ')') return NULL; close_paren = p; p--; /* Now we should be in the line number. */ if (p == start || !isDIGIT(*p)) return NULL; /* Skip over the digits. */ while (p > start && isDIGIT(*p)) p--; /* Now we should be at the colon. */ if (p == start || *p != ':') return NULL; source_number_start = p + 1; source_name_end = p; /* Just beyond the end. */ p--; /* Look for the open paren. */ while (p > start && *p != '(') p--; if (p == start) return NULL; p++; *source_name_size = source_name_end - p; if (grok_atoUV(source_number_start, &uv, &source_line_end) && source_line_end == close_paren && uv <= PERL_INT_MAX ) { *source_line = (STRLEN)uv; return p; } return NULL; } /* Given a raw frame, read a pipe from the symbolicator (that's the * technical term) atos, reads the result, and parses the source code * location. We must stay low-level, so we use snprintf(), pipe(), * and fread(), and then also parse the output ourselves. */ static void atos_symbolize(atos_context* ctx, void* raw_frame, char** source_name, STRLEN* source_name_size, STRLEN* source_line) { char cmd[1024]; const char* p; Size_t cnt; if (ctx->unavail) return; /* Simple security measure: if there's any funny business with * the object name (used as "-o '%s'" ), leave since at least * partially the user controls it. */ for (p = ctx->fname; *p; p++) { if (*p == '\'' || isCNTRL(*p)) { ctx->unavail = TRUE; return; } } cnt = snprintf(cmd, sizeof(cmd), ctx->format, ctx->fname, ctx->object_base_addr, raw_frame); if (cnt < sizeof(cmd)) { /* Undo nostdio.h #defines that disable stdio. * This is somewhat naughty, but is used elsewhere * in the core, and affects only OS X. */ #undef FILE #undef popen #undef fread #undef pclose FILE* fp = popen(cmd, "r"); /* At the moment we open a new pipe for each stack frame. * This is naturally somewhat slow, but hopefully generating * stack traces is never going to in a performance critical path. * * We could play tricks with atos by batching the stack * addresses to be resolved: atos can either take multiple * addresses from the command line, or read addresses from * a file (though the mess of creating temporary files would * probably negate much of any possible speedup). * * Normally there are only two objects present in the backtrace: * perl itself, and the libdyld.dylib. (Note that the object * filenames contain the full pathname, so perl may not always * be in the same place.) Whenever the object in the * backtrace changes, the base address also changes. * * The problem with batching the addresses, though, would be * matching the results with the addresses: the parsing of * the results is already painful enough with a single address. */ if (fp) { char out[1024]; UV cnt = fread(out, 1, sizeof(out), fp); if (cnt < sizeof(out)) { const char* p = atos_parse(out + cnt - 1, out, source_name_size, source_line); if (p) { Newx(*source_name, *source_name_size, char); Copy(p, *source_name, *source_name_size, char); } } pclose(fp); } } } #endif /* #ifdef PERL_DARWIN */ /* =for apidoc get_c_backtrace Collects the backtrace (aka "stacktrace") into a single linear malloced buffer, which the caller B<must> C<Perl_free_c_backtrace()>. Scans the frames back by S<C<depth + skip>>, then drops the C<skip> innermost, returning at most C<depth> frames. =cut */ Perl_c_backtrace* Perl_get_c_backtrace(pTHX_ int depth, int skip) { /* Note that here we must stay as low-level as possible: Newx(), * Copy(), Safefree(); since we may be called from anywhere, * so we should avoid higher level constructs like SVs or AVs. * * Since we are using safesysmalloc() via Newx(), don't try * getting backtrace() there, unless you like deep recursion. */ /* Currently only implemented with backtrace() and dladdr(), * for other platforms NULL is returned. */ #if defined(HAS_BACKTRACE) && defined(HAS_DLADDR) /* backtrace() is available via <execinfo.h> in glibc and in most * modern BSDs; dladdr() is available via <dlfcn.h>. */ /* We try fetching this many frames total, but then discard * the |skip| first ones. For the remaining ones we will try * retrieving more information with dladdr(). */ int try_depth = skip + depth; /* The addresses (program counters) returned by backtrace(). */ void** raw_frames; /* Retrieved with dladdr() from the addresses returned by backtrace(). */ Dl_info* dl_infos; /* Sizes _including_ the terminating \0 of the object name * and symbol name strings. */ STRLEN* object_name_sizes; STRLEN* symbol_name_sizes; #ifdef USE_BFD /* The symbol names comes either from dli_sname, * or if using BFD, they can come from BFD. */ char** symbol_names; #endif /* The source code location information. Dug out with e.g. BFD. */ char** source_names; STRLEN* source_name_sizes; STRLEN* source_lines; Perl_c_backtrace* bt = NULL; /* This is what will be returned. */ int got_depth; /* How many frames were returned from backtrace(). */ UV frame_count = 0; /* How many frames we return. */ UV total_bytes = 0; /* The size of the whole returned backtrace. */ #ifdef USE_BFD bfd_context bfd_ctx; #endif #ifdef PERL_DARWIN atos_context atos_ctx; #endif /* Here are probably possibilities for optimizing. We could for * example have a struct that contains most of these and then * allocate |try_depth| of them, saving a bunch of malloc calls. * Note, however, that |frames| could not be part of that struct * because backtrace() will want an array of just them. Also be * careful about the name strings. */ Newx(raw_frames, try_depth, void*); Newx(dl_infos, try_depth, Dl_info); Newx(object_name_sizes, try_depth, STRLEN); Newx(symbol_name_sizes, try_depth, STRLEN); Newx(source_names, try_depth, char*); Newx(source_name_sizes, try_depth, STRLEN); Newx(source_lines, try_depth, STRLEN); #ifdef USE_BFD Newx(symbol_names, try_depth, char*); #endif /* Get the raw frames. */ got_depth = (int)backtrace(raw_frames, try_depth); /* We use dladdr() instead of backtrace_symbols() because we want * the full details instead of opaque strings. This is useful for * two reasons: () the details are needed for further symbolic * digging, for example in OS X (2) by having the details we fully * control the output, which in turn is useful when more platforms * are added: we can keep out output "portable". */ /* We want a single linear allocation, which can then be freed * with a single swoop. We will do the usual trick of first * walking over the structure and seeing how much we need to * allocate, then allocating, and then walking over the structure * the second time and populating it. */ /* First we must compute the total size of the buffer. */ total_bytes = sizeof(Perl_c_backtrace_header); if (got_depth > skip) { int i; #ifdef USE_BFD bfd_init(); /* Is this safe to call multiple times? */ Zero(&bfd_ctx, 1, bfd_context); #endif #ifdef PERL_DARWIN Zero(&atos_ctx, 1, atos_context); #endif for (i = skip; i < try_depth; i++) { Dl_info* dl_info = &dl_infos[i]; object_name_sizes[i] = 0; source_names[i] = NULL; source_name_sizes[i] = 0; source_lines[i] = 0; /* Yes, zero from dladdr() is failure. */ if (dladdr(raw_frames[i], dl_info)) { total_bytes += sizeof(Perl_c_backtrace_frame); object_name_sizes[i] = dl_info->dli_fname ? strlen(dl_info->dli_fname) : 0; symbol_name_sizes[i] = dl_info->dli_sname ? strlen(dl_info->dli_sname) : 0; #ifdef USE_BFD bfd_update(&bfd_ctx, dl_info); bfd_symbolize(&bfd_ctx, raw_frames[i], &symbol_names[i], &symbol_name_sizes[i], &source_names[i], &source_name_sizes[i], &source_lines[i]); #endif #if PERL_DARWIN atos_update(&atos_ctx, dl_info); atos_symbolize(&atos_ctx, raw_frames[i], &source_names[i], &source_name_sizes[i], &source_lines[i]); #endif /* Plus ones for the terminating \0. */ total_bytes += object_name_sizes[i] + 1; total_bytes += symbol_name_sizes[i] + 1; total_bytes += source_name_sizes[i] + 1; frame_count++; } else { break; } } #ifdef USE_BFD Safefree(bfd_ctx.bfd_syms); #endif } /* Now we can allocate and populate the result buffer. */ Newxc(bt, total_bytes, char, Perl_c_backtrace); Zero(bt, total_bytes, char); bt->header.frame_count = frame_count; bt->header.total_bytes = total_bytes; if (frame_count > 0) { Perl_c_backtrace_frame* frame = bt->frame_info; char* name_base = (char *)(frame + frame_count); char* name_curr = name_base; /* Outputting the name strings here. */ UV i; for (i = skip; i < skip + frame_count; i++) { Dl_info* dl_info = &dl_infos[i]; frame->addr = raw_frames[i]; frame->object_base_addr = dl_info->dli_fbase; frame->symbol_addr = dl_info->dli_saddr; /* Copies a string, including the \0, and advances the name_curr. * Also copies the start and the size to the frame. */ #define PERL_C_BACKTRACE_STRCPY(frame, doffset, src, dsize, size) \ if (size && src) \ Copy(src, name_curr, size, char); \ frame->doffset = name_curr - (char*)bt; \ frame->dsize = size; \ name_curr += size; \ *name_curr++ = 0; PERL_C_BACKTRACE_STRCPY(frame, object_name_offset, dl_info->dli_fname, object_name_size, object_name_sizes[i]); #ifdef USE_BFD PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset, symbol_names[i], symbol_name_size, symbol_name_sizes[i]); Safefree(symbol_names[i]); #else PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset, dl_info->dli_sname, symbol_name_size, symbol_name_sizes[i]); #endif PERL_C_BACKTRACE_STRCPY(frame, source_name_offset, source_names[i], source_name_size, source_name_sizes[i]); Safefree(source_names[i]); #undef PERL_C_BACKTRACE_STRCPY frame->source_line_number = source_lines[i]; frame++; } assert(total_bytes == (UV)(sizeof(Perl_c_backtrace_header) + frame_count * sizeof(Perl_c_backtrace_frame) + name_curr - name_base)); } #ifdef USE_BFD Safefree(symbol_names); if (bfd_ctx.abfd) { bfd_close(bfd_ctx.abfd); } #endif Safefree(source_lines); Safefree(source_name_sizes); Safefree(source_names); Safefree(symbol_name_sizes); Safefree(object_name_sizes); /* Assuming the strings returned by dladdr() are pointers * to read-only static memory (the object file), so that * they do not need freeing (and cannot be). */ Safefree(dl_infos); Safefree(raw_frames); return bt; #else PERL_UNUSED_ARGV(depth); PERL_UNUSED_ARGV(skip); return NULL; #endif } /* =for apidoc free_c_backtrace Deallocates a backtrace received from get_c_bracktrace. =cut */ /* =for apidoc get_c_backtrace_dump Returns a SV containing a dump of C<depth> frames of the call stack, skipping the C<skip> innermost ones. C<depth> of 20 is usually enough. The appended output looks like: ... 1 10e004812:0082 Perl_croak util.c:1716 /usr/bin/perl 2 10df8d6d2:1d72 perl_parse perl.c:3975 /usr/bin/perl ... The fields are tab-separated. The first column is the depth (zero being the innermost non-skipped frame). In the hex:offset, the hex is where the program counter was in C<S_parse_body>, and the :offset (might be missing) tells how much inside the C<S_parse_body> the program counter was. The C<util.c:1716> is the source code file and line number. The F</usr/bin/perl> is obvious (hopefully). Unknowns are C<"-">. Unknowns can happen unfortunately quite easily: if the platform doesn't support retrieving the information; if the binary is missing the debug information; if the optimizer has transformed the code by for example inlining. =cut */ SV* Perl_get_c_backtrace_dump(pTHX_ int depth, int skip) { Perl_c_backtrace* bt; bt = get_c_backtrace(depth, skip + 1 /* Hide ourselves. */); if (bt) { Perl_c_backtrace_frame* frame; SV* dsv = newSVpvs(""); UV i; for (i = 0, frame = bt->frame_info; i < bt->header.frame_count; i++, frame++) { Perl_sv_catpvf(aTHX_ dsv, "%d", (int)i); Perl_sv_catpvf(aTHX_ dsv, "\t%p", frame->addr ? frame->addr : "-"); /* Symbol (function) names might disappear without debug info. * * The source code location might disappear in case of the * optimizer inlining or otherwise rearranging the code. */ if (frame->symbol_addr) { Perl_sv_catpvf(aTHX_ dsv, ":%04x", (int) ((char*)frame->addr - (char*)frame->symbol_addr)); } Perl_sv_catpvf(aTHX_ dsv, "\t%s", frame->symbol_name_size && frame->symbol_name_offset ? (char*)bt + frame->symbol_name_offset : "-"); if (frame->source_name_size && frame->source_name_offset && frame->source_line_number) { Perl_sv_catpvf(aTHX_ dsv, "\t%s:%" UVuf, (char*)bt + frame->source_name_offset, (UV)frame->source_line_number); } else { Perl_sv_catpvf(aTHX_ dsv, "\t-"); } Perl_sv_catpvf(aTHX_ dsv, "\t%s", frame->object_name_size && frame->object_name_offset ? (char*)bt + frame->object_name_offset : "-"); /* The frame->object_base_addr is not output, * but it is used for symbolizing/symbolicating. */ sv_catpvs(dsv, "\n"); } Perl_free_c_backtrace(bt); return dsv; } return NULL; } /* =for apidoc dump_c_backtrace Dumps the C backtrace to the given C<fp>. Returns true if a backtrace could be retrieved, false if not. =cut */ bool Perl_dump_c_backtrace(pTHX_ PerlIO* fp, int depth, int skip) { SV* sv; PERL_ARGS_ASSERT_DUMP_C_BACKTRACE; sv = Perl_get_c_backtrace_dump(aTHX_ depth, skip); if (sv) { sv_2mortal(sv); PerlIO_printf(fp, "%s", SvPV_nolen(sv)); return TRUE; } return FALSE; } #endif /* #ifdef USE_C_BACKTRACE */ #ifdef PERL_TSA_ACTIVE /* pthread_mutex_t and perl_mutex are typedef equivalent * so casting the pointers is fine. */ int perl_tsa_mutex_lock(perl_mutex* mutex) { return pthread_mutex_lock((pthread_mutex_t *) mutex); } int perl_tsa_mutex_unlock(perl_mutex* mutex) { return pthread_mutex_unlock((pthread_mutex_t *) mutex); } int perl_tsa_mutex_destroy(perl_mutex* mutex) { return pthread_mutex_destroy((pthread_mutex_t *) mutex); } #endif #ifdef USE_DTRACE /* log a sub call or return */ void Perl_dtrace_probe_call(pTHX_ CV *cv, bool is_call) { const char *func; const char *file; const char *stash; const COP *start; line_t line; PERL_ARGS_ASSERT_DTRACE_PROBE_CALL; if (CvNAMED(cv)) { HEK *hek = CvNAME_HEK(cv); func = HEK_KEY(hek); } else { GV *gv = CvGV(cv); func = GvENAME(gv); } start = (const COP *)CvSTART(cv); file = CopFILE(start); line = CopLINE(start); stash = CopSTASHPV(start); if (is_call) { PERL_SUB_ENTRY(func, file, line, stash); } else { PERL_SUB_RETURN(func, file, line, stash); } } /* log a require file loading/loaded */ void Perl_dtrace_probe_load(pTHX_ const char *name, bool is_loading) { PERL_ARGS_ASSERT_DTRACE_PROBE_LOAD; if (is_loading) { PERL_LOADING_FILE(name); } else { PERL_LOADED_FILE(name); } } /* log an op execution */ void Perl_dtrace_probe_op(pTHX_ const OP *op) { PERL_ARGS_ASSERT_DTRACE_PROBE_OP; PERL_OP_ENTRY(OP_NAME(op)); } /* log a compile/run phase change */ void Perl_dtrace_probe_phase(pTHX_ enum perl_phase phase) { const char *ph_old = PL_phase_names[PL_phase]; const char *ph_new = PL_phase_names[phase]; PERL_PHASE_CHANGE(ph_new, ph_old); } #endif /* * ex: set ts=8 sts=4 sw=4 et: */
./CrossVul/dataset_final_sorted/CWE-119/c/good_410_0
crossvul-cpp_data_bad_1_1
/* Copyright (c) 2015, Cisco Systems All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <math.h> #include <string.h> #include <memory.h> #include <assert.h> #include "global.h" #include "getvlc.h" #include "common_block.h" #include "inter_prediction.h" extern int zigzag16[16]; extern int zigzag64[64]; extern int zigzag256[256]; int YPOS, XPOS; #undef TEMPLATE #define TEMPLATE(func) (decoder_info->bitdepth == 8 ? func ## _lbd : func ## _hbd) void read_sequence_header(decoder_info_t *decoder_info, stream_t *stream) { decoder_info->width = get_flc(16, stream); decoder_info->height = get_flc(16, stream); decoder_info->log2_sb_size = get_flc(3, stream); decoder_info->pb_split = get_flc(1, stream); decoder_info->tb_split_enable = get_flc(1, stream); decoder_info->max_num_ref = get_flc(2, stream) + 1; decoder_info->interp_ref = get_flc(2, stream); decoder_info->max_delta_qp = get_flc(1, stream); decoder_info->deblocking = get_flc(1, stream); decoder_info->clpf = get_flc(1, stream); decoder_info->use_block_contexts = get_flc(1, stream); decoder_info->bipred = get_flc(2, stream); decoder_info->qmtx = get_flc(1, stream); if (decoder_info->qmtx) { decoder_info->qmtx_offset = get_flc(6, stream) - 32; } decoder_info->subsample = get_flc(2, stream); decoder_info->subsample = // 0: 400 1: 420 2: 422 3: 444 (decoder_info->subsample & 1) * 20 + (decoder_info->subsample & 2) * 22 + ((decoder_info->subsample & 3) == 3) * 2 + 400; decoder_info->num_reorder_pics = get_flc(4, stream); if (decoder_info->subsample != 400) { decoder_info->cfl_intra = get_flc(1, stream); decoder_info->cfl_inter = get_flc(1, stream); } decoder_info->bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->bitdepth == 10) decoder_info->bitdepth += 2 * get_flc(1, stream); decoder_info->input_bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->input_bitdepth == 10) decoder_info->input_bitdepth += 2 * get_flc(1, stream); } void read_frame_header(decoder_info_t *dec_info, stream_t *stream) { frame_info_t *frame_info = &dec_info->frame_info; frame_info->frame_type = get_flc(1, stream); frame_info->qp = get_flc(8, stream); frame_info->num_intra_modes = get_flc(4, stream); if (frame_info->frame_type != I_FRAME) { frame_info->num_ref = get_flc(2, stream) + 1; int r; for (r = 0; r < frame_info->num_ref; r++) { frame_info->ref_array[r] = get_flc(6, stream) - 1; } if (frame_info->num_ref == 2 && frame_info->ref_array[0] == -1) { frame_info->ref_array[frame_info->num_ref++] = get_flc(5, stream) - 1; } } else { frame_info->num_ref = 0; } frame_info->display_frame_num = get_flc(16, stream); #if CDEF dec_info->cdef_damping[1] = dec_info->cdef_damping[0] = get_flc(2, stream) + 3; dec_info->cdef_bits = get_flc(2, stream); for (int i = 0; i < (1 << dec_info->cdef_bits); i++) { dec_info->cdef_presets[i].pri_strength[0] = get_flc(4, stream); dec_info->cdef_presets[i].skip_condition[0] = get_flc(1, stream); dec_info->cdef_presets[i].sec_strength[0] = get_flc(2, stream); if (dec_info->subsample != 400) { dec_info->cdef_presets[i].pri_strength[1] = get_flc(4, stream); dec_info->cdef_presets[i].skip_condition[1] = get_flc(1, stream); dec_info->cdef_presets[i].sec_strength[1] = get_flc(2, stream); } } #endif } void read_mv(stream_t *stream,mv_t *mv,mv_t *mvp) { mv_t mvd; int mvabs, mvsign = 0; /* MVX */ if ((mvabs = get_vlc(7, stream))) mvsign = get_flc(1, stream); mvd.x = mvabs * (mvsign ? -1 : 1); mv->x = mvp->x + mvd.x; /* MVY */ if ((mvabs = get_vlc(7, stream))) mvsign = get_flc(1, stream); mvd.y = mvabs * (mvsign ? -1 : 1); mv->y = mvp->y + mvd.y; } void read_coeff(stream_t *stream,int16_t *coeff,int size,int type){ int16_t scoeff[MAX_QUANT_SIZE*MAX_QUANT_SIZE]; int i,j,levelFlag,sign,level,pos,run,tmp,code; int qsize = min(size,MAX_QUANT_SIZE); int N = qsize*qsize; int level_mode; int chroma_flag = type&1; int intra_flag = (type>>1)&1; int vlc_adaptive = intra_flag && !chroma_flag; /* Initialize arrays */ memset(scoeff,0,N*sizeof(int16_t)); memset(coeff,0,size*size*sizeof(int16_t)); pos = 0; /* Use one bit to signal chroma/last_pos=1/level=1 */ if (chroma_flag==1){ int tmp = get_flc(1, stream); if (tmp){ sign = get_flc(1, stream); scoeff[pos] = sign ? -1 : 1; pos = N; } } /* Initiate forward scan */ level_mode = 1; level = 1; while (pos < N){ if (level_mode){ /* Level-mode */ while (pos < N && level > 0){ level = get_vlc(vlc_adaptive,stream); if (level){ sign = get_flc(1, stream); } else{ sign = 1; } scoeff[pos] = sign ? -level : level; if (chroma_flag==0) vlc_adaptive = level > 3; pos++; } } if (pos >= N){ break; } /* Run-mode */ int eob; int eob_pos = chroma_flag ? 0 : 2; if (chroma_flag && size <= 8) code = get_vlc(10, stream); else code = get_vlc(6, stream); eob = code == eob_pos; if (eob) { break; } if (code > eob_pos) code -= 1; levelFlag = (code % 5) == 4; if (levelFlag) run = code / 5; else run = 4*(code/5) + code % 5; pos += run; /* Decode level and sign */ if (levelFlag){ tmp = get_vlc(0,stream); sign = tmp&1; level = (tmp>>1)+2; } else{ level = 1; sign = get_flc(1, stream); } scoeff[pos] = sign ? -level : level; level_mode = level > 1; //Set level_mode pos++; } //while pos < N /* Perform inverse zigzag scan */ int *zigzagptr = zigzag64; if (qsize==4) zigzagptr = zigzag16; else if (qsize==8) zigzagptr = zigzag64; else if (qsize==16) zigzagptr = zigzag256; for (i=0;i<qsize;i++){ for (j=0;j<qsize;j++){ coeff[i*qsize + j] = scoeff[zigzagptr[i*qsize + j]]; } } } int read_delta_qp(stream_t *stream){ int abs_delta_qp,sign_delta_qp,delta_qp; sign_delta_qp = 0; abs_delta_qp = get_vlc(0,stream); if (abs_delta_qp > 0) sign_delta_qp = get_flc(1, stream); delta_qp = sign_delta_qp ? -abs_delta_qp : abs_delta_qp; return delta_qp; } int read_block(decoder_info_t *decoder_info,stream_t *stream,block_info_dec_t *block_info, frame_type_t frame_type) { int width = decoder_info->width; int height = decoder_info->height; int bit_start; int code,tb_split; int pb_part=0; cbp_t cbp; int stat_frame_type = decoder_info->bit_count.stat_frame_type; //TODO: Use only one variable for frame type int size = block_info->block_pos.size; int ypos = block_info->block_pos.ypos; int xpos = block_info->block_pos.xpos; YPOS = ypos; XPOS = xpos; int sizeY = size; int sizeC = size>>block_info->sub; mv_t mv,zerovec; mv_t mvp; mv_t mv_arr[4]; //TODO: Use mv_arr0 instead mv_t mv_arr0[4]; mv_t mv_arr1[4]; block_mode_t mode; intra_mode_t intra_mode = MODE_DC; int16_t *coeff_y = block_info->coeffq_y; int16_t *coeff_u = block_info->coeffq_u; int16_t *coeff_v = block_info->coeffq_v; zerovec.y = zerovec.x = 0; bit_start = stream->bitcnt; mode = decoder_info->mode; int coeff_block_type = (mode == MODE_INTRA)<<1; /* Initialize bit counter for statistical purposes */ bit_start = stream->bitcnt; if (mode == MODE_SKIP){ /* Derive skip vector candidates and number of skip vector candidates from neighbour blocks */ mv_t mv_skip[MAX_NUM_SKIP]; int num_skip_vec,skip_idx; inter_pred_t skip_candidates[MAX_NUM_SKIP]; num_skip_vec = TEMPLATE(get_mv_skip)(ypos, xpos, width, height, size, size, 1 << decoder_info->log2_sb_size, decoder_info->deblock_data, skip_candidates); if (decoder_info->bit_count.stat_frame_type == B_FRAME && decoder_info->interp_ref == 2) { num_skip_vec = TEMPLATE(get_mv_skip_temp)(decoder_info->width, decoder_info->frame_info.phase, decoder_info->num_reorder_pics + 1, &block_info->block_pos, decoder_info->deblock_data, skip_candidates); } for (int idx = 0; idx < num_skip_vec; idx++) { mv_skip[idx] = skip_candidates[idx].mv0; } /* Decode skip index */ if (num_skip_vec == 4) skip_idx = get_flc(2, stream); else if (num_skip_vec == 3){ skip_idx = get_vlc(12, stream); } else if (num_skip_vec == 2){ skip_idx = get_flc(1, stream); } else skip_idx = 0; decoder_info->bit_count.skip_idx[stat_frame_type] += (stream->bitcnt - bit_start); block_info->num_skip_vec = num_skip_vec; block_info->block_param.skip_idx = skip_idx; if (skip_idx == num_skip_vec) mv = mv_skip[0]; else mv = mv_skip[skip_idx]; mv_arr[0] = mv; mv_arr[1] = mv; mv_arr[2] = mv; mv_arr[3] = mv; block_info->block_param.ref_idx0 = skip_candidates[skip_idx].ref_idx0; block_info->block_param.ref_idx1 = skip_candidates[skip_idx].ref_idx1; for (int i = 0; i < 4; i++) { mv_arr0[i] = skip_candidates[skip_idx].mv0; mv_arr1[i] = skip_candidates[skip_idx].mv1; } block_info->block_param.dir = skip_candidates[skip_idx].bipred_flag; } else if (mode == MODE_MERGE){ /* Derive skip vector candidates and number of skip vector candidates from neighbour blocks */ mv_t mv_skip[MAX_NUM_SKIP]; int num_skip_vec,skip_idx; inter_pred_t merge_candidates[MAX_NUM_SKIP]; num_skip_vec = TEMPLATE(get_mv_merge)(ypos, xpos, width, height, size, size, 1 << decoder_info->log2_sb_size, decoder_info->deblock_data, merge_candidates); for (int idx = 0; idx < num_skip_vec; idx++) { mv_skip[idx] = merge_candidates[idx].mv0; } /* Decode skip index */ if (num_skip_vec == 4) skip_idx = get_flc(2, stream); else if (num_skip_vec == 3){ skip_idx = get_vlc(12, stream); } else if (num_skip_vec == 2){ skip_idx = get_flc(1, stream); } else skip_idx = 0; decoder_info->bit_count.skip_idx[stat_frame_type] += (stream->bitcnt - bit_start); block_info->num_skip_vec = num_skip_vec; block_info->block_param.skip_idx = skip_idx; if (skip_idx == num_skip_vec) mv = mv_skip[0]; else mv = mv_skip[skip_idx]; mv_arr[0] = mv; mv_arr[1] = mv; mv_arr[2] = mv; mv_arr[3] = mv; block_info->block_param.ref_idx0 = merge_candidates[skip_idx].ref_idx0; block_info->block_param.ref_idx1 = merge_candidates[skip_idx].ref_idx1; for (int i = 0; i < 4; i++) { mv_arr0[i] = merge_candidates[skip_idx].mv0; mv_arr1[i] = merge_candidates[skip_idx].mv1; } block_info->block_param.dir = merge_candidates[skip_idx].bipred_flag; } else if (mode==MODE_INTER){ int ref_idx; if (decoder_info->pb_split){ /* Decode PU partition */ pb_part = get_vlc(13, stream); } else{ pb_part = 0; } block_info->block_param.pb_part = pb_part; if (decoder_info->frame_info.num_ref > 1){ ref_idx = decoder_info->ref_idx; } else{ ref_idx = 0; } //if (mode==MODE_INTER) decoder_info->bit_count.size_and_ref_idx[stat_frame_type][log2i(size)-3][ref_idx] += 1; mvp = TEMPLATE(get_mv_pred)(ypos,xpos,width,height,size,size,1<<decoder_info->log2_sb_size,ref_idx,decoder_info->deblock_data); /* Deode motion vectors for each prediction block */ mv_t mvp2 = mvp; if (pb_part==0){ read_mv(stream,&mv_arr[0],&mvp2); mv_arr[1] = mv_arr[0]; mv_arr[2] = mv_arr[0]; mv_arr[3] = mv_arr[0]; } else if(pb_part==1){ //HOR read_mv(stream,&mv_arr[0],&mvp2); mvp2 = mv_arr[0]; read_mv(stream,&mv_arr[2],&mvp2); mv_arr[1] = mv_arr[0]; mv_arr[3] = mv_arr[2]; } else if(pb_part==2){ //VER read_mv(stream,&mv_arr[0],&mvp2); mvp2 = mv_arr[0]; read_mv(stream,&mv_arr[1],&mvp2); mv_arr[2] = mv_arr[0]; mv_arr[3] = mv_arr[1]; } else{ read_mv(stream,&mv_arr[0],&mvp2); mvp2 = mv_arr[0]; read_mv(stream,&mv_arr[1],&mvp2); read_mv(stream,&mv_arr[2],&mvp2); read_mv(stream,&mv_arr[3],&mvp2); } decoder_info->bit_count.mv[stat_frame_type] += (stream->bitcnt - bit_start); block_info->block_param.ref_idx0 = ref_idx; block_info->block_param.ref_idx1 = ref_idx; block_info->block_param.dir = 0; } else if (mode==MODE_BIPRED){ int ref_idx = 0; mvp = TEMPLATE(get_mv_pred)(ypos,xpos,width,height,size,size,1 << decoder_info->log2_sb_size, ref_idx,decoder_info->deblock_data); /* Deode motion vectors */ mv_t mvp2 = mvp; #if BIPRED_PART if (decoder_info->pb_split) { /* Decode PU partition */ pb_part = get_vlc(13, stream); } else { pb_part = 0; } #else pb_part = 0; #endif block_info->block_param.pb_part = pb_part; if (pb_part == 0) { read_mv(stream, &mv_arr0[0], &mvp2); mv_arr0[1] = mv_arr0[0]; mv_arr0[2] = mv_arr0[0]; mv_arr0[3] = mv_arr0[0]; } else { mv_arr0[0] = mvp2; mv_arr0[1] = mvp2; mv_arr0[2] = mvp2; mv_arr0[3] = mvp2; } if (decoder_info->bit_count.stat_frame_type == B_FRAME) mvp2 = mv_arr0[0]; if (pb_part == 0) { read_mv(stream, &mv_arr1[0], &mvp2); mv_arr1[1] = mv_arr1[0]; mv_arr1[2] = mv_arr1[0]; mv_arr1[3] = mv_arr1[0]; } else if (pb_part == 1) { //HOR read_mv(stream, &mv_arr1[0], &mvp2); mvp2 = mv_arr1[0]; read_mv(stream, &mv_arr1[2], &mvp2); mv_arr1[1] = mv_arr1[0]; mv_arr1[3] = mv_arr1[2]; } else if (pb_part == 2) { //VER read_mv(stream, &mv_arr1[0], &mvp2); mvp2 = mv_arr1[0]; read_mv(stream, &mv_arr1[1], &mvp2); mv_arr1[2] = mv_arr1[0]; mv_arr1[3] = mv_arr1[1]; } else { read_mv(stream, &mv_arr1[0], &mvp2); mvp2 = mv_arr1[0]; read_mv(stream, &mv_arr1[1], &mvp2); read_mv(stream, &mv_arr1[2], &mvp2); read_mv(stream, &mv_arr1[3], &mvp2); } if (decoder_info->bit_count.stat_frame_type == B_FRAME) { block_info->block_param.ref_idx0 = 0; block_info->block_param.ref_idx1 = 1; if (decoder_info->frame_info.interp_ref > 0) { block_info->block_param.ref_idx0 += 1; block_info->block_param.ref_idx1 += 1; } } else{ if (decoder_info->frame_info.num_ref == 2) { int code = get_vlc(13, stream); block_info->block_param.ref_idx0 = (code >> 1) & 1; block_info->block_param.ref_idx1 = (code >> 0) & 1; } else { int code = get_vlc(10, stream); block_info->block_param.ref_idx0 = (code >> 2) & 3; block_info->block_param.ref_idx1 = (code >> 0) & 3; } } block_info->block_param.dir = 2; int combined_ref = block_info->block_param.ref_idx0 * decoder_info->frame_info.num_ref + block_info->block_param.ref_idx1; decoder_info->bit_count.bi_ref[stat_frame_type][combined_ref] += 1; decoder_info->bit_count.mv[stat_frame_type] += (stream->bitcnt - bit_start); } else if (mode==MODE_INTRA){ /* Decode intra prediction mode */ if (decoder_info->frame_info.num_intra_modes<=4){ intra_mode = get_flc(2, stream); } else { intra_mode = get_vlc(8, stream); } decoder_info->bit_count.intra_mode[stat_frame_type] += (stream->bitcnt - bit_start); decoder_info->bit_count.size_and_intra_mode[stat_frame_type][log2i(size)-3][intra_mode] += 1; block_info->block_param.intra_mode = intra_mode; for (int i=0;i<4;i++){ mv_arr[i] = zerovec; //Note: This is necessary for derivation of mvp and mv_skip } block_info->block_param.ref_idx0 = 0; block_info->block_param.ref_idx1 = 0; block_info->block_param.dir = -1; } if (mode!=MODE_SKIP){ int tmp; int cbp_table[8] = {1,0,5,2,6,3,7,4}; code = 0; if (decoder_info->subsample == 400) { tb_split = cbp.u = cbp.v = 0; cbp.y = get_flc(1,stream); if (decoder_info->tb_split_enable && cbp.y) { // 0: cbp=split=0, 10: cbp=1,split=0, 11: split=1 tb_split = get_flc(1,stream); cbp.y &= !tb_split; } } else { bit_start = stream->bitcnt; code = get_vlc(0,stream); int off = (mode == MODE_MERGE) ? 1 : 2; if (decoder_info->tb_split_enable) { tb_split = code == off; if (code > off) code -= 1; if (tb_split) decoder_info->bit_count.cbp2_stat[0][stat_frame_type][mode-1][log2i(size)-3][8] += 1; } else{ tb_split = 0; } } block_info->block_param.tb_split = tb_split; decoder_info->bit_count.cbp[stat_frame_type] += (stream->bitcnt - bit_start); if (tb_split == 0){ if (decoder_info->subsample != 400) { tmp = 0; if (mode==MODE_MERGE){ if (code==7) code = 1; else if (code>0) code = code+1; } else { if (decoder_info->block_context->cbp == 0 && code < 2) { code = 1 - code; } } while (tmp < 8 && code != cbp_table[tmp]) tmp++; decoder_info->bit_count.cbp2_stat[max(0,decoder_info->block_context->cbp)][stat_frame_type][mode-1][log2i(size)-3][tmp] += 1; cbp.y = ((tmp>>0)&1); cbp.u = ((tmp>>1)&1); cbp.v = ((tmp>>2)&1); } block_info->cbp = cbp; if (cbp.y){ bit_start = stream->bitcnt; read_coeff(stream,coeff_y,sizeY,coeff_block_type|0); decoder_info->bit_count.coeff_y[stat_frame_type] += (stream->bitcnt - bit_start); } else memset(coeff_y,0,sizeY*sizeY*sizeof(int16_t)); if (cbp.u){ bit_start = stream->bitcnt; read_coeff(stream,coeff_u,sizeC,coeff_block_type|1); decoder_info->bit_count.coeff_u[stat_frame_type] += (stream->bitcnt - bit_start); } else memset(coeff_u,0,sizeC*sizeC*sizeof(int16_t)); if (cbp.v){ bit_start = stream->bitcnt; read_coeff(stream,coeff_v,sizeC,coeff_block_type|1); decoder_info->bit_count.coeff_v[stat_frame_type] += (stream->bitcnt - bit_start); } else memset(coeff_v,0,sizeC*sizeC*sizeof(int16_t)); } else{ if (sizeC > 4){ int index; int16_t *coeff; /* Loop over 4 TUs */ for (index=0;index<4;index++){ bit_start = stream->bitcnt; code = get_vlc(0,stream); int tmp = 0; while (code != cbp_table[tmp] && tmp < 8) tmp++; if (decoder_info->block_context->cbp==0 && tmp < 2) tmp = 1-tmp; cbp.y = ((tmp>>0)&1); cbp.u = ((tmp>>1)&1); cbp.v = ((tmp>>2)&1); /* Updating statistics for CBP */ decoder_info->bit_count.cbp[stat_frame_type] += (stream->bitcnt - bit_start); decoder_info->bit_count.cbp_stat[stat_frame_type][cbp.y + (cbp.u<<1) + (cbp.v<<2)] += 1; /* Decode coefficients for this TU */ /* Y */ coeff = coeff_y + index*sizeY/2*sizeY/2; if (cbp.y){ bit_start = stream->bitcnt; read_coeff(stream,coeff,sizeY/2,coeff_block_type|0); decoder_info->bit_count.coeff_y[stat_frame_type] += (stream->bitcnt - bit_start); } else{ memset(coeff,0,sizeY/2*sizeY/2*sizeof(int16_t)); } /* U */ coeff = coeff_u + index*sizeC/2*sizeC/2; if (cbp.u){ bit_start = stream->bitcnt; read_coeff(stream,coeff,sizeC/2,coeff_block_type|1); decoder_info->bit_count.coeff_u[stat_frame_type] += (stream->bitcnt - bit_start); } else{ memset(coeff,0,sizeC/2*sizeC/2*sizeof(int16_t)); } /* V */ coeff = coeff_v + index*sizeC/2*sizeC/2; if (cbp.v){ bit_start = stream->bitcnt; read_coeff(stream,coeff,sizeC/2,coeff_block_type|1); decoder_info->bit_count.coeff_v[stat_frame_type] += (stream->bitcnt - bit_start); } else{ memset(coeff,0,sizeC/2*sizeC/2*sizeof(int16_t)); } } block_info->cbp.y = 1; //TODO: Do properly with respect to deblocking filter block_info->cbp.u = 1; block_info->cbp.v = 1; } else{ int index; int16_t *coeff; /* Loop over 4 TUs */ for (index=0;index<4;index++){ bit_start = stream->bitcnt; cbp.y = get_flc(1, stream); decoder_info->bit_count.cbp[stat_frame_type] += (stream->bitcnt - bit_start); /* Y */ coeff = coeff_y + index*sizeY/2*sizeY/2; if (cbp.y){ bit_start = stream->bitcnt; read_coeff(stream,coeff,sizeY/2,coeff_block_type|0); decoder_info->bit_count.coeff_y[stat_frame_type] += (stream->bitcnt - bit_start); } else{ memset(coeff,0,sizeY/2*sizeY/2*sizeof(int16_t)); } } bit_start = stream->bitcnt; if (decoder_info->subsample != 400) { int tmp; tmp = get_vlc(13, stream); cbp.u = tmp & 1; cbp.v = (tmp >> 1) & 1; } else cbp.u = cbp.v = 0; decoder_info->bit_count.cbp[stat_frame_type] += (stream->bitcnt - bit_start); if (cbp.u){ bit_start = stream->bitcnt; read_coeff(stream,coeff_u,sizeC,coeff_block_type|1); decoder_info->bit_count.coeff_u[stat_frame_type] += (stream->bitcnt - bit_start); } else memset(coeff_u,0,sizeC*sizeC*sizeof(int16_t)); if (cbp.v){ bit_start = stream->bitcnt; read_coeff(stream,coeff_v,sizeC,coeff_block_type|1); decoder_info->bit_count.coeff_v[stat_frame_type] += (stream->bitcnt - bit_start); } else memset(coeff_v,0,sizeC*sizeC*sizeof(int16_t)); block_info->cbp.y = 1; //TODO: Do properly with respect to deblocking filter block_info->cbp.u = 1; block_info->cbp.v = 1; } //if (size==8) } //if (tb_split==0) } //if (mode!=MODE_SKIP) else{ tb_split = 0; block_info->cbp.y = 0; block_info->cbp.u = 0; block_info->cbp.v = 0; } /* Store block data */ if (mode==MODE_BIPRED){ memcpy(block_info->block_param.mv_arr0,mv_arr0,4*sizeof(mv_t)); //Used for mv0 coding memcpy(block_info->block_param.mv_arr1,mv_arr1,4*sizeof(mv_t)); //Used for mv1 coding } else if(mode==MODE_SKIP){ memcpy(block_info->block_param.mv_arr0,mv_arr0,4*sizeof(mv_t)); //Used for mv0 coding memcpy(block_info->block_param.mv_arr1,mv_arr1,4*sizeof(mv_t)); //Used for mv1 coding } else if(mode==MODE_MERGE){ memcpy(block_info->block_param.mv_arr0,mv_arr0,4*sizeof(mv_t)); //Used for mv0 coding memcpy(block_info->block_param.mv_arr1,mv_arr1,4*sizeof(mv_t)); //Used for mv1 coding } else{ memcpy(block_info->block_param.mv_arr0,mv_arr,4*sizeof(mv_t)); //Used for mv0 coding memcpy(block_info->block_param.mv_arr1,mv_arr,4*sizeof(mv_t)); //Used for mv1 coding } block_info->block_param.mode = mode; block_info->block_param.tb_split = tb_split; int bwidth = min(size,width - xpos); int bheight = min(size,height - ypos); /* Update mode and block size statistics */ decoder_info->bit_count.mode[stat_frame_type][mode] += (bwidth/MIN_BLOCK_SIZE * bheight/MIN_BLOCK_SIZE); decoder_info->bit_count.size[stat_frame_type][log2i(size)-3] += (bwidth/MIN_BLOCK_SIZE * bheight/MIN_BLOCK_SIZE); decoder_info->bit_count.size_and_mode[stat_frame_type][log2i(size)-3][mode] += (bwidth/MIN_BLOCK_SIZE * bheight/MIN_BLOCK_SIZE); return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_1_1
crossvul-cpp_data_good_4779_2
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP DDDD BBBB % % P P D D B B % % PPPP D D BBBB % % P D D B B % % P DDDD BBBB % % % % % % Read/Write Palm Database ImageViewer Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % 20071202 TS * rewrote RLE decoder - old version could cause buffer overflows % * failure of RLE decoding now thows error RLEDecoderError % * fixed bug in RLE decoding - now all rows are decoded, not just % the first one % * fixed bug in reader - record offsets now handled correctly % * fixed bug in reader - only bits 0..2 indicate compression type % * in writer: now using image color count instead of depth */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/colormap-private.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" /* Typedef declarations. */ typedef struct _PDBInfo { char name[32]; short int attributes, version; size_t create_time, modify_time, archive_time, modify_number, application_info, sort_info; char type[4], /* database type identifier "vIMG" */ id[4]; /* database creator identifier "View" */ size_t seed, next_record; short int number_records; } PDBInfo; typedef struct _PDBImage { char name[32], version; size_t reserved_1, note; short int x_last, y_last; size_t reserved_2; short int width, height; unsigned char type; unsigned short x_anchor, y_anchor; } PDBImage; /* Forward declarations. */ static MagickBooleanType WritePDBImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage unpacks the packed image pixels into runlength-encoded % pixel packets. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(Image *image,unsigned char *pixels, % const size_t length) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o pixels: The address of a byte (8 bits) array of pixel data created by % the decoding process. % % o length: Number of bytes to read into buffer 'pixels'. % */ static MagickBooleanType DecodeImage(Image *image, unsigned char *pixels, const size_t length) { #define RLE_MODE_NONE -1 #define RLE_MODE_COPY 0 #define RLE_MODE_RUN 1 int data = 0, count = 0; unsigned char *p; int mode = RLE_MODE_NONE; for (p = pixels; p < pixels + length; p++) { if (0 == count) { data = ReadBlobByte( image ); if (-1 == data) return MagickFalse; if (data > 128) { mode = RLE_MODE_RUN; count = data - 128 + 1; data = ReadBlobByte( image ); if (-1 == data) return MagickFalse; } else { mode = RLE_MODE_COPY; count = data + 1; } } if (RLE_MODE_COPY == mode) { data = ReadBlobByte( image ); if (-1 == data) return MagickFalse; } *p = (unsigned char)data; --count; } return MagickTrue; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P D B % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPDB() returns MagickTrue if the image format type, identified by the % magick string, is PDB. % % The format of the ReadPDBImage method is: % % MagickBooleanType IsPDB(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPDB(const unsigned char *magick,const size_t length) { if (length < 68) return(MagickFalse); if (memcmp(magick+60,"vIMGView",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P D B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPDBImage() reads an Pilot image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPDBImage method is: % % Image *ReadPDBImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadPDBImage(const ImageInfo *image_info,ExceptionInfo *exception) { unsigned char attributes, tag[3]; Image *image; IndexPacket index; MagickBooleanType status; PDBImage pdb_image; PDBInfo pdb_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register unsigned char *p; size_t bits_per_pixel, num_pad_bytes, one, packets; ssize_t count, img_offset, comment_offset = 0, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a PDB image file. */ count=ReadBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name); if (count != sizeof(pdb_info.name)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); pdb_info.attributes=(short) ReadBlobMSBShort(image); pdb_info.version=(short) ReadBlobMSBShort(image); pdb_info.create_time=ReadBlobMSBLong(image); pdb_info.modify_time=ReadBlobMSBLong(image); pdb_info.archive_time=ReadBlobMSBLong(image); pdb_info.modify_number=ReadBlobMSBLong(image); pdb_info.application_info=ReadBlobMSBLong(image); pdb_info.sort_info=ReadBlobMSBLong(image); (void) ReadBlob(image,4,(unsigned char *) pdb_info.type); (void) ReadBlob(image,4,(unsigned char *) pdb_info.id); pdb_info.seed=ReadBlobMSBLong(image); pdb_info.next_record=ReadBlobMSBLong(image); pdb_info.number_records=(short) ReadBlobMSBShort(image); if ((memcmp(pdb_info.type,"vIMG",4) != 0) || (memcmp(pdb_info.id,"View",4) != 0)) if (pdb_info.next_record != 0) ThrowReaderException(CoderError,"MultipleRecordListNotSupported"); /* Read record header. */ img_offset=(ssize_t) ReadBlobMSBSignedLong(image); attributes=(unsigned char) (ReadBlobByte(image)); (void) attributes; count=ReadBlob(image,3,(unsigned char *) tag); if (count != 3 || memcmp(tag,"\x6f\x80\x00",3) != 0) ThrowReaderException(CorruptImageError,"CorruptImage"); if (pdb_info.number_records > 1) { comment_offset=(ssize_t) ReadBlobMSBSignedLong(image); attributes=(unsigned char) (ReadBlobByte(image)); count=ReadBlob(image,3,(unsigned char *) tag); if (count != 3 || memcmp(tag,"\x6f\x80\x01",3) != 0) ThrowReaderException(CorruptImageError,"CorruptImage"); } num_pad_bytes = (size_t) (img_offset - TellBlob( image )); while (num_pad_bytes-- != 0) { int c; c=ReadBlobByte(image); if (c == EOF) break; } /* Read image header. */ count=ReadBlob(image,sizeof(pdb_image.name),(unsigned char *) pdb_image.name); if (count != sizeof(pdb_image.name)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); pdb_image.version=ReadBlobByte(image); pdb_image.type=(unsigned char) ReadBlobByte(image); pdb_image.reserved_1=ReadBlobMSBLong(image); pdb_image.note=ReadBlobMSBLong(image); pdb_image.x_last=(short) ReadBlobMSBShort(image); pdb_image.y_last=(short) ReadBlobMSBShort(image); pdb_image.reserved_2=ReadBlobMSBLong(image); pdb_image.x_anchor=ReadBlobMSBShort(image); pdb_image.y_anchor=ReadBlobMSBShort(image); pdb_image.width=(short) ReadBlobMSBShort(image); pdb_image.height=(short) ReadBlobMSBShort(image); /* Initialize image structure. */ image->columns=(size_t) pdb_image.width; image->rows=(size_t) pdb_image.height; image->depth=8; image->storage_class=PseudoClass; bits_per_pixel=pdb_image.type == 0 ? 2UL : pdb_image.type == 2 ? 4UL : 1UL; one=1; if (AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } packets=(bits_per_pixel*image->columns+7)/8; pixels=(unsigned char *) AcquireQuantumMemory(packets+257UL,image->rows* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); switch (pdb_image.version & 0x07) { case 0: { image->compression=NoCompression; count=(ssize_t) ReadBlob(image, packets * image -> rows, pixels); break; } case 1: { image->compression=RLECompression; if (!DecodeImage(image, pixels, packets * image -> rows)) ThrowReaderException( CorruptImageError, "RLEDecoderError" ); break; } default: ThrowReaderException(CorruptImageError, "UnrecognizedImageCompressionType" ); } p=pixels; switch (bits_per_pixel) { case 1: { int bit; /* Read 1-bit PDB image. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(IndexPacket) (*p & (0x80 >> bit) ? 0x00 : 0x01); SetPixelIndex(indexes+x+bit,index); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) SyncImage(image); break; } case 2: { /* Read 2-bit PDB image. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns-3; x+=4) { index=ConstrainColormapIndex(image,3UL-((*p >> 6) & 0x03)); SetPixelIndex(indexes+x,index); index=ConstrainColormapIndex(image,3UL-((*p >> 4) & 0x03)); SetPixelIndex(indexes+x+1,index); index=ConstrainColormapIndex(image,3UL-((*p >> 2) & 0x03)); SetPixelIndex(indexes+x+2,index); index=ConstrainColormapIndex(image,3UL-((*p) & 0x03)); SetPixelIndex(indexes+x+3,index); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) SyncImage(image); break; } case 4: { /* Read 4-bit PDB image. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns-1; x+=2) { index=ConstrainColormapIndex(image,15UL-((*p >> 4) & 0x0f)); SetPixelIndex(indexes+x,index); index=ConstrainColormapIndex(image,15UL-((*p) & 0x0f)); SetPixelIndex(indexes+x+1,index); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) SyncImage(image); break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); if (pdb_info.number_records > 1) { char *comment; int c; register char *p; size_t length; num_pad_bytes = (size_t) (comment_offset - TellBlob( image )); while (num_pad_bytes--) ReadBlobByte( image ); /* Read comment. */ c=ReadBlobByte(image); length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; c != EOF; p++) { if ((size_t) (p-comment+MaxTextExtent) >= length) { *p='\0'; length<<=1; length+=MaxTextExtent; comment=(char *) ResizeQuantumMemory(comment,length+MaxTextExtent, sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=c; c=ReadBlobByte(image); } *p='\0'; if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P D B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPDBImage() adds properties for the PDB image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPDBImage method is: % % size_t RegisterPDBImage(void) % */ ModuleExport size_t RegisterPDBImage(void) { MagickInfo *entry; entry=SetMagickInfo("PDB"); entry->decoder=(DecodeImageHandler *) ReadPDBImage; entry->encoder=(EncodeImageHandler *) WritePDBImage; entry->magick=(IsImageFormatHandler *) IsPDB; entry->description=ConstantString("Palm Database ImageViewer Format"); entry->module=ConstantString("PDB"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P D B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPDBImage() removes format registrations made by the % PDB module from the list of supported formats. % % The format of the UnregisterPDBImage method is: % % UnregisterPDBImage(void) % */ ModuleExport void UnregisterPDBImage(void) { (void) UnregisterMagickInfo("PDB"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P D B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePDBImage() writes an image % % The format of the WritePDBImage method is: % % MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % */ static unsigned char *EncodeRLE(unsigned char *destination, unsigned char *source,size_t literal,size_t repeat) { if (literal > 0) *destination++=(unsigned char) (literal-1); (void) CopyMagickMemory(destination,source,literal); destination+=literal; if (repeat > 0) { *destination++=(unsigned char) (0x80 | (repeat-1)); *destination++=source[literal]; } return(destination); } static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image) { const char *comment; int bits; MagickBooleanType status; PDBImage pdb_image; PDBInfo pdb_info; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t x; register unsigned char *q; size_t bits_per_pixel, literal, packets, packet_size, repeat; ssize_t y; unsigned char *buffer, *runlength, *scanline; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); if ((image -> colors <= 2 ) || (GetImageType(image,&image->exception ) == BilevelType)) { bits_per_pixel=1; } else if (image->colors <= 4) { bits_per_pixel=2; } else if (image->colors <= 8) { bits_per_pixel=3; } else { bits_per_pixel=4; } (void) ResetMagickMemory(&pdb_info,0,sizeof(pdb_info)); (void) CopyMagickString(pdb_info.name,image_info->filename, sizeof(pdb_info.name)); pdb_info.attributes=0; pdb_info.version=0; pdb_info.create_time=time(NULL); pdb_info.modify_time=pdb_info.create_time; pdb_info.archive_time=0; pdb_info.modify_number=0; pdb_info.application_info=0; pdb_info.sort_info=0; (void) CopyMagickMemory(pdb_info.type,"vIMG",4); (void) CopyMagickMemory(pdb_info.id,"View",4); pdb_info.seed=0; pdb_info.next_record=0; comment=GetImageProperty(image,"comment"); pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2); (void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info); (void) WriteBlob(image,4,(unsigned char *) pdb_info.type); (void) WriteBlob(image,4,(unsigned char *) pdb_info.id); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records); (void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name)); pdb_image.version=1; /* RLE Compressed */ switch (bits_per_pixel) { case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */ case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */ default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */ } pdb_image.reserved_1=0; pdb_image.note=0; pdb_image.x_last=0; pdb_image.y_last=0; pdb_image.reserved_2=0; pdb_image.x_anchor=(unsigned short) 0xffff; pdb_image.y_anchor=(unsigned short) 0xffff; pdb_image.width=(short) image->columns; if (image->columns % 16) pdb_image.width=(short) (16*(image->columns/16+1)); pdb_image.height=(short) image->rows; packets=((bits_per_pixel*image->columns+7)/8); runlength=(unsigned char *) AcquireQuantumMemory(9UL*packets, image->rows*sizeof(*runlength)); if (runlength == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); buffer=(unsigned char *) AcquireQuantumMemory(512,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); packet_size=(size_t) (image->depth > 8 ? 2 : 1); scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); /* Convert to GRAY raster scanline. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,image->depth > 8 ? 16 : 8); bits=8/(int) bits_per_pixel-1; /* start at most significant bits */ literal=0; repeat=0; q=runlength; buffer[0]=0x00; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, GrayQuantum,scanline,&image->exception); for (x=0; x < (ssize_t) pdb_image.width; x++) { if (x < (ssize_t) image->columns) buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >> (8-bits_per_pixel) << bits*bits_per_pixel; bits--; if (bits < 0) { if (((literal+repeat) > 0) && (buffer[literal+repeat] == buffer[literal+repeat-1])) { if (repeat == 0) { literal--; repeat++; } repeat++; if (0x7f < repeat) { q=EncodeRLE(q,buffer,literal,repeat); literal=0; repeat=0; } } else { if (repeat >= 2) literal+=repeat; else { q=EncodeRLE(q,buffer,literal,repeat); buffer[0]=buffer[literal+repeat]; literal=0; } literal++; repeat=0; if (0x7f < literal) { q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0); (void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80); literal-=0x80; } } bits=8/(int) bits_per_pixel-1; buffer[literal+repeat]=0x00; } } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } q=EncodeRLE(q,buffer,literal,repeat); scanline=(unsigned char *) RelinquishMagickMemory(scanline); buffer=(unsigned char *) RelinquishMagickMemory(buffer); quantum_info=DestroyQuantumInfo(quantum_info); /* Write the Image record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8* pdb_info.number_records)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,0); if (pdb_info.number_records > 1) { /* Write the comment record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q- runlength)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,1); } /* Write the Image data. */ (void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *) pdb_image.name); (void) WriteBlobByte(image,(unsigned char) pdb_image.version); (void) WriteBlobByte(image,pdb_image.type); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2); (void) WriteBlobMSBShort(image,pdb_image.x_anchor); (void) WriteBlobMSBShort(image,pdb_image.y_anchor); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height); (void) WriteBlob(image,(size_t) (q-runlength),runlength); runlength=(unsigned char *) RelinquishMagickMemory(runlength); if (pdb_info.number_records > 1) (void) WriteBlobString(image,comment); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_4779_2
crossvul-cpp_data_good_5263_0
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Sterling Hughes <sterling@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define ZEND_INCLUDE_FULL_WINDOWS_HEADERS #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_CURL #include <stdio.h> #include <string.h> #ifdef PHP_WIN32 #include <winsock2.h> #include <sys/types.h> #endif #include <curl/curl.h> #include <curl/easy.h> /* As of curl 7.11.1 this is no longer defined inside curl.h */ #ifndef HttpPost #define HttpPost curl_httppost #endif /* {{{ cruft for thread safe SSL crypto locks */ #if defined(ZTS) && defined(HAVE_CURL_SSL) # ifdef PHP_WIN32 # define PHP_CURL_NEED_OPENSSL_TSL # include <openssl/crypto.h> # else /* !PHP_WIN32 */ # if defined(HAVE_CURL_OPENSSL) # if defined(HAVE_OPENSSL_CRYPTO_H) # define PHP_CURL_NEED_OPENSSL_TSL # include <openssl/crypto.h> # else # warning \ "libcurl was compiled with OpenSSL support, but configure could not find " \ "openssl/crypto.h; thus no SSL crypto locking callbacks will be set, which may " \ "cause random crashes on SSL requests" # endif # elif defined(HAVE_CURL_GNUTLS) # if defined(HAVE_GCRYPT_H) # define PHP_CURL_NEED_GNUTLS_TSL # include <gcrypt.h> # else # warning \ "libcurl was compiled with GnuTLS support, but configure could not find " \ "gcrypt.h; thus no SSL crypto locking callbacks will be set, which may " \ "cause random crashes on SSL requests" # endif # else # warning \ "libcurl was compiled with SSL support, but configure could not determine which" \ "library was used; thus no SSL crypto locking callbacks will be set, which may " \ "cause random crashes on SSL requests" # endif /* HAVE_CURL_OPENSSL || HAVE_CURL_GNUTLS */ # endif /* PHP_WIN32 */ #endif /* ZTS && HAVE_CURL_SSL */ /* }}} */ #define SMART_STR_PREALLOC 4096 #include "zend_smart_str.h" #include "ext/standard/info.h" #include "ext/standard/file.h" #include "ext/standard/url.h" #include "php_curl.h" int le_curl; int le_curl_multi_handle; int le_curl_share_handle; #ifdef PHP_CURL_NEED_OPENSSL_TSL /* {{{ */ static MUTEX_T *php_curl_openssl_tsl = NULL; static void php_curl_ssl_lock(int mode, int n, const char * file, int line) { if (mode & CRYPTO_LOCK) { tsrm_mutex_lock(php_curl_openssl_tsl[n]); } else { tsrm_mutex_unlock(php_curl_openssl_tsl[n]); } } static unsigned long php_curl_ssl_id(void) { return (unsigned long) tsrm_thread_id(); } #endif /* }}} */ #ifdef PHP_CURL_NEED_GNUTLS_TSL /* {{{ */ static int php_curl_ssl_mutex_create(void **m) { if (*((MUTEX_T *) m) = tsrm_mutex_alloc()) { return SUCCESS; } else { return FAILURE; } } static int php_curl_ssl_mutex_destroy(void **m) { tsrm_mutex_free(*((MUTEX_T *) m)); return SUCCESS; } static int php_curl_ssl_mutex_lock(void **m) { return tsrm_mutex_lock(*((MUTEX_T *) m)); } static int php_curl_ssl_mutex_unlock(void **m) { return tsrm_mutex_unlock(*((MUTEX_T *) m)); } static struct gcry_thread_cbs php_curl_gnutls_tsl = { GCRY_THREAD_OPTION_USER, NULL, php_curl_ssl_mutex_create, php_curl_ssl_mutex_destroy, php_curl_ssl_mutex_lock, php_curl_ssl_mutex_unlock }; #endif /* }}} */ static void _php_curl_close_ex(php_curl *ch); static void _php_curl_close(zend_resource *rsrc); #define SAVE_CURL_ERROR(__handle, __err) (__handle)->err.no = (int) __err; #define CAAL(s, v) add_assoc_long_ex(return_value, s, sizeof(s) - 1, (zend_long) v); #define CAAD(s, v) add_assoc_double_ex(return_value, s, sizeof(s) - 1, (double) v); #define CAAS(s, v) add_assoc_string_ex(return_value, s, sizeof(s) - 1, (char *) (v ? v : "")); #define CAASTR(s, v) add_assoc_str_ex(return_value, s, sizeof(s) - 1, \ v ? zend_string_copy(v) : ZSTR_EMPTY_ALLOC()); #define CAAZ(s, v) add_assoc_zval_ex(return_value, s, sizeof(s) -1 , (zval *) v); #if defined(PHP_WIN32) || defined(__GNUC__) # define php_curl_ret(__ret) RETVAL_FALSE; return __ret; #else # define php_curl_ret(__ret) RETVAL_FALSE; return; #endif static int php_curl_option_str(php_curl *ch, zend_long option, const char *str, const int len, zend_bool make_copy) { CURLcode error = CURLE_OK; if (strlen(str) != len) { php_error_docref(NULL, E_WARNING, "Curl option contains invalid characters (\\0)"); return FAILURE; } #if LIBCURL_VERSION_NUM >= 0x071100 if (make_copy) { #endif char *copystr; /* Strings passed to libcurl as 'char *' arguments, are copied by the library since 7.17.0 */ copystr = estrndup(str, len); error = curl_easy_setopt(ch->cp, option, copystr); zend_llist_add_element(&ch->to_free->str, &copystr); #if LIBCURL_VERSION_NUM >= 0x071100 } else { error = curl_easy_setopt(ch->cp, option, str); } #endif SAVE_CURL_ERROR(ch, error) return error == CURLE_OK ? SUCCESS : FAILURE; } static int php_curl_option_url(php_curl *ch, const char *url, const int len) /* {{{ */ { /* Disable file:// if open_basedir are used */ if (PG(open_basedir) && *PG(open_basedir)) { #if LIBCURL_VERSION_NUM >= 0x071304 curl_easy_setopt(ch->cp, CURLOPT_PROTOCOLS, CURLPROTO_ALL & ~CURLPROTO_FILE); #else php_url *uri; if (!(uri = php_url_parse_ex(url, len))) { php_error_docref(NULL, E_WARNING, "Invalid URL '%s'", url); return FAILURE; } if (uri->scheme && !strncasecmp("file", uri->scheme, sizeof("file"))) { php_error_docref(NULL, E_WARNING, "Protocol 'file' disabled in cURL"); php_url_free(uri); return FAILURE; } php_url_free(uri); #endif } return php_curl_option_str(ch, CURLOPT_URL, url, len, 0); } /* }}} */ void _php_curl_verify_handlers(php_curl *ch, int reporterror) /* {{{ */ { php_stream *stream; ZEND_ASSERT(ch && ch->handlers); if (!Z_ISUNDEF(ch->handlers->std_err)) { stream = (php_stream *)zend_fetch_resource2_ex(&ch->handlers->std_err, NULL, php_file_le_stream(), php_file_le_pstream()); if (stream == NULL) { if (reporterror) { php_error_docref(NULL, E_WARNING, "CURLOPT_STDERR resource has gone away, resetting to stderr"); } zval_ptr_dtor(&ch->handlers->std_err); ZVAL_UNDEF(&ch->handlers->std_err); curl_easy_setopt(ch->cp, CURLOPT_STDERR, stderr); } } if (ch->handlers->read && !Z_ISUNDEF(ch->handlers->read->stream)) { stream = (php_stream *)zend_fetch_resource2_ex(&ch->handlers->read->stream, NULL, php_file_le_stream(), php_file_le_pstream()); if (stream == NULL) { if (reporterror) { php_error_docref(NULL, E_WARNING, "CURLOPT_INFILE resource has gone away, resetting to default"); } zval_ptr_dtor(&ch->handlers->read->stream); ZVAL_UNDEF(&ch->handlers->read->stream); ch->handlers->read->res = NULL; ch->handlers->read->fp = 0; curl_easy_setopt(ch->cp, CURLOPT_INFILE, (void *) ch); } } if (ch->handlers->write_header && !Z_ISUNDEF(ch->handlers->write_header->stream)) { stream = (php_stream *)zend_fetch_resource2_ex(&ch->handlers->write_header->stream, NULL, php_file_le_stream(), php_file_le_pstream()); if (stream == NULL) { if (reporterror) { php_error_docref(NULL, E_WARNING, "CURLOPT_WRITEHEADER resource has gone away, resetting to default"); } zval_ptr_dtor(&ch->handlers->write_header->stream); ZVAL_UNDEF(&ch->handlers->write_header->stream); ch->handlers->write_header->fp = 0; ch->handlers->write_header->method = PHP_CURL_IGNORE; curl_easy_setopt(ch->cp, CURLOPT_WRITEHEADER, (void *) ch); } } if (ch->handlers->write && !Z_ISUNDEF(ch->handlers->write->stream)) { stream = (php_stream *)zend_fetch_resource2_ex(&ch->handlers->write->stream, NULL, php_file_le_stream(), php_file_le_pstream()); if (stream == NULL) { if (reporterror) { php_error_docref(NULL, E_WARNING, "CURLOPT_FILE resource has gone away, resetting to default"); } zval_ptr_dtor(&ch->handlers->write->stream); ZVAL_UNDEF(&ch->handlers->write->stream); ch->handlers->write->fp = 0; ch->handlers->write->method = PHP_CURL_STDOUT; curl_easy_setopt(ch->cp, CURLOPT_FILE, (void *) ch); } } return; } /* }}} */ /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_curl_version, 0, 0, 0) ZEND_ARG_INFO(0, version) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_curl_init, 0, 0, 0) ZEND_ARG_INFO(0, url) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_copy_handle, 0) ZEND_ARG_INFO(0, ch) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_setopt, 0) ZEND_ARG_INFO(0, ch) ZEND_ARG_INFO(0, option) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_setopt_array, 0) ZEND_ARG_INFO(0, ch) ZEND_ARG_ARRAY_INFO(0, options, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_exec, 0) ZEND_ARG_INFO(0, ch) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_curl_getinfo, 0, 0, 1) ZEND_ARG_INFO(0, ch) ZEND_ARG_INFO(0, option) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_error, 0) ZEND_ARG_INFO(0, ch) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_errno, 0) ZEND_ARG_INFO(0, ch) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_close, 0) ZEND_ARG_INFO(0, ch) ZEND_END_ARG_INFO() #if LIBCURL_VERSION_NUM >= 0x070c01 /* 7.12.1 */ ZEND_BEGIN_ARG_INFO(arginfo_curl_reset, 0) ZEND_ARG_INFO(0, ch) ZEND_END_ARG_INFO() #endif #if LIBCURL_VERSION_NUM > 0x070f03 /* 7.15.4 */ ZEND_BEGIN_ARG_INFO(arginfo_curl_escape, 0) ZEND_ARG_INFO(0, ch) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_unescape, 0) ZEND_ARG_INFO(0, ch) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_setopt, 0) ZEND_ARG_INFO(0, sh) ZEND_ARG_INFO(0, option) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_init, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_add_handle, 0) ZEND_ARG_INFO(0, mh) ZEND_ARG_INFO(0, ch) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_remove_handle, 0) ZEND_ARG_INFO(0, mh) ZEND_ARG_INFO(0, ch) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_curl_multi_select, 0, 0, 1) ZEND_ARG_INFO(0, mh) ZEND_ARG_INFO(0, timeout) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_curl_multi_exec, 0, 0, 1) ZEND_ARG_INFO(0, mh) ZEND_ARG_INFO(1, still_running) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_getcontent, 0) ZEND_ARG_INFO(0, ch) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_curl_multi_info_read, 0, 0, 1) ZEND_ARG_INFO(0, mh) ZEND_ARG_INFO(1, msgs_in_queue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_close, 0) ZEND_ARG_INFO(0, mh) ZEND_END_ARG_INFO() #if LIBCURL_VERSION_NUM >= 0x070c00 /* Available since 7.12.0 */ ZEND_BEGIN_ARG_INFO(arginfo_curl_strerror, 0) ZEND_ARG_INFO(0, errornum) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_strerror, 0) ZEND_ARG_INFO(0, errornum) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_curl_share_init, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_share_close, 0) ZEND_ARG_INFO(0, sh) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_curl_share_setopt, 0) ZEND_ARG_INFO(0, sh) ZEND_ARG_INFO(0, option) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() #if LIBCURL_VERSION_NUM >= 0x071200 /* Available since 7.18.0 */ ZEND_BEGIN_ARG_INFO(arginfo_curl_pause, 0) ZEND_ARG_INFO(0, ch) ZEND_ARG_INFO(0, bitmask) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_curlfile_create, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, mimetype) ZEND_ARG_INFO(0, postname) ZEND_END_ARG_INFO() /* }}} */ /* {{{ curl_functions[] */ const zend_function_entry curl_functions[] = { PHP_FE(curl_init, arginfo_curl_init) PHP_FE(curl_copy_handle, arginfo_curl_copy_handle) PHP_FE(curl_version, arginfo_curl_version) PHP_FE(curl_setopt, arginfo_curl_setopt) PHP_FE(curl_setopt_array, arginfo_curl_setopt_array) PHP_FE(curl_exec, arginfo_curl_exec) PHP_FE(curl_getinfo, arginfo_curl_getinfo) PHP_FE(curl_error, arginfo_curl_error) PHP_FE(curl_errno, arginfo_curl_errno) PHP_FE(curl_close, arginfo_curl_close) #if LIBCURL_VERSION_NUM >= 0x070c00 /* 7.12.0 */ PHP_FE(curl_strerror, arginfo_curl_strerror) PHP_FE(curl_multi_strerror, arginfo_curl_multi_strerror) #endif #if LIBCURL_VERSION_NUM >= 0x070c01 /* 7.12.1 */ PHP_FE(curl_reset, arginfo_curl_reset) #endif #if LIBCURL_VERSION_NUM >= 0x070f04 /* 7.15.4 */ PHP_FE(curl_escape, arginfo_curl_escape) PHP_FE(curl_unescape, arginfo_curl_unescape) #endif #if LIBCURL_VERSION_NUM >= 0x071200 /* 7.18.0 */ PHP_FE(curl_pause, arginfo_curl_pause) #endif PHP_FE(curl_multi_init, arginfo_curl_multi_init) PHP_FE(curl_multi_add_handle, arginfo_curl_multi_add_handle) PHP_FE(curl_multi_remove_handle, arginfo_curl_multi_remove_handle) PHP_FE(curl_multi_select, arginfo_curl_multi_select) PHP_FE(curl_multi_exec, arginfo_curl_multi_exec) PHP_FE(curl_multi_getcontent, arginfo_curl_multi_getcontent) PHP_FE(curl_multi_info_read, arginfo_curl_multi_info_read) PHP_FE(curl_multi_close, arginfo_curl_multi_close) #if LIBCURL_VERSION_NUM >= 0x070f04 /* 7.15.4 */ PHP_FE(curl_multi_setopt, arginfo_curl_multi_setopt) #endif PHP_FE(curl_share_init, arginfo_curl_share_init) PHP_FE(curl_share_close, arginfo_curl_share_close) PHP_FE(curl_share_setopt, arginfo_curl_share_setopt) PHP_FE(curl_file_create, arginfo_curlfile_create) PHP_FE_END }; /* }}} */ /* {{{ curl_module_entry */ zend_module_entry curl_module_entry = { STANDARD_MODULE_HEADER, "curl", curl_functions, PHP_MINIT(curl), PHP_MSHUTDOWN(curl), NULL, NULL, PHP_MINFO(curl), PHP_CURL_VERSION, STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_CURL ZEND_GET_MODULE (curl) #endif /* {{{ PHP_INI_BEGIN */ PHP_INI_BEGIN() PHP_INI_ENTRY("curl.cainfo", "", PHP_INI_SYSTEM, NULL) PHP_INI_END() /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(curl) { curl_version_info_data *d; char **p; char str[1024]; size_t n = 0; d = curl_version_info(CURLVERSION_NOW); php_info_print_table_start(); php_info_print_table_row(2, "cURL support", "enabled"); php_info_print_table_row(2, "cURL Information", d->version); sprintf(str, "%d", d->age); php_info_print_table_row(2, "Age", str); /* To update on each new cURL release using src/main.c in cURL sources */ if (d->features) { struct feat { const char *name; int bitmask; }; unsigned int i; static const struct feat feats[] = { #if LIBCURL_VERSION_NUM >= 0x070a07 /* 7.10.7 */ {"AsynchDNS", CURL_VERSION_ASYNCHDNS}, #endif #if LIBCURL_VERSION_NUM >= 0x070f04 /* 7.15.4 */ {"CharConv", CURL_VERSION_CONV}, #endif #if LIBCURL_VERSION_NUM >= 0x070a06 /* 7.10.6 */ {"Debug", CURL_VERSION_DEBUG}, {"GSS-Negotiate", CURL_VERSION_GSSNEGOTIATE}, #endif #if LIBCURL_VERSION_NUM >= 0x070c00 /* 7.12.0 */ {"IDN", CURL_VERSION_IDN}, #endif {"IPv6", CURL_VERSION_IPV6}, {"krb4", CURL_VERSION_KERBEROS4}, #if LIBCURL_VERSION_NUM >= 0x070b01 /* 7.11.1 */ {"Largefile", CURL_VERSION_LARGEFILE}, #endif {"libz", CURL_VERSION_LIBZ}, #if LIBCURL_VERSION_NUM >= 0x070a06 /* 7.10.6 */ {"NTLM", CURL_VERSION_NTLM}, #endif #if LIBCURL_VERSION_NUM >= 0x071600 /* 7.22.0 */ {"NTLMWB", CURL_VERSION_NTLM_WB}, #endif #if LIBCURL_VERSION_NUM >= 0x070a08 /* 7.10.8 */ {"SPNEGO", CURL_VERSION_SPNEGO}, #endif {"SSL", CURL_VERSION_SSL}, #if LIBCURL_VERSION_NUM >= 0x070d02 /* 7.13.2 */ {"SSPI", CURL_VERSION_SSPI}, #endif #if LIBCURL_VERSION_NUM >= 0x071504 /* 7.21.4 */ {"TLS-SRP", CURL_VERSION_TLSAUTH_SRP}, #endif #if LIBCURL_VERSION_NUM >= 0x072100 /* 7.33.0 */ {"HTTP2", CURL_VERSION_HTTP2}, #endif #if LIBCURL_VERSION_NUM >= 0x072600 /* 7.38.0 */ {"GSSAPI", CURL_VERSION_GSSAPI}, #endif #if LIBCURL_VERSION_NUM >= 0x072800 /* 7.40.0 */ {"KERBEROS5", CURL_VERSION_KERBEROS5}, {"UNIX_SOCKETS", CURL_VERSION_UNIX_SOCKETS}, #endif #if LIBCURL_VERSION_NUM >= 0x072f00 /* 7.47.0 */ {"PSL", CURL_VERSION_PSL}, #endif {NULL, 0} }; php_info_print_table_row(1, "Features"); for(i=0; i<sizeof(feats)/sizeof(feats[0]); i++) { if (feats[i].name) { php_info_print_table_row(2, feats[i].name, d->features & feats[i].bitmask ? "Yes" : "No"); } } } n = 0; p = (char **) d->protocols; while (*p != NULL) { n += sprintf(str + n, "%s%s", *p, *(p + 1) != NULL ? ", " : ""); p++; } php_info_print_table_row(2, "Protocols", str); php_info_print_table_row(2, "Host", d->host); if (d->ssl_version) { php_info_print_table_row(2, "SSL Version", d->ssl_version); } if (d->libz_version) { php_info_print_table_row(2, "ZLib Version", d->libz_version); } #if defined(CURLVERSION_SECOND) && CURLVERSION_NOW >= CURLVERSION_SECOND if (d->ares) { php_info_print_table_row(2, "ZLib Version", d->ares); } #endif #if defined(CURLVERSION_THIRD) && CURLVERSION_NOW >= CURLVERSION_THIRD if (d->libidn) { php_info_print_table_row(2, "libIDN Version", d->libidn); } #endif #if LIBCURL_VERSION_NUM >= 0x071300 if (d->iconv_ver_num) { php_info_print_table_row(2, "IconV Version", d->iconv_ver_num); } if (d->libssh_version) { php_info_print_table_row(2, "libSSH Version", d->libssh_version); } #endif php_info_print_table_end(); } /* }}} */ #define REGISTER_CURL_CONSTANT(__c) REGISTER_LONG_CONSTANT(#__c, __c, CONST_CS | CONST_PERSISTENT) /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(curl) { le_curl = zend_register_list_destructors_ex(_php_curl_close, NULL, "curl", module_number); le_curl_multi_handle = zend_register_list_destructors_ex(_php_curl_multi_close, NULL, "curl_multi", module_number); le_curl_share_handle = zend_register_list_destructors_ex(_php_curl_share_close, NULL, "curl_share", module_number); REGISTER_INI_ENTRIES(); /* See http://curl.haxx.se/lxr/source/docs/libcurl/symbols-in-versions or curl src/docs/libcurl/symbols-in-versions for a (almost) complete list of options and which version they were introduced */ /* Constants for curl_setopt() */ REGISTER_CURL_CONSTANT(CURLOPT_AUTOREFERER); REGISTER_CURL_CONSTANT(CURLOPT_BINARYTRANSFER); REGISTER_CURL_CONSTANT(CURLOPT_BUFFERSIZE); REGISTER_CURL_CONSTANT(CURLOPT_CAINFO); REGISTER_CURL_CONSTANT(CURLOPT_CAPATH); REGISTER_CURL_CONSTANT(CURLOPT_CONNECTTIMEOUT); REGISTER_CURL_CONSTANT(CURLOPT_COOKIE); REGISTER_CURL_CONSTANT(CURLOPT_COOKIEFILE); REGISTER_CURL_CONSTANT(CURLOPT_COOKIEJAR); REGISTER_CURL_CONSTANT(CURLOPT_COOKIESESSION); REGISTER_CURL_CONSTANT(CURLOPT_CRLF); REGISTER_CURL_CONSTANT(CURLOPT_CUSTOMREQUEST); REGISTER_CURL_CONSTANT(CURLOPT_DNS_CACHE_TIMEOUT); REGISTER_CURL_CONSTANT(CURLOPT_DNS_USE_GLOBAL_CACHE); REGISTER_CURL_CONSTANT(CURLOPT_EGDSOCKET); REGISTER_CURL_CONSTANT(CURLOPT_ENCODING); REGISTER_CURL_CONSTANT(CURLOPT_FAILONERROR); REGISTER_CURL_CONSTANT(CURLOPT_FILE); REGISTER_CURL_CONSTANT(CURLOPT_FILETIME); REGISTER_CURL_CONSTANT(CURLOPT_FOLLOWLOCATION); REGISTER_CURL_CONSTANT(CURLOPT_FORBID_REUSE); REGISTER_CURL_CONSTANT(CURLOPT_FRESH_CONNECT); REGISTER_CURL_CONSTANT(CURLOPT_FTPAPPEND); REGISTER_CURL_CONSTANT(CURLOPT_FTPLISTONLY); REGISTER_CURL_CONSTANT(CURLOPT_FTPPORT); REGISTER_CURL_CONSTANT(CURLOPT_FTP_USE_EPRT); REGISTER_CURL_CONSTANT(CURLOPT_FTP_USE_EPSV); REGISTER_CURL_CONSTANT(CURLOPT_HEADER); REGISTER_CURL_CONSTANT(CURLOPT_HEADERFUNCTION); REGISTER_CURL_CONSTANT(CURLOPT_HTTP200ALIASES); REGISTER_CURL_CONSTANT(CURLOPT_HTTPGET); REGISTER_CURL_CONSTANT(CURLOPT_HTTPHEADER); REGISTER_CURL_CONSTANT(CURLOPT_HTTPPROXYTUNNEL); REGISTER_CURL_CONSTANT(CURLOPT_HTTP_VERSION); REGISTER_CURL_CONSTANT(CURLOPT_INFILE); REGISTER_CURL_CONSTANT(CURLOPT_INFILESIZE); REGISTER_CURL_CONSTANT(CURLOPT_INTERFACE); REGISTER_CURL_CONSTANT(CURLOPT_KRB4LEVEL); REGISTER_CURL_CONSTANT(CURLOPT_LOW_SPEED_LIMIT); REGISTER_CURL_CONSTANT(CURLOPT_LOW_SPEED_TIME); REGISTER_CURL_CONSTANT(CURLOPT_MAXCONNECTS); REGISTER_CURL_CONSTANT(CURLOPT_MAXREDIRS); REGISTER_CURL_CONSTANT(CURLOPT_NETRC); REGISTER_CURL_CONSTANT(CURLOPT_NOBODY); REGISTER_CURL_CONSTANT(CURLOPT_NOPROGRESS); REGISTER_CURL_CONSTANT(CURLOPT_NOSIGNAL); REGISTER_CURL_CONSTANT(CURLOPT_PORT); REGISTER_CURL_CONSTANT(CURLOPT_POST); REGISTER_CURL_CONSTANT(CURLOPT_POSTFIELDS); REGISTER_CURL_CONSTANT(CURLOPT_POSTQUOTE); REGISTER_CURL_CONSTANT(CURLOPT_PREQUOTE); REGISTER_CURL_CONSTANT(CURLOPT_PRIVATE); REGISTER_CURL_CONSTANT(CURLOPT_PROGRESSFUNCTION); REGISTER_CURL_CONSTANT(CURLOPT_PROXY); REGISTER_CURL_CONSTANT(CURLOPT_PROXYPORT); REGISTER_CURL_CONSTANT(CURLOPT_PROXYTYPE); REGISTER_CURL_CONSTANT(CURLOPT_PROXYUSERPWD); REGISTER_CURL_CONSTANT(CURLOPT_PUT); REGISTER_CURL_CONSTANT(CURLOPT_QUOTE); REGISTER_CURL_CONSTANT(CURLOPT_RANDOM_FILE); REGISTER_CURL_CONSTANT(CURLOPT_RANGE); REGISTER_CURL_CONSTANT(CURLOPT_READDATA); REGISTER_CURL_CONSTANT(CURLOPT_READFUNCTION); REGISTER_CURL_CONSTANT(CURLOPT_REFERER); REGISTER_CURL_CONSTANT(CURLOPT_RESUME_FROM); REGISTER_CURL_CONSTANT(CURLOPT_RETURNTRANSFER); REGISTER_CURL_CONSTANT(CURLOPT_SHARE); REGISTER_CURL_CONSTANT(CURLOPT_SSLCERT); REGISTER_CURL_CONSTANT(CURLOPT_SSLCERTPASSWD); REGISTER_CURL_CONSTANT(CURLOPT_SSLCERTTYPE); REGISTER_CURL_CONSTANT(CURLOPT_SSLENGINE); REGISTER_CURL_CONSTANT(CURLOPT_SSLENGINE_DEFAULT); REGISTER_CURL_CONSTANT(CURLOPT_SSLKEY); REGISTER_CURL_CONSTANT(CURLOPT_SSLKEYPASSWD); REGISTER_CURL_CONSTANT(CURLOPT_SSLKEYTYPE); REGISTER_CURL_CONSTANT(CURLOPT_SSLVERSION); REGISTER_CURL_CONSTANT(CURLOPT_SSL_CIPHER_LIST); REGISTER_CURL_CONSTANT(CURLOPT_SSL_VERIFYHOST); REGISTER_CURL_CONSTANT(CURLOPT_SSL_VERIFYPEER); REGISTER_CURL_CONSTANT(CURLOPT_STDERR); REGISTER_CURL_CONSTANT(CURLOPT_TELNETOPTIONS); REGISTER_CURL_CONSTANT(CURLOPT_TIMECONDITION); REGISTER_CURL_CONSTANT(CURLOPT_TIMEOUT); REGISTER_CURL_CONSTANT(CURLOPT_TIMEVALUE); REGISTER_CURL_CONSTANT(CURLOPT_TRANSFERTEXT); REGISTER_CURL_CONSTANT(CURLOPT_UNRESTRICTED_AUTH); REGISTER_CURL_CONSTANT(CURLOPT_UPLOAD); REGISTER_CURL_CONSTANT(CURLOPT_URL); REGISTER_CURL_CONSTANT(CURLOPT_USERAGENT); REGISTER_CURL_CONSTANT(CURLOPT_USERPWD); REGISTER_CURL_CONSTANT(CURLOPT_VERBOSE); REGISTER_CURL_CONSTANT(CURLOPT_WRITEFUNCTION); REGISTER_CURL_CONSTANT(CURLOPT_WRITEHEADER); /* */ REGISTER_CURL_CONSTANT(CURLE_ABORTED_BY_CALLBACK); REGISTER_CURL_CONSTANT(CURLE_BAD_CALLING_ORDER); REGISTER_CURL_CONSTANT(CURLE_BAD_CONTENT_ENCODING); REGISTER_CURL_CONSTANT(CURLE_BAD_DOWNLOAD_RESUME); REGISTER_CURL_CONSTANT(CURLE_BAD_FUNCTION_ARGUMENT); REGISTER_CURL_CONSTANT(CURLE_BAD_PASSWORD_ENTERED); REGISTER_CURL_CONSTANT(CURLE_COULDNT_CONNECT); REGISTER_CURL_CONSTANT(CURLE_COULDNT_RESOLVE_HOST); REGISTER_CURL_CONSTANT(CURLE_COULDNT_RESOLVE_PROXY); REGISTER_CURL_CONSTANT(CURLE_FAILED_INIT); REGISTER_CURL_CONSTANT(CURLE_FILE_COULDNT_READ_FILE); REGISTER_CURL_CONSTANT(CURLE_FTP_ACCESS_DENIED); REGISTER_CURL_CONSTANT(CURLE_FTP_BAD_DOWNLOAD_RESUME); REGISTER_CURL_CONSTANT(CURLE_FTP_CANT_GET_HOST); REGISTER_CURL_CONSTANT(CURLE_FTP_CANT_RECONNECT); REGISTER_CURL_CONSTANT(CURLE_FTP_COULDNT_GET_SIZE); REGISTER_CURL_CONSTANT(CURLE_FTP_COULDNT_RETR_FILE); REGISTER_CURL_CONSTANT(CURLE_FTP_COULDNT_SET_ASCII); REGISTER_CURL_CONSTANT(CURLE_FTP_COULDNT_SET_BINARY); REGISTER_CURL_CONSTANT(CURLE_FTP_COULDNT_STOR_FILE); REGISTER_CURL_CONSTANT(CURLE_FTP_COULDNT_USE_REST); REGISTER_CURL_CONSTANT(CURLE_FTP_PARTIAL_FILE); REGISTER_CURL_CONSTANT(CURLE_FTP_PORT_FAILED); REGISTER_CURL_CONSTANT(CURLE_FTP_QUOTE_ERROR); REGISTER_CURL_CONSTANT(CURLE_FTP_USER_PASSWORD_INCORRECT); REGISTER_CURL_CONSTANT(CURLE_FTP_WEIRD_227_FORMAT); REGISTER_CURL_CONSTANT(CURLE_FTP_WEIRD_PASS_REPLY); REGISTER_CURL_CONSTANT(CURLE_FTP_WEIRD_PASV_REPLY); REGISTER_CURL_CONSTANT(CURLE_FTP_WEIRD_SERVER_REPLY); REGISTER_CURL_CONSTANT(CURLE_FTP_WEIRD_USER_REPLY); REGISTER_CURL_CONSTANT(CURLE_FTP_WRITE_ERROR); REGISTER_CURL_CONSTANT(CURLE_FUNCTION_NOT_FOUND); REGISTER_CURL_CONSTANT(CURLE_GOT_NOTHING); REGISTER_CURL_CONSTANT(CURLE_HTTP_NOT_FOUND); REGISTER_CURL_CONSTANT(CURLE_HTTP_PORT_FAILED); REGISTER_CURL_CONSTANT(CURLE_HTTP_POST_ERROR); REGISTER_CURL_CONSTANT(CURLE_HTTP_RANGE_ERROR); REGISTER_CURL_CONSTANT(CURLE_HTTP_RETURNED_ERROR); REGISTER_CURL_CONSTANT(CURLE_LDAP_CANNOT_BIND); REGISTER_CURL_CONSTANT(CURLE_LDAP_SEARCH_FAILED); REGISTER_CURL_CONSTANT(CURLE_LIBRARY_NOT_FOUND); REGISTER_CURL_CONSTANT(CURLE_MALFORMAT_USER); REGISTER_CURL_CONSTANT(CURLE_OBSOLETE); REGISTER_CURL_CONSTANT(CURLE_OK); REGISTER_CURL_CONSTANT(CURLE_OPERATION_TIMEDOUT); REGISTER_CURL_CONSTANT(CURLE_OPERATION_TIMEOUTED); REGISTER_CURL_CONSTANT(CURLE_OUT_OF_MEMORY); REGISTER_CURL_CONSTANT(CURLE_PARTIAL_FILE); REGISTER_CURL_CONSTANT(CURLE_READ_ERROR); REGISTER_CURL_CONSTANT(CURLE_RECV_ERROR); REGISTER_CURL_CONSTANT(CURLE_SEND_ERROR); REGISTER_CURL_CONSTANT(CURLE_SHARE_IN_USE); REGISTER_CURL_CONSTANT(CURLE_SSL_CACERT); REGISTER_CURL_CONSTANT(CURLE_SSL_CERTPROBLEM); REGISTER_CURL_CONSTANT(CURLE_SSL_CIPHER); REGISTER_CURL_CONSTANT(CURLE_SSL_CONNECT_ERROR); REGISTER_CURL_CONSTANT(CURLE_SSL_ENGINE_NOTFOUND); REGISTER_CURL_CONSTANT(CURLE_SSL_ENGINE_SETFAILED); REGISTER_CURL_CONSTANT(CURLE_SSL_PEER_CERTIFICATE); REGISTER_CURL_CONSTANT(CURLE_TELNET_OPTION_SYNTAX); REGISTER_CURL_CONSTANT(CURLE_TOO_MANY_REDIRECTS); REGISTER_CURL_CONSTANT(CURLE_UNKNOWN_TELNET_OPTION); REGISTER_CURL_CONSTANT(CURLE_UNSUPPORTED_PROTOCOL); REGISTER_CURL_CONSTANT(CURLE_URL_MALFORMAT); REGISTER_CURL_CONSTANT(CURLE_URL_MALFORMAT_USER); REGISTER_CURL_CONSTANT(CURLE_WRITE_ERROR); /* cURL info constants */ REGISTER_CURL_CONSTANT(CURLINFO_CONNECT_TIME); REGISTER_CURL_CONSTANT(CURLINFO_CONTENT_LENGTH_DOWNLOAD); REGISTER_CURL_CONSTANT(CURLINFO_CONTENT_LENGTH_UPLOAD); REGISTER_CURL_CONSTANT(CURLINFO_CONTENT_TYPE); REGISTER_CURL_CONSTANT(CURLINFO_EFFECTIVE_URL); REGISTER_CURL_CONSTANT(CURLINFO_FILETIME); REGISTER_CURL_CONSTANT(CURLINFO_HEADER_OUT); REGISTER_CURL_CONSTANT(CURLINFO_HEADER_SIZE); REGISTER_CURL_CONSTANT(CURLINFO_HTTP_CODE); REGISTER_CURL_CONSTANT(CURLINFO_LASTONE); REGISTER_CURL_CONSTANT(CURLINFO_NAMELOOKUP_TIME); REGISTER_CURL_CONSTANT(CURLINFO_PRETRANSFER_TIME); REGISTER_CURL_CONSTANT(CURLINFO_PRIVATE); REGISTER_CURL_CONSTANT(CURLINFO_REDIRECT_COUNT); REGISTER_CURL_CONSTANT(CURLINFO_REDIRECT_TIME); REGISTER_CURL_CONSTANT(CURLINFO_REQUEST_SIZE); REGISTER_CURL_CONSTANT(CURLINFO_SIZE_DOWNLOAD); REGISTER_CURL_CONSTANT(CURLINFO_SIZE_UPLOAD); REGISTER_CURL_CONSTANT(CURLINFO_SPEED_DOWNLOAD); REGISTER_CURL_CONSTANT(CURLINFO_SPEED_UPLOAD); REGISTER_CURL_CONSTANT(CURLINFO_SSL_VERIFYRESULT); REGISTER_CURL_CONSTANT(CURLINFO_STARTTRANSFER_TIME); REGISTER_CURL_CONSTANT(CURLINFO_TOTAL_TIME); /* Other */ REGISTER_CURL_CONSTANT(CURLMSG_DONE); REGISTER_CURL_CONSTANT(CURLVERSION_NOW); /* Curl Multi Constants */ REGISTER_CURL_CONSTANT(CURLM_BAD_EASY_HANDLE); REGISTER_CURL_CONSTANT(CURLM_BAD_HANDLE); REGISTER_CURL_CONSTANT(CURLM_CALL_MULTI_PERFORM); REGISTER_CURL_CONSTANT(CURLM_INTERNAL_ERROR); REGISTER_CURL_CONSTANT(CURLM_OK); REGISTER_CURL_CONSTANT(CURLM_OUT_OF_MEMORY); #if LIBCURL_VERSION_NUM >= 0x072001 /* Available since 7.32.1 */ REGISTER_CURL_CONSTANT(CURLM_ADDED_ALREADY); #endif /* Curl proxy constants */ REGISTER_CURL_CONSTANT(CURLPROXY_HTTP); REGISTER_CURL_CONSTANT(CURLPROXY_SOCKS4); REGISTER_CURL_CONSTANT(CURLPROXY_SOCKS5); /* Curl Share constants */ REGISTER_CURL_CONSTANT(CURLSHOPT_NONE); REGISTER_CURL_CONSTANT(CURLSHOPT_SHARE); REGISTER_CURL_CONSTANT(CURLSHOPT_UNSHARE); /* Curl Http Version constants (CURLOPT_HTTP_VERSION) */ REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_1_0); REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_1_1); REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_NONE); /* Curl Lock constants */ REGISTER_CURL_CONSTANT(CURL_LOCK_DATA_COOKIE); REGISTER_CURL_CONSTANT(CURL_LOCK_DATA_DNS); REGISTER_CURL_CONSTANT(CURL_LOCK_DATA_SSL_SESSION); /* Curl NETRC constants (CURLOPT_NETRC) */ REGISTER_CURL_CONSTANT(CURL_NETRC_IGNORED); REGISTER_CURL_CONSTANT(CURL_NETRC_OPTIONAL); REGISTER_CURL_CONSTANT(CURL_NETRC_REQUIRED); /* Curl SSL Version constants (CURLOPT_SSLVERSION) */ REGISTER_CURL_CONSTANT(CURL_SSLVERSION_DEFAULT); REGISTER_CURL_CONSTANT(CURL_SSLVERSION_SSLv2); REGISTER_CURL_CONSTANT(CURL_SSLVERSION_SSLv3); REGISTER_CURL_CONSTANT(CURL_SSLVERSION_TLSv1); /* Curl TIMECOND constants (CURLOPT_TIMECONDITION) */ REGISTER_CURL_CONSTANT(CURL_TIMECOND_IFMODSINCE); REGISTER_CURL_CONSTANT(CURL_TIMECOND_IFUNMODSINCE); REGISTER_CURL_CONSTANT(CURL_TIMECOND_LASTMOD); REGISTER_CURL_CONSTANT(CURL_TIMECOND_NONE); /* Curl version constants */ REGISTER_CURL_CONSTANT(CURL_VERSION_IPV6); REGISTER_CURL_CONSTANT(CURL_VERSION_KERBEROS4); REGISTER_CURL_CONSTANT(CURL_VERSION_LIBZ); REGISTER_CURL_CONSTANT(CURL_VERSION_SSL); #if LIBCURL_VERSION_NUM >= 0x070a06 /* Available since 7.10.6 */ REGISTER_CURL_CONSTANT(CURLOPT_HTTPAUTH); /* http authentication options */ REGISTER_CURL_CONSTANT(CURLAUTH_ANY); REGISTER_CURL_CONSTANT(CURLAUTH_ANYSAFE); REGISTER_CURL_CONSTANT(CURLAUTH_BASIC); REGISTER_CURL_CONSTANT(CURLAUTH_DIGEST); REGISTER_CURL_CONSTANT(CURLAUTH_GSSNEGOTIATE); REGISTER_CURL_CONSTANT(CURLAUTH_NONE); REGISTER_CURL_CONSTANT(CURLAUTH_NTLM); #endif #if LIBCURL_VERSION_NUM >= 0x070a07 /* Available since 7.10.7 */ REGISTER_CURL_CONSTANT(CURLINFO_HTTP_CONNECTCODE); REGISTER_CURL_CONSTANT(CURLOPT_FTP_CREATE_MISSING_DIRS); REGISTER_CURL_CONSTANT(CURLOPT_PROXYAUTH); #endif #if LIBCURL_VERSION_NUM >= 0x070a08 /* Available since 7.10.8 */ REGISTER_CURL_CONSTANT(CURLE_FILESIZE_EXCEEDED); REGISTER_CURL_CONSTANT(CURLE_LDAP_INVALID_URL); REGISTER_CURL_CONSTANT(CURLINFO_HTTPAUTH_AVAIL); REGISTER_CURL_CONSTANT(CURLINFO_RESPONSE_CODE); REGISTER_CURL_CONSTANT(CURLINFO_PROXYAUTH_AVAIL); REGISTER_CURL_CONSTANT(CURLOPT_FTP_RESPONSE_TIMEOUT); REGISTER_CURL_CONSTANT(CURLOPT_IPRESOLVE); REGISTER_CURL_CONSTANT(CURLOPT_MAXFILESIZE); REGISTER_CURL_CONSTANT(CURL_IPRESOLVE_V4); REGISTER_CURL_CONSTANT(CURL_IPRESOLVE_V6); REGISTER_CURL_CONSTANT(CURL_IPRESOLVE_WHATEVER); #endif #if LIBCURL_VERSION_NUM >= 0x070b00 /* Available since 7.11.0 */ REGISTER_CURL_CONSTANT(CURLE_FTP_SSL_FAILED); REGISTER_CURL_CONSTANT(CURLFTPSSL_ALL); REGISTER_CURL_CONSTANT(CURLFTPSSL_CONTROL); REGISTER_CURL_CONSTANT(CURLFTPSSL_NONE); REGISTER_CURL_CONSTANT(CURLFTPSSL_TRY); REGISTER_CURL_CONSTANT(CURLOPT_FTP_SSL); REGISTER_CURL_CONSTANT(CURLOPT_NETRC_FILE); #endif #if LIBCURL_VERSION_NUM >= 0x070c02 /* Available since 7.12.2 */ REGISTER_CURL_CONSTANT(CURLFTPAUTH_DEFAULT); REGISTER_CURL_CONSTANT(CURLFTPAUTH_SSL); REGISTER_CURL_CONSTANT(CURLFTPAUTH_TLS); REGISTER_CURL_CONSTANT(CURLOPT_FTPSSLAUTH); #endif #if LIBCURL_VERSION_NUM >= 0x070d00 /* Available since 7.13.0 */ REGISTER_CURL_CONSTANT(CURLOPT_FTP_ACCOUNT); #endif #if LIBCURL_VERSION_NUM >= 0x070b02 /* Available since 7.11.2 */ REGISTER_CURL_CONSTANT(CURLOPT_TCP_NODELAY); #endif #if LIBCURL_VERSION_NUM >= 0x070c02 /* Available since 7.12.2 */ REGISTER_CURL_CONSTANT(CURLINFO_OS_ERRNO); #endif #if LIBCURL_VERSION_NUM >= 0x070c03 /* Available since 7.12.3 */ REGISTER_CURL_CONSTANT(CURLINFO_NUM_CONNECTS); REGISTER_CURL_CONSTANT(CURLINFO_SSL_ENGINES); #endif #if LIBCURL_VERSION_NUM >= 0x070e01 /* Available since 7.14.1 */ REGISTER_CURL_CONSTANT(CURLINFO_COOKIELIST); REGISTER_CURL_CONSTANT(CURLOPT_COOKIELIST); REGISTER_CURL_CONSTANT(CURLOPT_IGNORE_CONTENT_LENGTH); #endif #if LIBCURL_VERSION_NUM >= 0x070f00 /* Available since 7.15.0 */ REGISTER_CURL_CONSTANT(CURLOPT_FTP_SKIP_PASV_IP); #endif #if LIBCURL_VERSION_NUM >= 0x070f01 /* Available since 7.15.1 */ REGISTER_CURL_CONSTANT(CURLOPT_FTP_FILEMETHOD); #endif #if LIBCURL_VERSION_NUM >= 0x070f02 /* Available since 7.15.2 */ REGISTER_CURL_CONSTANT(CURLOPT_CONNECT_ONLY); REGISTER_CURL_CONSTANT(CURLOPT_LOCALPORT); REGISTER_CURL_CONSTANT(CURLOPT_LOCALPORTRANGE); #endif #if LIBCURL_VERSION_NUM >= 0x070f03 /* Available since 7.15.3 */ REGISTER_CURL_CONSTANT(CURLFTPMETHOD_MULTICWD); REGISTER_CURL_CONSTANT(CURLFTPMETHOD_NOCWD); REGISTER_CURL_CONSTANT(CURLFTPMETHOD_SINGLECWD); #endif #if LIBCURL_VERSION_NUM >= 0x070f04 /* Available since 7.15.4 */ REGISTER_CURL_CONSTANT(CURLINFO_FTP_ENTRY_PATH); #endif #if LIBCURL_VERSION_NUM >= 0x070f05 /* Available since 7.15.5 */ REGISTER_CURL_CONSTANT(CURLOPT_FTP_ALTERNATIVE_TO_USER); REGISTER_CURL_CONSTANT(CURLOPT_MAX_RECV_SPEED_LARGE); REGISTER_CURL_CONSTANT(CURLOPT_MAX_SEND_SPEED_LARGE); #endif #if LIBCURL_VERSION_NUM >= 0x071000 /* Available since 7.16.0 */ REGISTER_CURL_CONSTANT(CURLE_SSL_CACERT_BADFILE); REGISTER_CURL_CONSTANT(CURLOPT_SSL_SESSIONID_CACHE); REGISTER_CURL_CONSTANT(CURLMOPT_PIPELINING); #endif #if LIBCURL_VERSION_NUM >= 0x071001 /* Available since 7.16.1 */ REGISTER_CURL_CONSTANT(CURLE_SSH); REGISTER_CURL_CONSTANT(CURLOPT_FTP_SSL_CCC); REGISTER_CURL_CONSTANT(CURLOPT_SSH_AUTH_TYPES); REGISTER_CURL_CONSTANT(CURLOPT_SSH_PRIVATE_KEYFILE); REGISTER_CURL_CONSTANT(CURLOPT_SSH_PUBLIC_KEYFILE); REGISTER_CURL_CONSTANT(CURLFTPSSL_CCC_ACTIVE); REGISTER_CURL_CONSTANT(CURLFTPSSL_CCC_NONE); REGISTER_CURL_CONSTANT(CURLFTPSSL_CCC_PASSIVE); #endif #if LIBCURL_VERSION_NUM >= 0x071002 /* Available since 7.16.2 */ REGISTER_CURL_CONSTANT(CURLOPT_CONNECTTIMEOUT_MS); REGISTER_CURL_CONSTANT(CURLOPT_HTTP_CONTENT_DECODING); REGISTER_CURL_CONSTANT(CURLOPT_HTTP_TRANSFER_DECODING); REGISTER_CURL_CONSTANT(CURLOPT_TIMEOUT_MS); #endif #if LIBCURL_VERSION_NUM >= 0x071003 /* Available since 7.16.3 */ REGISTER_CURL_CONSTANT(CURLMOPT_MAXCONNECTS); #endif #if LIBCURL_VERSION_NUM >= 0x071004 /* Available since 7.16.4 */ REGISTER_CURL_CONSTANT(CURLOPT_KRBLEVEL); REGISTER_CURL_CONSTANT(CURLOPT_NEW_DIRECTORY_PERMS); REGISTER_CURL_CONSTANT(CURLOPT_NEW_FILE_PERMS); #endif #if LIBCURL_VERSION_NUM >= 0x071100 /* Available since 7.17.0 */ REGISTER_CURL_CONSTANT(CURLOPT_APPEND); REGISTER_CURL_CONSTANT(CURLOPT_DIRLISTONLY); REGISTER_CURL_CONSTANT(CURLOPT_USE_SSL); /* Curl SSL Constants */ REGISTER_CURL_CONSTANT(CURLUSESSL_ALL); REGISTER_CURL_CONSTANT(CURLUSESSL_CONTROL); REGISTER_CURL_CONSTANT(CURLUSESSL_NONE); REGISTER_CURL_CONSTANT(CURLUSESSL_TRY); #endif #if LIBCURL_VERSION_NUM >= 0x071101 /* Available since 7.17.1 */ REGISTER_CURL_CONSTANT(CURLOPT_SSH_HOST_PUBLIC_KEY_MD5); #endif #if LIBCURL_VERSION_NUM >= 0x071200 /* Available since 7.18.0 */ REGISTER_CURL_CONSTANT(CURLOPT_PROXY_TRANSFER_MODE); REGISTER_CURL_CONSTANT(CURLPAUSE_ALL); REGISTER_CURL_CONSTANT(CURLPAUSE_CONT); REGISTER_CURL_CONSTANT(CURLPAUSE_RECV); REGISTER_CURL_CONSTANT(CURLPAUSE_RECV_CONT); REGISTER_CURL_CONSTANT(CURLPAUSE_SEND); REGISTER_CURL_CONSTANT(CURLPAUSE_SEND_CONT); REGISTER_CURL_CONSTANT(CURL_READFUNC_PAUSE); REGISTER_CURL_CONSTANT(CURL_WRITEFUNC_PAUSE); REGISTER_CURL_CONSTANT(CURLPROXY_SOCKS4A); REGISTER_CURL_CONSTANT(CURLPROXY_SOCKS5_HOSTNAME); #endif #if LIBCURL_VERSION_NUM >= 0x071202 /* Available since 7.18.2 */ REGISTER_CURL_CONSTANT(CURLINFO_REDIRECT_URL); #endif #if LIBCURL_VERSION_NUM >= 0x071300 /* Available since 7.19.0 */ REGISTER_CURL_CONSTANT(CURLINFO_APPCONNECT_TIME); REGISTER_CURL_CONSTANT(CURLINFO_PRIMARY_IP); REGISTER_CURL_CONSTANT(CURLOPT_ADDRESS_SCOPE); REGISTER_CURL_CONSTANT(CURLOPT_CRLFILE); REGISTER_CURL_CONSTANT(CURLOPT_ISSUERCERT); REGISTER_CURL_CONSTANT(CURLOPT_KEYPASSWD); REGISTER_CURL_CONSTANT(CURLSSH_AUTH_ANY); REGISTER_CURL_CONSTANT(CURLSSH_AUTH_DEFAULT); REGISTER_CURL_CONSTANT(CURLSSH_AUTH_HOST); REGISTER_CURL_CONSTANT(CURLSSH_AUTH_KEYBOARD); REGISTER_CURL_CONSTANT(CURLSSH_AUTH_NONE); REGISTER_CURL_CONSTANT(CURLSSH_AUTH_PASSWORD); REGISTER_CURL_CONSTANT(CURLSSH_AUTH_PUBLICKEY); #endif #if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */ REGISTER_CURL_CONSTANT(CURLINFO_CERTINFO); REGISTER_CURL_CONSTANT(CURLOPT_CERTINFO); REGISTER_CURL_CONSTANT(CURLOPT_PASSWORD); REGISTER_CURL_CONSTANT(CURLOPT_POSTREDIR); REGISTER_CURL_CONSTANT(CURLOPT_PROXYPASSWORD); REGISTER_CURL_CONSTANT(CURLOPT_PROXYUSERNAME); REGISTER_CURL_CONSTANT(CURLOPT_USERNAME); REGISTER_CURL_CONSTANT(CURL_REDIR_POST_301); REGISTER_CURL_CONSTANT(CURL_REDIR_POST_302); REGISTER_CURL_CONSTANT(CURL_REDIR_POST_ALL); #endif #if LIBCURL_VERSION_NUM >= 0x071303 /* Available since 7.19.3 */ REGISTER_CURL_CONSTANT(CURLAUTH_DIGEST_IE); #endif #if LIBCURL_VERSION_NUM >= 0x071304 /* Available since 7.19.4 */ REGISTER_CURL_CONSTANT(CURLINFO_CONDITION_UNMET); REGISTER_CURL_CONSTANT(CURLOPT_NOPROXY); REGISTER_CURL_CONSTANT(CURLOPT_PROTOCOLS); REGISTER_CURL_CONSTANT(CURLOPT_REDIR_PROTOCOLS); REGISTER_CURL_CONSTANT(CURLOPT_SOCKS5_GSSAPI_NEC); REGISTER_CURL_CONSTANT(CURLOPT_SOCKS5_GSSAPI_SERVICE); REGISTER_CURL_CONSTANT(CURLOPT_TFTP_BLKSIZE); REGISTER_CURL_CONSTANT(CURLPROTO_ALL); REGISTER_CURL_CONSTANT(CURLPROTO_DICT); REGISTER_CURL_CONSTANT(CURLPROTO_FILE); REGISTER_CURL_CONSTANT(CURLPROTO_FTP); REGISTER_CURL_CONSTANT(CURLPROTO_FTPS); REGISTER_CURL_CONSTANT(CURLPROTO_HTTP); REGISTER_CURL_CONSTANT(CURLPROTO_HTTPS); REGISTER_CURL_CONSTANT(CURLPROTO_LDAP); REGISTER_CURL_CONSTANT(CURLPROTO_LDAPS); REGISTER_CURL_CONSTANT(CURLPROTO_SCP); REGISTER_CURL_CONSTANT(CURLPROTO_SFTP); REGISTER_CURL_CONSTANT(CURLPROTO_TELNET); REGISTER_CURL_CONSTANT(CURLPROTO_TFTP); REGISTER_CURL_CONSTANT(CURLPROXY_HTTP_1_0); REGISTER_CURL_CONSTANT(CURLFTP_CREATE_DIR); REGISTER_CURL_CONSTANT(CURLFTP_CREATE_DIR_NONE); REGISTER_CURL_CONSTANT(CURLFTP_CREATE_DIR_RETRY); #endif #if LIBCURL_VERSION_NUM >= 0x071306 /* Available since 7.19.6 */ REGISTER_CURL_CONSTANT(CURLOPT_SSH_KNOWNHOSTS); #endif #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ REGISTER_CURL_CONSTANT(CURLINFO_RTSP_CLIENT_CSEQ); REGISTER_CURL_CONSTANT(CURLINFO_RTSP_CSEQ_RECV); REGISTER_CURL_CONSTANT(CURLINFO_RTSP_SERVER_CSEQ); REGISTER_CURL_CONSTANT(CURLINFO_RTSP_SESSION_ID); REGISTER_CURL_CONSTANT(CURLOPT_FTP_USE_PRET); REGISTER_CURL_CONSTANT(CURLOPT_MAIL_FROM); REGISTER_CURL_CONSTANT(CURLOPT_MAIL_RCPT); REGISTER_CURL_CONSTANT(CURLOPT_RTSP_CLIENT_CSEQ); REGISTER_CURL_CONSTANT(CURLOPT_RTSP_REQUEST); REGISTER_CURL_CONSTANT(CURLOPT_RTSP_SERVER_CSEQ); REGISTER_CURL_CONSTANT(CURLOPT_RTSP_SESSION_ID); REGISTER_CURL_CONSTANT(CURLOPT_RTSP_STREAM_URI); REGISTER_CURL_CONSTANT(CURLOPT_RTSP_TRANSPORT); REGISTER_CURL_CONSTANT(CURLPROTO_IMAP); REGISTER_CURL_CONSTANT(CURLPROTO_IMAPS); REGISTER_CURL_CONSTANT(CURLPROTO_POP3); REGISTER_CURL_CONSTANT(CURLPROTO_POP3S); REGISTER_CURL_CONSTANT(CURLPROTO_RTSP); REGISTER_CURL_CONSTANT(CURLPROTO_SMTP); REGISTER_CURL_CONSTANT(CURLPROTO_SMTPS); REGISTER_CURL_CONSTANT(CURL_RTSPREQ_ANNOUNCE); REGISTER_CURL_CONSTANT(CURL_RTSPREQ_DESCRIBE); REGISTER_CURL_CONSTANT(CURL_RTSPREQ_GET_PARAMETER); REGISTER_CURL_CONSTANT(CURL_RTSPREQ_OPTIONS); REGISTER_CURL_CONSTANT(CURL_RTSPREQ_PAUSE); REGISTER_CURL_CONSTANT(CURL_RTSPREQ_PLAY); REGISTER_CURL_CONSTANT(CURL_RTSPREQ_RECEIVE); REGISTER_CURL_CONSTANT(CURL_RTSPREQ_RECORD); REGISTER_CURL_CONSTANT(CURL_RTSPREQ_SET_PARAMETER); REGISTER_CURL_CONSTANT(CURL_RTSPREQ_SETUP); REGISTER_CURL_CONSTANT(CURL_RTSPREQ_TEARDOWN); #endif #if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */ REGISTER_CURL_CONSTANT(CURLINFO_LOCAL_IP); REGISTER_CURL_CONSTANT(CURLINFO_LOCAL_PORT); REGISTER_CURL_CONSTANT(CURLINFO_PRIMARY_PORT); REGISTER_CURL_CONSTANT(CURLOPT_FNMATCH_FUNCTION); REGISTER_CURL_CONSTANT(CURLOPT_WILDCARDMATCH); REGISTER_CURL_CONSTANT(CURLPROTO_RTMP); REGISTER_CURL_CONSTANT(CURLPROTO_RTMPE); REGISTER_CURL_CONSTANT(CURLPROTO_RTMPS); REGISTER_CURL_CONSTANT(CURLPROTO_RTMPT); REGISTER_CURL_CONSTANT(CURLPROTO_RTMPTE); REGISTER_CURL_CONSTANT(CURLPROTO_RTMPTS); REGISTER_CURL_CONSTANT(CURL_FNMATCHFUNC_FAIL); REGISTER_CURL_CONSTANT(CURL_FNMATCHFUNC_MATCH); REGISTER_CURL_CONSTANT(CURL_FNMATCHFUNC_NOMATCH); #endif #if LIBCURL_VERSION_NUM >= 0x071502 /* Available since 7.21.2 */ REGISTER_CURL_CONSTANT(CURLPROTO_GOPHER); #endif #if LIBCURL_VERSION_NUM >= 0x071503 /* Available since 7.21.3 */ REGISTER_CURL_CONSTANT(CURLAUTH_ONLY); REGISTER_CURL_CONSTANT(CURLOPT_RESOLVE); #endif #if LIBCURL_VERSION_NUM >= 0x071504 /* Available since 7.21.4 */ REGISTER_CURL_CONSTANT(CURLOPT_TLSAUTH_PASSWORD); REGISTER_CURL_CONSTANT(CURLOPT_TLSAUTH_TYPE); REGISTER_CURL_CONSTANT(CURLOPT_TLSAUTH_USERNAME); REGISTER_CURL_CONSTANT(CURL_TLSAUTH_SRP); #endif #if LIBCURL_VERSION_NUM >= 0x071506 /* Available since 7.21.6 */ REGISTER_CURL_CONSTANT(CURLOPT_ACCEPT_ENCODING); REGISTER_CURL_CONSTANT(CURLOPT_TRANSFER_ENCODING); #endif #if LIBCURL_VERSION_NUM >= 0x071600 /* Available since 7.22.0 */ REGISTER_CURL_CONSTANT(CURLAUTH_NTLM_WB); REGISTER_CURL_CONSTANT(CURLGSSAPI_DELEGATION_FLAG); REGISTER_CURL_CONSTANT(CURLGSSAPI_DELEGATION_POLICY_FLAG); REGISTER_CURL_CONSTANT(CURLOPT_GSSAPI_DELEGATION); #endif #if LIBCURL_VERSION_NUM >= 0x071800 /* Available since 7.24.0 */ REGISTER_CURL_CONSTANT(CURLOPT_ACCEPTTIMEOUT_MS); REGISTER_CURL_CONSTANT(CURLOPT_DNS_SERVERS); #endif #if LIBCURL_VERSION_NUM >= 0x071900 /* Available since 7.25.0 */ REGISTER_CURL_CONSTANT(CURLOPT_MAIL_AUTH); REGISTER_CURL_CONSTANT(CURLOPT_SSL_OPTIONS); REGISTER_CURL_CONSTANT(CURLOPT_TCP_KEEPALIVE); REGISTER_CURL_CONSTANT(CURLOPT_TCP_KEEPIDLE); REGISTER_CURL_CONSTANT(CURLOPT_TCP_KEEPINTVL); REGISTER_CURL_CONSTANT(CURLSSLOPT_ALLOW_BEAST); #endif #if LIBCURL_VERSION_NUM >= 0x071901 /* Available since 7.25.1 */ REGISTER_CURL_CONSTANT(CURL_REDIR_POST_303); #endif #if LIBCURL_VERSION_NUM >= 0x071c00 /* Available since 7.28.0 */ REGISTER_CURL_CONSTANT(CURLSSH_AUTH_AGENT); #endif #if LIBCURL_VERSION_NUM >= 0x071e00 /* Available since 7.30.0 */ REGISTER_CURL_CONSTANT(CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE); REGISTER_CURL_CONSTANT(CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE); REGISTER_CURL_CONSTANT(CURLMOPT_MAX_HOST_CONNECTIONS); REGISTER_CURL_CONSTANT(CURLMOPT_MAX_PIPELINE_LENGTH); REGISTER_CURL_CONSTANT(CURLMOPT_MAX_TOTAL_CONNECTIONS); #endif #if LIBCURL_VERSION_NUM >= 0x071f00 /* Available since 7.31.0 */ REGISTER_CURL_CONSTANT(CURLOPT_SASL_IR); #endif #if LIBCURL_VERSION_NUM >= 0x072100 /* Available since 7.33.0 */ REGISTER_CURL_CONSTANT(CURLOPT_DNS_INTERFACE); REGISTER_CURL_CONSTANT(CURLOPT_DNS_LOCAL_IP4); REGISTER_CURL_CONSTANT(CURLOPT_DNS_LOCAL_IP6); REGISTER_CURL_CONSTANT(CURLOPT_XOAUTH2_BEARER); REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_2_0); REGISTER_CURL_CONSTANT(CURL_VERSION_HTTP2); #endif #if LIBCURL_VERSION_NUM >= 0x072200 /* Available since 7.34.0 */ REGISTER_CURL_CONSTANT(CURLOPT_LOGIN_OPTIONS); REGISTER_CURL_CONSTANT(CURL_SSLVERSION_TLSv1_0); REGISTER_CURL_CONSTANT(CURL_SSLVERSION_TLSv1_1); REGISTER_CURL_CONSTANT(CURL_SSLVERSION_TLSv1_2); #endif #if LIBCURL_VERSION_NUM >= 0x072400 /* Available since 7.36.0 */ REGISTER_CURL_CONSTANT(CURLOPT_EXPECT_100_TIMEOUT_MS); REGISTER_CURL_CONSTANT(CURLOPT_SSL_ENABLE_ALPN); REGISTER_CURL_CONSTANT(CURLOPT_SSL_ENABLE_NPN); #endif #if LIBCURL_VERSION_NUM >= 0x072500 /* Available since 7.37.0 */ REGISTER_CURL_CONSTANT(CURLHEADER_SEPARATE); REGISTER_CURL_CONSTANT(CURLHEADER_UNIFIED); REGISTER_CURL_CONSTANT(CURLOPT_HEADEROPT); REGISTER_CURL_CONSTANT(CURLOPT_PROXYHEADER); #endif #if LIBCURL_VERSION_NUM >= 0x072600 /* Available since 7.38.0 */ REGISTER_CURL_CONSTANT(CURLAUTH_NEGOTIATE); #endif #if LIBCURL_VERSION_NUM >= 0x072700 /* Available since 7.39.0 */ REGISTER_CURL_CONSTANT(CURLOPT_PINNEDPUBLICKEY); #endif #if LIBCURL_VERSION_NUM >= 0x072800 /* Available since 7.40.0 */ REGISTER_CURL_CONSTANT(CURLOPT_UNIX_SOCKET_PATH); REGISTER_CURL_CONSTANT(CURLPROTO_SMB); REGISTER_CURL_CONSTANT(CURLPROTO_SMBS); #endif #if LIBCURL_VERSION_NUM >= 0x072900 /* Available since 7.41.0 */ REGISTER_CURL_CONSTANT(CURLOPT_SSL_VERIFYSTATUS); #endif #if LIBCURL_VERSION_NUM >= 0x072a00 /* Available since 7.42.0 */ REGISTER_CURL_CONSTANT(CURLOPT_PATH_AS_IS); REGISTER_CURL_CONSTANT(CURLOPT_SSL_FALSESTART); #endif #if LIBCURL_VERSION_NUM >= 0x072b00 /* Available since 7.43.0 */ REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_2); REGISTER_CURL_CONSTANT(CURLOPT_PIPEWAIT); REGISTER_CURL_CONSTANT(CURLOPT_PROXY_SERVICE_NAME); REGISTER_CURL_CONSTANT(CURLOPT_SERVICE_NAME); REGISTER_CURL_CONSTANT(CURLPIPE_NOTHING); REGISTER_CURL_CONSTANT(CURLPIPE_HTTP1); REGISTER_CURL_CONSTANT(CURLPIPE_MULTIPLEX); #endif #if LIBCURL_VERSION_NUM >= 0x072c00 /* Available since 7.44.0 */ REGISTER_CURL_CONSTANT(CURLSSLOPT_NO_REVOKE); #endif #if LIBCURL_VERSION_NUM >= 0x072d00 /* Available since 7.45.0 */ REGISTER_CURL_CONSTANT(CURLOPT_DEFAULT_PROTOCOL); #endif #if LIBCURL_VERSION_NUM >= 0x072e00 /* Available since 7.46.0 */ REGISTER_CURL_CONSTANT(CURLOPT_STREAM_WEIGHT); #endif #if LIBCURL_VERSION_NUM >= 0x072f00 /* Available since 7.47.0 */ REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_2TLS); #endif #if LIBCURL_VERSION_NUM >= 0x073000 /* Available since 7.48.0 */ REGISTER_CURL_CONSTANT(CURLOPT_TFTP_NO_OPTIONS); #endif #if LIBCURL_VERSION_NUM >= 0x073100 /* Available since 7.49.0 */ REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE); REGISTER_CURL_CONSTANT(CURLOPT_CONNECT_TO); REGISTER_CURL_CONSTANT(CURLOPT_TCP_FASTOPEN); #endif #if CURLOPT_FTPASCII != 0 REGISTER_CURL_CONSTANT(CURLOPT_FTPASCII); #endif #if CURLOPT_MUTE != 0 REGISTER_CURL_CONSTANT(CURLOPT_MUTE); #endif #if CURLOPT_PASSWDFUNCTION != 0 REGISTER_CURL_CONSTANT(CURLOPT_PASSWDFUNCTION); #endif REGISTER_CURL_CONSTANT(CURLOPT_SAFE_UPLOAD); #ifdef PHP_CURL_NEED_OPENSSL_TSL if (!CRYPTO_get_id_callback()) { int i, c = CRYPTO_num_locks(); php_curl_openssl_tsl = malloc(c * sizeof(MUTEX_T)); if (!php_curl_openssl_tsl) { return FAILURE; } for (i = 0; i < c; ++i) { php_curl_openssl_tsl[i] = tsrm_mutex_alloc(); } CRYPTO_set_id_callback(php_curl_ssl_id); CRYPTO_set_locking_callback(php_curl_ssl_lock); } #endif #ifdef PHP_CURL_NEED_GNUTLS_TSL gcry_control(GCRYCTL_SET_THREAD_CBS, &php_curl_gnutls_tsl); #endif if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) { return FAILURE; } curlfile_register_class(); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(curl) { curl_global_cleanup(); #ifdef PHP_CURL_NEED_OPENSSL_TSL if (php_curl_openssl_tsl) { int i, c = CRYPTO_num_locks(); CRYPTO_set_id_callback(NULL); CRYPTO_set_locking_callback(NULL); for (i = 0; i < c; ++i) { tsrm_mutex_free(php_curl_openssl_tsl[i]); } free(php_curl_openssl_tsl); php_curl_openssl_tsl = NULL; } #endif UNREGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* {{{ curl_write_nothing * Used as a work around. See _php_curl_close_ex */ static size_t curl_write_nothing(char *data, size_t size, size_t nmemb, void *ctx) { return size * nmemb; } /* }}} */ /* {{{ curl_write */ static size_t curl_write(char *data, size_t size, size_t nmemb, void *ctx) { php_curl *ch = (php_curl *) ctx; php_curl_write *t = ch->handlers->write; size_t length = size * nmemb; #if PHP_CURL_DEBUG fprintf(stderr, "curl_write() called\n"); fprintf(stderr, "data = %s, size = %d, nmemb = %d, ctx = %x\n", data, size, nmemb, ctx); #endif switch (t->method) { case PHP_CURL_STDOUT: PHPWRITE(data, length); break; case PHP_CURL_FILE: return fwrite(data, size, nmemb, t->fp); case PHP_CURL_RETURN: if (length > 0) { smart_str_appendl(&t->buf, data, (int) length); } break; case PHP_CURL_USER: { zval argv[2]; zval retval; int error; zend_fcall_info fci; ZVAL_RES(&argv[0], ch->res); Z_ADDREF(argv[0]); ZVAL_STRINGL(&argv[1], data, length); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.object = NULL; ZVAL_COPY_VALUE(&fci.function_name, &t->func_name); fci.retval = &retval; fci.param_count = 2; fci.params = argv; fci.no_separation = 0; fci.symbol_table = NULL; ch->in_callback = 1; error = zend_call_function(&fci, &t->fci_cache); ch->in_callback = 0; if (error == FAILURE) { php_error_docref(NULL, E_WARNING, "Could not call the CURLOPT_WRITEFUNCTION"); length = -1; } else if (!Z_ISUNDEF(retval)) { _php_curl_verify_handlers(ch, 1); length = zval_get_long(&retval); } zval_ptr_dtor(&argv[0]); zval_ptr_dtor(&argv[1]); break; } } return length; } /* }}} */ #if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */ /* {{{ curl_fnmatch */ static int curl_fnmatch(void *ctx, const char *pattern, const char *string) { php_curl *ch = (php_curl *) ctx; php_curl_fnmatch *t = ch->handlers->fnmatch; int rval = CURL_FNMATCHFUNC_FAIL; switch (t->method) { case PHP_CURL_USER: { zval argv[3]; zval retval; int error; zend_fcall_info fci; ZVAL_RES(&argv[0], ch->res); Z_ADDREF(argv[0]); ZVAL_STRING(&argv[1], pattern); ZVAL_STRING(&argv[2], string); fci.size = sizeof(fci); fci.function_table = EG(function_table); ZVAL_COPY_VALUE(&fci.function_name, &t->func_name); fci.object = NULL; fci.retval = &retval; fci.param_count = 3; fci.params = argv; fci.no_separation = 0; fci.symbol_table = NULL; ch->in_callback = 1; error = zend_call_function(&fci, &t->fci_cache); ch->in_callback = 0; if (error == FAILURE) { php_error_docref(NULL, E_WARNING, "Cannot call the CURLOPT_FNMATCH_FUNCTION"); } else if (!Z_ISUNDEF(retval)) { _php_curl_verify_handlers(ch, 1); rval = zval_get_long(&retval); } zval_ptr_dtor(&argv[0]); zval_ptr_dtor(&argv[1]); zval_ptr_dtor(&argv[2]); break; } } return rval; } /* }}} */ #endif /* {{{ curl_progress */ static size_t curl_progress(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow) { php_curl *ch = (php_curl *)clientp; php_curl_progress *t = ch->handlers->progress; size_t rval = 0; #if PHP_CURL_DEBUG fprintf(stderr, "curl_progress() called\n"); fprintf(stderr, "clientp = %x, dltotal = %f, dlnow = %f, ultotal = %f, ulnow = %f\n", clientp, dltotal, dlnow, ultotal, ulnow); #endif switch (t->method) { case PHP_CURL_USER: { zval argv[5]; zval retval; int error; zend_fcall_info fci; ZVAL_RES(&argv[0], ch->res); Z_ADDREF(argv[0]); ZVAL_LONG(&argv[1], (zend_long)dltotal); ZVAL_LONG(&argv[2], (zend_long)dlnow); ZVAL_LONG(&argv[3], (zend_long)ultotal); ZVAL_LONG(&argv[4], (zend_long)ulnow); fci.size = sizeof(fci); fci.function_table = EG(function_table); ZVAL_COPY_VALUE(&fci.function_name, &t->func_name); fci.object = NULL; fci.retval = &retval; fci.param_count = 5; fci.params = argv; fci.no_separation = 0; fci.symbol_table = NULL; ch->in_callback = 1; error = zend_call_function(&fci, &t->fci_cache); ch->in_callback = 0; if (error == FAILURE) { php_error_docref(NULL, E_WARNING, "Cannot call the CURLOPT_PROGRESSFUNCTION"); } else if (!Z_ISUNDEF(retval)) { _php_curl_verify_handlers(ch, 1); if (0 != zval_get_long(&retval)) { rval = 1; } } zval_ptr_dtor(&argv[0]); zval_ptr_dtor(&argv[1]); zval_ptr_dtor(&argv[2]); zval_ptr_dtor(&argv[3]); zval_ptr_dtor(&argv[4]); break; } } return rval; } /* }}} */ /* {{{ curl_read */ static size_t curl_read(char *data, size_t size, size_t nmemb, void *ctx) { php_curl *ch = (php_curl *)ctx; php_curl_read *t = ch->handlers->read; int length = 0; switch (t->method) { case PHP_CURL_DIRECT: if (t->fp) { length = fread(data, size, nmemb, t->fp); } break; case PHP_CURL_USER: { zval argv[3]; zval retval; int error; zend_fcall_info fci; ZVAL_RES(&argv[0], ch->res); Z_ADDREF(argv[0]); if (t->res) { ZVAL_RES(&argv[1], t->res); Z_ADDREF(argv[1]); } else { ZVAL_NULL(&argv[1]); } ZVAL_LONG(&argv[2], (int)size * nmemb); fci.size = sizeof(fci); fci.function_table = EG(function_table); ZVAL_COPY_VALUE(&fci.function_name, &t->func_name); fci.object = NULL; fci.retval = &retval; fci.param_count = 3; fci.params = argv; fci.no_separation = 0; fci.symbol_table = NULL; ch->in_callback = 1; error = zend_call_function(&fci, &t->fci_cache); ch->in_callback = 0; if (error == FAILURE) { php_error_docref(NULL, E_WARNING, "Cannot call the CURLOPT_READFUNCTION"); #if LIBCURL_VERSION_NUM >= 0x070c01 /* 7.12.1 */ length = CURL_READFUNC_ABORT; #endif } else if (!Z_ISUNDEF(retval)) { _php_curl_verify_handlers(ch, 1); if (Z_TYPE(retval) == IS_STRING) { length = MIN((int) (size * nmemb), Z_STRLEN(retval)); memcpy(data, Z_STRVAL(retval), length); } zval_ptr_dtor(&retval); } zval_ptr_dtor(&argv[0]); zval_ptr_dtor(&argv[1]); zval_ptr_dtor(&argv[2]); break; } } return length; } /* }}} */ /* {{{ curl_write_header */ static size_t curl_write_header(char *data, size_t size, size_t nmemb, void *ctx) { php_curl *ch = (php_curl *) ctx; php_curl_write *t = ch->handlers->write_header; size_t length = size * nmemb; switch (t->method) { case PHP_CURL_STDOUT: /* Handle special case write when we're returning the entire transfer */ if (ch->handlers->write->method == PHP_CURL_RETURN && length > 0) { smart_str_appendl(&ch->handlers->write->buf, data, (int) length); } else { PHPWRITE(data, length); } break; case PHP_CURL_FILE: return fwrite(data, size, nmemb, t->fp); case PHP_CURL_USER: { zval argv[2]; zval retval; int error; zend_fcall_info fci; ZVAL_RES(&argv[0], ch->res); Z_ADDREF(argv[0]); ZVAL_STRINGL(&argv[1], data, length); fci.size = sizeof(fci); fci.function_table = EG(function_table); ZVAL_COPY_VALUE(&fci.function_name, &t->func_name); fci.symbol_table = NULL; fci.object = NULL; fci.retval = &retval; fci.param_count = 2; fci.params = argv; fci.no_separation = 0; ch->in_callback = 1; error = zend_call_function(&fci, &t->fci_cache); ch->in_callback = 0; if (error == FAILURE) { php_error_docref(NULL, E_WARNING, "Could not call the CURLOPT_HEADERFUNCTION"); length = -1; } else if (!Z_ISUNDEF(retval)) { _php_curl_verify_handlers(ch, 1); length = zval_get_long(&retval); } zval_ptr_dtor(&argv[0]); zval_ptr_dtor(&argv[1]); break; } case PHP_CURL_IGNORE: return length; default: return -1; } return length; } /* }}} */ static int curl_debug(CURL *cp, curl_infotype type, char *buf, size_t buf_len, void *ctx) /* {{{ */ { php_curl *ch = (php_curl *)ctx; if (type == CURLINFO_HEADER_OUT) { if (ch->header.str) { zend_string_release(ch->header.str); } if (buf_len > 0) { ch->header.str = zend_string_init(buf, buf_len, 0); } } return 0; } /* }}} */ #if CURLOPT_PASSWDFUNCTION != 0 /* {{{ curl_passwd */ static size_t curl_passwd(void *ctx, char *prompt, char *buf, int buflen) { php_curl *ch = (php_curl *) ctx; zval *func = &ch->handlers->passwd; zval argv[3]; zval retval; int error; int ret = -1; ZVAL_RES(&argv[0], ch->res); Z_ADDREF(argv[0]); ZVAL_STRING(&argv[1], prompt); ZVAL_LONG(&argv[2], buflen); error = call_user_function(EG(function_table), NULL, func, &retval, 2, argv); if (error == FAILURE) { php_error_docref(NULL, E_WARNING, "Could not call the CURLOPT_PASSWDFUNCTION"); } else if (Z_TYPE(retval) == IS_STRING) { if (Z_STRLEN(retval) > buflen) { php_error_docref(NULL, E_WARNING, "Returned password is too long for libcurl to handle"); } else { memcpy(buf, Z_STRVAL(retval), Z_STRLEN(retval) + 1); } } else { php_error_docref(NULL, E_WARNING, "User handler '%s' did not return a string", Z_STRVAL_P(func)); } zval_ptr_dtor(&argv[0]); zval_ptr_dtor(&argv[1]); zval_ptr_dtor(&argv[2]); zval_ptr_dtor(&retval); return ret; } /* }}} */ #endif /* {{{ curl_free_string */ static void curl_free_string(void **string) { efree((char *)*string); } /* }}} */ /* {{{ curl_free_post */ static void curl_free_post(void **post) { curl_formfree((struct HttpPost *)*post); } /* }}} */ /* {{{ curl_free_slist */ static void curl_free_slist(zval *el) { curl_slist_free_all(((struct curl_slist *)Z_PTR_P(el))); } /* }}} */ /* {{{ proto array curl_version([int version]) Return cURL version information. */ PHP_FUNCTION(curl_version) { curl_version_info_data *d; zend_long uversion = CURLVERSION_NOW; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &uversion) == FAILURE) { return; } d = curl_version_info(uversion); if (d == NULL) { RETURN_FALSE; } array_init(return_value); CAAL("version_number", d->version_num); CAAL("age", d->age); CAAL("features", d->features); CAAL("ssl_version_number", d->ssl_version_num); CAAS("version", d->version); CAAS("host", d->host); CAAS("ssl_version", d->ssl_version); CAAS("libz_version", d->libz_version); /* Add an array of protocols */ { char **p = (char **) d->protocols; zval protocol_list; array_init(&protocol_list); while (*p != NULL) { add_next_index_string(&protocol_list, *p); p++; } CAAZ("protocols", &protocol_list); } } /* }}} */ /* {{{ alloc_curl_handle */ static php_curl *alloc_curl_handle() { php_curl *ch = ecalloc(1, sizeof(php_curl)); ch->to_free = ecalloc(1, sizeof(struct _php_curl_free)); ch->handlers = ecalloc(1, sizeof(php_curl_handlers)); ch->handlers->write = ecalloc(1, sizeof(php_curl_write)); ch->handlers->write_header = ecalloc(1, sizeof(php_curl_write)); ch->handlers->read = ecalloc(1, sizeof(php_curl_read)); ch->handlers->progress = NULL; #if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */ ch->handlers->fnmatch = NULL; #endif ch->clone = emalloc(sizeof(uint32_t)); *ch->clone = 1; memset(&ch->err, 0, sizeof(struct _php_curl_error)); zend_llist_init(&ch->to_free->str, sizeof(char *), (llist_dtor_func_t)curl_free_string, 0); zend_llist_init(&ch->to_free->post, sizeof(struct HttpPost *), (llist_dtor_func_t)curl_free_post, 0); ch->to_free->slist = emalloc(sizeof(HashTable)); zend_hash_init(ch->to_free->slist, 4, NULL, curl_free_slist, 0); return ch; } /* }}} */ #if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */ /* {{{ create_certinfo */ static void create_certinfo(struct curl_certinfo *ci, zval *listcode) { int i; if (ci) { zval certhash; for (i=0; i<ci->num_of_certs; i++) { struct curl_slist *slist; array_init(&certhash); for (slist = ci->certinfo[i]; slist; slist = slist->next) { int len; char s[64]; char *tmp; strncpy(s, slist->data, 64); tmp = memchr(s, ':', 64); if(tmp) { *tmp = '\0'; len = strlen(s); add_assoc_string(&certhash, s, &slist->data[len+1]); } else { php_error_docref(NULL, E_WARNING, "Could not extract hash key from certificate info"); } } add_next_index_zval(listcode, &certhash); } } } /* }}} */ #endif /* {{{ _php_curl_set_default_options() Set default options for a handle */ static void _php_curl_set_default_options(php_curl *ch) { char *cainfo; curl_easy_setopt(ch->cp, CURLOPT_NOPROGRESS, 1); curl_easy_setopt(ch->cp, CURLOPT_VERBOSE, 0); curl_easy_setopt(ch->cp, CURLOPT_ERRORBUFFER, ch->err.str); curl_easy_setopt(ch->cp, CURLOPT_WRITEFUNCTION, curl_write); curl_easy_setopt(ch->cp, CURLOPT_FILE, (void *) ch); curl_easy_setopt(ch->cp, CURLOPT_READFUNCTION, curl_read); curl_easy_setopt(ch->cp, CURLOPT_INFILE, (void *) ch); curl_easy_setopt(ch->cp, CURLOPT_HEADERFUNCTION, curl_write_header); curl_easy_setopt(ch->cp, CURLOPT_WRITEHEADER, (void *) ch); #if !defined(ZTS) curl_easy_setopt(ch->cp, CURLOPT_DNS_USE_GLOBAL_CACHE, 1); #endif curl_easy_setopt(ch->cp, CURLOPT_DNS_CACHE_TIMEOUT, 120); curl_easy_setopt(ch->cp, CURLOPT_MAXREDIRS, 20); /* prevent infinite redirects */ cainfo = INI_STR("openssl.cafile"); if (!(cainfo && cainfo[0] != '\0')) { cainfo = INI_STR("curl.cainfo"); } if (cainfo && cainfo[0] != '\0') { curl_easy_setopt(ch->cp, CURLOPT_CAINFO, cainfo); } #if defined(ZTS) curl_easy_setopt(ch->cp, CURLOPT_NOSIGNAL, 1); #endif } /* }}} */ /* {{{ proto resource curl_init([string url]) Initialize a cURL session */ PHP_FUNCTION(curl_init) { php_curl *ch; CURL *cp; char *url = NULL; size_t url_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s", &url, &url_len) == FAILURE) { return; } cp = curl_easy_init(); if (!cp) { php_error_docref(NULL, E_WARNING, "Could not initialize a new cURL handle"); RETURN_FALSE; } ch = alloc_curl_handle(); ch->cp = cp; ch->handlers->write->method = PHP_CURL_STDOUT; ch->handlers->read->method = PHP_CURL_DIRECT; ch->handlers->write_header->method = PHP_CURL_IGNORE; _php_curl_set_default_options(ch); if (url) { if (php_curl_option_url(ch, url, url_len) == FAILURE) { _php_curl_close_ex(ch); RETURN_FALSE; } } ZVAL_RES(return_value, zend_register_resource(ch, le_curl)); ch->res = Z_RES_P(return_value); } /* }}} */ /* {{{ proto resource curl_copy_handle(resource ch) Copy a cURL handle along with all of it's preferences */ PHP_FUNCTION(curl_copy_handle) { CURL *cp; zval *zid; php_curl *ch, *dupch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } cp = curl_easy_duphandle(ch->cp); if (!cp) { php_error_docref(NULL, E_WARNING, "Cannot duplicate cURL handle"); RETURN_FALSE; } dupch = alloc_curl_handle(); dupch->cp = cp; Z_ADDREF_P(zid); if (!Z_ISUNDEF(ch->handlers->write->stream)) { Z_ADDREF(ch->handlers->write->stream); } dupch->handlers->write->stream = ch->handlers->write->stream; dupch->handlers->write->method = ch->handlers->write->method; if (!Z_ISUNDEF(ch->handlers->read->stream)) { Z_ADDREF(ch->handlers->read->stream); } dupch->handlers->read->stream = ch->handlers->read->stream; dupch->handlers->read->method = ch->handlers->read->method; dupch->handlers->write_header->method = ch->handlers->write_header->method; if (!Z_ISUNDEF(ch->handlers->write_header->stream)) { Z_ADDREF(ch->handlers->write_header->stream); } dupch->handlers->write_header->stream = ch->handlers->write_header->stream; dupch->handlers->write->fp = ch->handlers->write->fp; dupch->handlers->write_header->fp = ch->handlers->write_header->fp; dupch->handlers->read->fp = ch->handlers->read->fp; dupch->handlers->read->res = ch->handlers->read->res; #if CURLOPT_PASSWDDATA != 0 if (!Z_ISUNDEF(ch->handlers->passwd)) { ZVAL_COPY(&dupch->handlers->passwd, &ch->handlers->passwd); curl_easy_setopt(ch->cp, CURLOPT_PASSWDDATA, (void *) dupch); } #endif if (!Z_ISUNDEF(ch->handlers->write->func_name)) { ZVAL_COPY(&dupch->handlers->write->func_name, &ch->handlers->write->func_name); } if (!Z_ISUNDEF(ch->handlers->read->func_name)) { ZVAL_COPY(&dupch->handlers->read->func_name, &ch->handlers->read->func_name); } if (!Z_ISUNDEF(ch->handlers->write_header->func_name)) { ZVAL_COPY(&dupch->handlers->write_header->func_name, &ch->handlers->write_header->func_name); } curl_easy_setopt(dupch->cp, CURLOPT_ERRORBUFFER, dupch->err.str); curl_easy_setopt(dupch->cp, CURLOPT_FILE, (void *) dupch); curl_easy_setopt(dupch->cp, CURLOPT_INFILE, (void *) dupch); curl_easy_setopt(dupch->cp, CURLOPT_WRITEHEADER, (void *) dupch); if (ch->handlers->progress) { dupch->handlers->progress = ecalloc(1, sizeof(php_curl_progress)); if (!Z_ISUNDEF(ch->handlers->progress->func_name)) { ZVAL_COPY(&dupch->handlers->progress->func_name, &ch->handlers->progress->func_name); } dupch->handlers->progress->method = ch->handlers->progress->method; curl_easy_setopt(dupch->cp, CURLOPT_PROGRESSDATA, (void *) dupch); } /* Available since 7.21.0 */ #if LIBCURL_VERSION_NUM >= 0x071500 if (ch->handlers->fnmatch) { dupch->handlers->fnmatch = ecalloc(1, sizeof(php_curl_fnmatch)); if (!Z_ISUNDEF(ch->handlers->fnmatch->func_name)) { ZVAL_COPY(&dupch->handlers->fnmatch->func_name, &ch->handlers->fnmatch->func_name); } dupch->handlers->fnmatch->method = ch->handlers->fnmatch->method; curl_easy_setopt(dupch->cp, CURLOPT_FNMATCH_DATA, (void *) dupch); } #endif efree(dupch->to_free->slist); efree(dupch->to_free); dupch->to_free = ch->to_free; efree(dupch->clone); dupch->clone = ch->clone; /* Keep track of cloned copies to avoid invoking curl destructors for every clone */ (*ch->clone)++; ZVAL_RES(return_value, zend_register_resource(dupch, le_curl)); dupch->res = Z_RES_P(return_value); } /* }}} */ static int _php_curl_setopt(php_curl *ch, zend_long option, zval *zvalue) /* {{{ */ { CURLcode error = CURLE_OK; zend_long lval; ZVAL_DEREF(zvalue); switch (option) { /* Long options */ case CURLOPT_SSL_VERIFYHOST: lval = zval_get_long(zvalue); if (lval == 1) { #if LIBCURL_VERSION_NUM <= 0x071c00 /* 7.28.0 */ php_error_docref(NULL, E_NOTICE, "CURLOPT_SSL_VERIFYHOST with value 1 is deprecated and will be removed as of libcurl 7.28.1. It is recommended to use value 2 instead"); #else php_error_docref(NULL, E_NOTICE, "CURLOPT_SSL_VERIFYHOST no longer accepts the value 1, value 2 will be used instead"); error = curl_easy_setopt(ch->cp, option, 2); break; #endif } case CURLOPT_AUTOREFERER: case CURLOPT_BUFFERSIZE: case CURLOPT_CONNECTTIMEOUT: case CURLOPT_COOKIESESSION: case CURLOPT_CRLF: case CURLOPT_DNS_CACHE_TIMEOUT: case CURLOPT_DNS_USE_GLOBAL_CACHE: case CURLOPT_FAILONERROR: case CURLOPT_FILETIME: case CURLOPT_FORBID_REUSE: case CURLOPT_FRESH_CONNECT: case CURLOPT_FTP_USE_EPRT: case CURLOPT_FTP_USE_EPSV: case CURLOPT_HEADER: case CURLOPT_HTTPGET: case CURLOPT_HTTPPROXYTUNNEL: case CURLOPT_HTTP_VERSION: case CURLOPT_INFILESIZE: case CURLOPT_LOW_SPEED_LIMIT: case CURLOPT_LOW_SPEED_TIME: case CURLOPT_MAXCONNECTS: case CURLOPT_MAXREDIRS: case CURLOPT_NETRC: case CURLOPT_NOBODY: case CURLOPT_NOPROGRESS: case CURLOPT_NOSIGNAL: case CURLOPT_PORT: case CURLOPT_POST: case CURLOPT_PROXYPORT: case CURLOPT_PROXYTYPE: case CURLOPT_PUT: case CURLOPT_RESUME_FROM: case CURLOPT_SSLVERSION: case CURLOPT_SSL_VERIFYPEER: case CURLOPT_TIMECONDITION: case CURLOPT_TIMEOUT: case CURLOPT_TIMEVALUE: case CURLOPT_TRANSFERTEXT: case CURLOPT_UNRESTRICTED_AUTH: case CURLOPT_UPLOAD: case CURLOPT_VERBOSE: #if LIBCURL_VERSION_NUM >= 0x070a06 /* Available since 7.10.6 */ case CURLOPT_HTTPAUTH: #endif #if LIBCURL_VERSION_NUM >= 0x070a07 /* Available since 7.10.7 */ case CURLOPT_FTP_CREATE_MISSING_DIRS: case CURLOPT_PROXYAUTH: #endif #if LIBCURL_VERSION_NUM >= 0x070a08 /* Available since 7.10.8 */ case CURLOPT_FTP_RESPONSE_TIMEOUT: case CURLOPT_IPRESOLVE: case CURLOPT_MAXFILESIZE: #endif #if LIBCURL_VERSION_NUM >= 0x070b02 /* Available since 7.11.2 */ case CURLOPT_TCP_NODELAY: #endif #if LIBCURL_VERSION_NUM >= 0x070c02 /* Available since 7.12.2 */ case CURLOPT_FTPSSLAUTH: #endif #if LIBCURL_VERSION_NUM >= 0x070e01 /* Available since 7.14.1 */ case CURLOPT_IGNORE_CONTENT_LENGTH: #endif #if LIBCURL_VERSION_NUM >= 0x070f00 /* Available since 7.15.0 */ case CURLOPT_FTP_SKIP_PASV_IP: #endif #if LIBCURL_VERSION_NUM >= 0x070f01 /* Available since 7.15.1 */ case CURLOPT_FTP_FILEMETHOD: #endif #if LIBCURL_VERSION_NUM >= 0x070f02 /* Available since 7.15.2 */ case CURLOPT_CONNECT_ONLY: case CURLOPT_LOCALPORT: case CURLOPT_LOCALPORTRANGE: #endif #if LIBCURL_VERSION_NUM >= 0x071000 /* Available since 7.16.0 */ case CURLOPT_SSL_SESSIONID_CACHE: #endif #if LIBCURL_VERSION_NUM >= 0x071001 /* Available since 7.16.1 */ case CURLOPT_FTP_SSL_CCC: case CURLOPT_SSH_AUTH_TYPES: #endif #if LIBCURL_VERSION_NUM >= 0x071002 /* Available since 7.16.2 */ case CURLOPT_CONNECTTIMEOUT_MS: case CURLOPT_HTTP_CONTENT_DECODING: case CURLOPT_HTTP_TRANSFER_DECODING: case CURLOPT_TIMEOUT_MS: #endif #if LIBCURL_VERSION_NUM >= 0x071004 /* Available since 7.16.4 */ case CURLOPT_NEW_DIRECTORY_PERMS: case CURLOPT_NEW_FILE_PERMS: #endif #if LIBCURL_VERSION_NUM >= 0x071100 /* Available since 7.17.0 */ case CURLOPT_USE_SSL: #elif LIBCURL_VERSION_NUM >= 0x070b00 /* Available since 7.11.0 */ case CURLOPT_FTP_SSL: #endif #if LIBCURL_VERSION_NUM >= 0x071100 /* Available since 7.17.0 */ case CURLOPT_APPEND: case CURLOPT_DIRLISTONLY: #else case CURLOPT_FTPAPPEND: case CURLOPT_FTPLISTONLY: #endif #if LIBCURL_VERSION_NUM >= 0x071200 /* Available since 7.18.0 */ case CURLOPT_PROXY_TRANSFER_MODE: #endif #if LIBCURL_VERSION_NUM >= 0x071300 /* Available since 7.19.0 */ case CURLOPT_ADDRESS_SCOPE: #endif #if LIBCURL_VERSION_NUM > 0x071301 /* Available since 7.19.1 */ case CURLOPT_CERTINFO: #endif #if LIBCURL_VERSION_NUM >= 0x071304 /* Available since 7.19.4 */ case CURLOPT_PROTOCOLS: case CURLOPT_REDIR_PROTOCOLS: case CURLOPT_SOCKS5_GSSAPI_NEC: case CURLOPT_TFTP_BLKSIZE: #endif #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_FTP_USE_PRET: case CURLOPT_RTSP_CLIENT_CSEQ: case CURLOPT_RTSP_REQUEST: case CURLOPT_RTSP_SERVER_CSEQ: #endif #if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */ case CURLOPT_WILDCARDMATCH: #endif #if LIBCURL_VERSION_NUM >= 0x071504 /* Available since 7.21.4 */ case CURLOPT_TLSAUTH_TYPE: #endif #if LIBCURL_VERSION_NUM >= 0x071600 /* Available since 7.22.0 */ case CURLOPT_GSSAPI_DELEGATION: #endif #if LIBCURL_VERSION_NUM >= 0x071800 /* Available since 7.24.0 */ case CURLOPT_ACCEPTTIMEOUT_MS: #endif #if LIBCURL_VERSION_NUM >= 0x071900 /* Available since 7.25.0 */ case CURLOPT_SSL_OPTIONS: case CURLOPT_TCP_KEEPALIVE: case CURLOPT_TCP_KEEPIDLE: case CURLOPT_TCP_KEEPINTVL: #endif #if LIBCURL_VERSION_NUM >= 0x071f00 /* Available since 7.31.0 */ case CURLOPT_SASL_IR: #endif #if LIBCURL_VERSION_NUM >= 0x072400 /* Available since 7.36.0 */ case CURLOPT_EXPECT_100_TIMEOUT_MS: case CURLOPT_SSL_ENABLE_ALPN: case CURLOPT_SSL_ENABLE_NPN: #endif #if LIBCURL_VERSION_NUM >= 0x072500 /* Available since 7.37.0 */ case CURLOPT_HEADEROPT: #endif #if LIBCURL_VERSION_NUM >= 0x072900 /* Available since 7.41.0 */ case CURLOPT_SSL_VERIFYSTATUS: #endif #if LIBCURL_VERSION_NUM >= 0x072a00 /* Available since 7.42.0 */ case CURLOPT_PATH_AS_IS: case CURLOPT_SSL_FALSESTART: #endif #if LIBCURL_VERSION_NUM >= 0x072b00 /* Available since 7.43.0 */ case CURLOPT_PIPEWAIT: #endif #if LIBCURL_VERSION_NUM >= 0x072e00 /* Available since 7.46.0 */ case CURLOPT_STREAM_WEIGHT: #endif #if LIBCURL_VERSION_NUM >= 0x073000 /* Available since 7.48.0 */ case CURLOPT_TFTP_NO_OPTIONS: #endif #if LIBCURL_VERSION_NUM >= 0x073100 /* Available since 7.49.0 */ case CURLOPT_TCP_FASTOPEN: #endif #if CURLOPT_MUTE != 0 case CURLOPT_MUTE: #endif lval = zval_get_long(zvalue); #if LIBCURL_VERSION_NUM >= 0x71304 if ((option == CURLOPT_PROTOCOLS || option == CURLOPT_REDIR_PROTOCOLS) && (PG(open_basedir) && *PG(open_basedir)) && (lval & CURLPROTO_FILE)) { php_error_docref(NULL, E_WARNING, "CURLPROTO_FILE cannot be activated when an open_basedir is set"); return 1; } #endif # if defined(ZTS) if (option == CURLOPT_DNS_USE_GLOBAL_CACHE) { php_error_docref(NULL, E_WARNING, "CURLOPT_DNS_USE_GLOBAL_CACHE cannot be activated when thread safety is enabled"); return 1; } # endif error = curl_easy_setopt(ch->cp, option, lval); break; case CURLOPT_SAFE_UPLOAD: lval = zval_get_long(zvalue); if (lval == 0) { php_error_docref(NULL, E_WARNING, "Disabling safe uploads is no longer supported"); return FAILURE; } break; /* String options */ case CURLOPT_CAINFO: case CURLOPT_CAPATH: case CURLOPT_COOKIE: case CURLOPT_EGDSOCKET: case CURLOPT_INTERFACE: case CURLOPT_PROXY: case CURLOPT_PROXYUSERPWD: case CURLOPT_REFERER: case CURLOPT_SSLCERTTYPE: case CURLOPT_SSLENGINE: case CURLOPT_SSLENGINE_DEFAULT: case CURLOPT_SSLKEY: case CURLOPT_SSLKEYPASSWD: case CURLOPT_SSLKEYTYPE: case CURLOPT_SSL_CIPHER_LIST: case CURLOPT_USERAGENT: case CURLOPT_USERPWD: #if LIBCURL_VERSION_NUM >= 0x070e01 /* Available since 7.14.1 */ case CURLOPT_COOKIELIST: #endif #if LIBCURL_VERSION_NUM >= 0x070f05 /* Available since 7.15.5 */ case CURLOPT_FTP_ALTERNATIVE_TO_USER: #endif #if LIBCURL_VERSION_NUM >= 0x071101 /* Available since 7.17.1 */ case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5: #endif #if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */ case CURLOPT_PASSWORD: case CURLOPT_PROXYPASSWORD: case CURLOPT_PROXYUSERNAME: case CURLOPT_USERNAME: #endif #if LIBCURL_VERSION_NUM >= 0x071304 /* Available since 7.19.4 */ case CURLOPT_NOPROXY: case CURLOPT_SOCKS5_GSSAPI_SERVICE: #endif #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_MAIL_FROM: case CURLOPT_RTSP_STREAM_URI: case CURLOPT_RTSP_TRANSPORT: #endif #if LIBCURL_VERSION_NUM >= 0x071504 /* Available since 7.21.4 */ case CURLOPT_TLSAUTH_PASSWORD: case CURLOPT_TLSAUTH_USERNAME: #endif #if LIBCURL_VERSION_NUM >= 0x071506 /* Available since 7.21.6 */ case CURLOPT_ACCEPT_ENCODING: case CURLOPT_TRANSFER_ENCODING: #else case CURLOPT_ENCODING: #endif #if LIBCURL_VERSION_NUM >= 0x071800 /* Available since 7.24.0 */ case CURLOPT_DNS_SERVERS: #endif #if LIBCURL_VERSION_NUM >= 0x071900 /* Available since 7.25.0 */ case CURLOPT_MAIL_AUTH: #endif #if LIBCURL_VERSION_NUM >= 0x072200 /* Available since 7.34.0 */ case CURLOPT_LOGIN_OPTIONS: #endif #if LIBCURL_VERSION_NUM >= 0x072700 /* Available since 7.39.0 */ case CURLOPT_PINNEDPUBLICKEY: #endif #if LIBCURL_VERSION_NUM >= 0x072b00 /* Available since 7.43.0 */ case CURLOPT_PROXY_SERVICE_NAME: case CURLOPT_SERVICE_NAME: #endif #if LIBCURL_VERSION_NUM >= 0x072d00 /* Available since 7.45.0 */ case CURLOPT_DEFAULT_PROTOCOL: #endif { zend_string *str = zval_get_string(zvalue); int ret = php_curl_option_str(ch, option, ZSTR_VAL(str), ZSTR_LEN(str), 0); zend_string_release(str); return ret; } /* Curl nullable string options */ case CURLOPT_CUSTOMREQUEST: case CURLOPT_FTPPORT: case CURLOPT_RANGE: #if LIBCURL_VERSION_NUM >= 0x070d00 /* Available since 7.13.0 */ case CURLOPT_FTP_ACCOUNT: #endif #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_RTSP_SESSION_ID: #endif #if LIBCURL_VERSION_NUM >= 0x072100 /* Available since 7.33.0 */ case CURLOPT_DNS_INTERFACE: case CURLOPT_DNS_LOCAL_IP4: case CURLOPT_DNS_LOCAL_IP6: case CURLOPT_XOAUTH2_BEARER: #endif #if LIBCURL_VERSION_NUM >= 0x072800 /* Available since 7.40.0 */ case CURLOPT_UNIX_SOCKET_PATH: #endif #if LIBCURL_VERSION_NUM >= 0x071004 /* Available since 7.16.4 */ case CURLOPT_KRBLEVEL: #else case CURLOPT_KRB4LEVEL: #endif { if (Z_ISNULL_P(zvalue)) { error = curl_easy_setopt(ch->cp, option, NULL); } else { zend_string *str = zval_get_string(zvalue); int ret = php_curl_option_str(ch, option, ZSTR_VAL(str), ZSTR_LEN(str), 0); zend_string_release(str); return ret; } break; } /* Curl private option */ case CURLOPT_PRIVATE: { zend_string *str = zval_get_string(zvalue); int ret = php_curl_option_str(ch, option, ZSTR_VAL(str), ZSTR_LEN(str), 1); zend_string_release(str); return ret; } /* Curl url option */ case CURLOPT_URL: { zend_string *str = zval_get_string(zvalue); int ret = php_curl_option_url(ch, ZSTR_VAL(str), ZSTR_LEN(str)); zend_string_release(str); return ret; } /* Curl file handle options */ case CURLOPT_FILE: case CURLOPT_INFILE: case CURLOPT_STDERR: case CURLOPT_WRITEHEADER: { FILE *fp = NULL; php_stream *what = NULL; if (Z_TYPE_P(zvalue) != IS_NULL) { what = (php_stream *)zend_fetch_resource2_ex(zvalue, "File-Handle", php_file_le_stream(), php_file_le_pstream()); if (!what) { return FAILURE; } if (FAILURE == php_stream_cast(what, PHP_STREAM_AS_STDIO, (void *) &fp, REPORT_ERRORS)) { return FAILURE; } if (!fp) { return FAILURE; } } error = CURLE_OK; switch (option) { case CURLOPT_FILE: if (!what) { if (!Z_ISUNDEF(ch->handlers->write->stream)) { zval_ptr_dtor(&ch->handlers->write->stream); ZVAL_UNDEF(&ch->handlers->write->stream); } ch->handlers->write->fp = NULL; ch->handlers->write->method = PHP_CURL_STDOUT; } else if (what->mode[0] != 'r' || what->mode[1] == '+') { zval_ptr_dtor(&ch->handlers->write->stream); ch->handlers->write->fp = fp; ch->handlers->write->method = PHP_CURL_FILE; ZVAL_COPY(&ch->handlers->write->stream, zvalue); } else { php_error_docref(NULL, E_WARNING, "the provided file handle is not writable"); return FAILURE; } break; case CURLOPT_WRITEHEADER: if (!what) { if (!Z_ISUNDEF(ch->handlers->write_header->stream)) { zval_ptr_dtor(&ch->handlers->write_header->stream); ZVAL_UNDEF(&ch->handlers->write_header->stream); } ch->handlers->write_header->fp = NULL; ch->handlers->write_header->method = PHP_CURL_IGNORE; } else if (what->mode[0] != 'r' || what->mode[1] == '+') { zval_ptr_dtor(&ch->handlers->write_header->stream); ch->handlers->write_header->fp = fp; ch->handlers->write_header->method = PHP_CURL_FILE; ZVAL_COPY(&ch->handlers->write_header->stream, zvalue);; } else { php_error_docref(NULL, E_WARNING, "the provided file handle is not writable"); return FAILURE; } break; case CURLOPT_INFILE: if (!what) { if (!Z_ISUNDEF(ch->handlers->read->stream)) { zval_ptr_dtor(&ch->handlers->read->stream); ZVAL_UNDEF(&ch->handlers->read->stream); } ch->handlers->read->fp = NULL; ch->handlers->read->res = NULL; } else { zval_ptr_dtor(&ch->handlers->read->stream); ch->handlers->read->fp = fp; ch->handlers->read->res = Z_RES_P(zvalue); ZVAL_COPY(&ch->handlers->read->stream, zvalue); } break; case CURLOPT_STDERR: if (!what) { if (!Z_ISUNDEF(ch->handlers->std_err)) { zval_ptr_dtor(&ch->handlers->std_err); ZVAL_UNDEF(&ch->handlers->std_err); } } else if (what->mode[0] != 'r' || what->mode[1] == '+') { zval_ptr_dtor(&ch->handlers->std_err); ZVAL_COPY(&ch->handlers->std_err, zvalue); } else { php_error_docref(NULL, E_WARNING, "the provided file handle is not writable"); return FAILURE; } /* break omitted intentionally */ default: error = curl_easy_setopt(ch->cp, option, fp); break; } break; } /* Curl linked list options */ case CURLOPT_HTTP200ALIASES: case CURLOPT_HTTPHEADER: case CURLOPT_POSTQUOTE: case CURLOPT_PREQUOTE: case CURLOPT_QUOTE: case CURLOPT_TELNETOPTIONS: #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_MAIL_RCPT: #endif #if LIBCURL_VERSION_NUM >= 0x071503 /* Available since 7.21.3 */ case CURLOPT_RESOLVE: #endif #if LIBCURL_VERSION_NUM >= 0x072500 /* Available since 7.37.0 */ case CURLOPT_PROXYHEADER: #endif #if LIBCURL_VERSION_NUM >= 0x073100 /* Available since 7.49.0 */ case CURLOPT_CONNECT_TO: #endif { zval *current; HashTable *ph; zend_string *val; struct curl_slist *slist = NULL; ph = HASH_OF(zvalue); if (!ph) { char *name = NULL; switch (option) { case CURLOPT_HTTPHEADER: name = "CURLOPT_HTTPHEADER"; break; case CURLOPT_QUOTE: name = "CURLOPT_QUOTE"; break; case CURLOPT_HTTP200ALIASES: name = "CURLOPT_HTTP200ALIASES"; break; case CURLOPT_POSTQUOTE: name = "CURLOPT_POSTQUOTE"; break; case CURLOPT_PREQUOTE: name = "CURLOPT_PREQUOTE"; break; case CURLOPT_TELNETOPTIONS: name = "CURLOPT_TELNETOPTIONS"; break; #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_MAIL_RCPT: name = "CURLOPT_MAIL_RCPT"; break; #endif #if LIBCURL_VERSION_NUM >= 0x071503 /* Available since 7.21.3 */ case CURLOPT_RESOLVE: name = "CURLOPT_RESOLVE"; break; #endif #if LIBCURL_VERSION_NUM >= 0x072500 /* Available since 7.37.0 */ case CURLOPT_PROXYHEADER: name = "CURLOPT_PROXYHEADER"; break; #endif #if LIBCURL_VERSION_NUM >= 0x073100 /* Available since 7.49.0 */ case CURLOPT_CONNECT_TO: name = "CURLOPT_CONNECT_TO"; break; #endif } php_error_docref(NULL, E_WARNING, "You must pass either an object or an array with the %s argument", name); return FAILURE; } ZEND_HASH_FOREACH_VAL(ph, current) { ZVAL_DEREF(current); val = zval_get_string(current); slist = curl_slist_append(slist, ZSTR_VAL(val)); zend_string_release(val); if (!slist) { php_error_docref(NULL, E_WARNING, "Could not build curl_slist"); return 1; } } ZEND_HASH_FOREACH_END(); if (slist) { if ((*ch->clone) == 1) { zend_hash_index_update_ptr(ch->to_free->slist, option, slist); } else { zend_hash_next_index_insert_ptr(ch->to_free->slist, slist); } } error = curl_easy_setopt(ch->cp, option, slist); break; } case CURLOPT_BINARYTRANSFER: /* Do nothing, just backward compatibility */ break; case CURLOPT_FOLLOWLOCATION: lval = zval_get_long(zvalue); #if LIBCURL_VERSION_NUM < 0x071304 if (PG(open_basedir) && *PG(open_basedir)) { if (lval != 0) { php_error_docref(NULL, E_WARNING, "CURLOPT_FOLLOWLOCATION cannot be activated when an open_basedir is set"); return FAILURE; } } #endif error = curl_easy_setopt(ch->cp, option, lval); break; case CURLOPT_HEADERFUNCTION: if (!Z_ISUNDEF(ch->handlers->write_header->func_name)) { zval_ptr_dtor(&ch->handlers->write_header->func_name); ch->handlers->write_header->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->write_header->func_name, zvalue); ch->handlers->write_header->method = PHP_CURL_USER; break; case CURLOPT_POSTFIELDS: if (Z_TYPE_P(zvalue) == IS_ARRAY || Z_TYPE_P(zvalue) == IS_OBJECT) { zval *current; HashTable *postfields; zend_string *string_key; zend_ulong num_key; struct HttpPost *first = NULL; struct HttpPost *last = NULL; CURLFORMcode form_error; postfields = HASH_OF(zvalue); if (!postfields) { php_error_docref(NULL, E_WARNING, "Couldn't get HashTable in CURLOPT_POSTFIELDS"); return FAILURE; } ZEND_HASH_FOREACH_KEY_VAL(postfields, num_key, string_key, current) { zend_string *postval; /* Pretend we have a string_key here */ if (!string_key) { string_key = zend_long_to_str(num_key); } else { zend_string_addref(string_key); } ZVAL_DEREF(current); if (Z_TYPE_P(current) == IS_OBJECT && instanceof_function(Z_OBJCE_P(current), curl_CURLFile_class)) { /* new-style file upload */ zval *prop, rv; char *type = NULL, *filename = NULL; prop = zend_read_property(curl_CURLFile_class, current, "name", sizeof("name")-1, 0, &rv); if (Z_TYPE_P(prop) != IS_STRING) { php_error_docref(NULL, E_WARNING, "Invalid filename for key %s", ZSTR_VAL(string_key)); } else { postval = Z_STR_P(prop); if (php_check_open_basedir(ZSTR_VAL(postval))) { return 1; } prop = zend_read_property(curl_CURLFile_class, current, "mime", sizeof("mime")-1, 0, &rv); if (Z_TYPE_P(prop) == IS_STRING && Z_STRLEN_P(prop) > 0) { type = Z_STRVAL_P(prop); } prop = zend_read_property(curl_CURLFile_class, current, "postname", sizeof("postname")-1, 0, &rv); if (Z_TYPE_P(prop) == IS_STRING && Z_STRLEN_P(prop) > 0) { filename = Z_STRVAL_P(prop); } form_error = curl_formadd(&first, &last, CURLFORM_COPYNAME, ZSTR_VAL(string_key), CURLFORM_NAMELENGTH, ZSTR_LEN(string_key), CURLFORM_FILENAME, filename ? filename : ZSTR_VAL(postval), CURLFORM_CONTENTTYPE, type ? type : "application/octet-stream", CURLFORM_FILE, ZSTR_VAL(postval), CURLFORM_END); if (form_error != CURL_FORMADD_OK) { /* Not nice to convert between enums but we only have place for one error type */ error = (CURLcode)form_error; } } zend_string_release(string_key); continue; } postval = zval_get_string(current); /* The arguments after _NAMELENGTH and _CONTENTSLENGTH * must be explicitly cast to long in curl_formadd * use since curl needs a long not an int. */ form_error = curl_formadd(&first, &last, CURLFORM_COPYNAME, ZSTR_VAL(string_key), CURLFORM_NAMELENGTH, ZSTR_LEN(string_key), CURLFORM_COPYCONTENTS, ZSTR_VAL(postval), CURLFORM_CONTENTSLENGTH, ZSTR_LEN(postval), CURLFORM_END); if (form_error != CURL_FORMADD_OK) { /* Not nice to convert between enums but we only have place for one error type */ error = (CURLcode)form_error; } zend_string_release(postval); zend_string_release(string_key); } ZEND_HASH_FOREACH_END(); SAVE_CURL_ERROR(ch, error); if (error != CURLE_OK) { return FAILURE; } if ((*ch->clone) == 1) { zend_llist_clean(&ch->to_free->post); } zend_llist_add_element(&ch->to_free->post, &first); error = curl_easy_setopt(ch->cp, CURLOPT_HTTPPOST, first); } else { #if LIBCURL_VERSION_NUM >= 0x071101 zend_string *str = zval_get_string(zvalue); /* with curl 7.17.0 and later, we can use COPYPOSTFIELDS, but we have to provide size before */ error = curl_easy_setopt(ch->cp, CURLOPT_POSTFIELDSIZE, ZSTR_LEN(str)); error = curl_easy_setopt(ch->cp, CURLOPT_COPYPOSTFIELDS, ZSTR_VAL(str)); zend_string_release(str); #else char *post = NULL; zend_string *str = zval_get_string(zvalue); post = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_llist_add_element(&ch->to_free->str, &post); curl_easy_setopt(ch->cp, CURLOPT_POSTFIELDS, post); error = curl_easy_setopt(ch->cp, CURLOPT_POSTFIELDSIZE, ZSTR_LEN(str)); zend_string_release(str); #endif } break; case CURLOPT_PROGRESSFUNCTION: curl_easy_setopt(ch->cp, CURLOPT_PROGRESSFUNCTION, curl_progress); curl_easy_setopt(ch->cp, CURLOPT_PROGRESSDATA, ch); if (ch->handlers->progress == NULL) { ch->handlers->progress = ecalloc(1, sizeof(php_curl_progress)); } else if (!Z_ISUNDEF(ch->handlers->progress->func_name)) { zval_ptr_dtor(&ch->handlers->progress->func_name); ch->handlers->progress->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->progress->func_name, zvalue); ch->handlers->progress->method = PHP_CURL_USER; break; case CURLOPT_READFUNCTION: if (!Z_ISUNDEF(ch->handlers->read->func_name)) { zval_ptr_dtor(&ch->handlers->read->func_name); ch->handlers->read->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->read->func_name, zvalue); ch->handlers->read->method = PHP_CURL_USER; break; case CURLOPT_RETURNTRANSFER: lval = zval_get_long(zvalue); if (lval) { ch->handlers->write->method = PHP_CURL_RETURN; } else { ch->handlers->write->method = PHP_CURL_STDOUT; } break; case CURLOPT_WRITEFUNCTION: if (!Z_ISUNDEF(ch->handlers->write->func_name)) { zval_ptr_dtor(&ch->handlers->write->func_name); ch->handlers->write->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->write->func_name, zvalue); ch->handlers->write->method = PHP_CURL_USER; break; #if LIBCURL_VERSION_NUM >= 0x070f05 /* Available since 7.15.5 */ case CURLOPT_MAX_RECV_SPEED_LARGE: case CURLOPT_MAX_SEND_SPEED_LARGE: lval = zval_get_long(zvalue); error = curl_easy_setopt(ch->cp, option, (curl_off_t)lval); break; #endif #if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */ case CURLOPT_POSTREDIR: lval = zval_get_long(zvalue); error = curl_easy_setopt(ch->cp, CURLOPT_POSTREDIR, lval & CURL_REDIR_POST_ALL); break; #endif #if CURLOPT_PASSWDFUNCTION != 0 case CURLOPT_PASSWDFUNCTION: zval_ptr_dtor(&ch->handlers->passwd); ZVAL_COPY(&ch->handlers->passwd, zvalue); error = curl_easy_setopt(ch->cp, CURLOPT_PASSWDFUNCTION, curl_passwd); error = curl_easy_setopt(ch->cp, CURLOPT_PASSWDDATA, (void *) ch); break; #endif /* the following options deal with files, therefore the open_basedir check * is required. */ case CURLOPT_COOKIEFILE: case CURLOPT_COOKIEJAR: case CURLOPT_RANDOM_FILE: case CURLOPT_SSLCERT: #if LIBCURL_VERSION_NUM >= 0x070b00 /* Available since 7.11.0 */ case CURLOPT_NETRC_FILE: #endif #if LIBCURL_VERSION_NUM >= 0x071001 /* Available since 7.16.1 */ case CURLOPT_SSH_PRIVATE_KEYFILE: case CURLOPT_SSH_PUBLIC_KEYFILE: #endif #if LIBCURL_VERSION_NUM >= 0x071300 /* Available since 7.19.0 */ case CURLOPT_CRLFILE: case CURLOPT_ISSUERCERT: #endif #if LIBCURL_VERSION_NUM >= 0x071306 /* Available since 7.19.6 */ case CURLOPT_SSH_KNOWNHOSTS: #endif { zend_string *str = zval_get_string(zvalue); int ret; if (ZSTR_LEN(str) && php_check_open_basedir(ZSTR_VAL(str))) { zend_string_release(str); return FAILURE; } ret = php_curl_option_str(ch, option, ZSTR_VAL(str), ZSTR_LEN(str), 0); zend_string_release(str); return ret; } case CURLINFO_HEADER_OUT: lval = zval_get_long(zvalue); if (lval == 1) { curl_easy_setopt(ch->cp, CURLOPT_DEBUGFUNCTION, curl_debug); curl_easy_setopt(ch->cp, CURLOPT_DEBUGDATA, (void *)ch); curl_easy_setopt(ch->cp, CURLOPT_VERBOSE, 1); } else { curl_easy_setopt(ch->cp, CURLOPT_DEBUGFUNCTION, NULL); curl_easy_setopt(ch->cp, CURLOPT_DEBUGDATA, NULL); curl_easy_setopt(ch->cp, CURLOPT_VERBOSE, 0); } break; case CURLOPT_SHARE: { php_curlsh *sh; if ((sh = (php_curlsh *)zend_fetch_resource_ex(zvalue, le_curl_share_handle_name, le_curl_share_handle))) { curl_easy_setopt(ch->cp, CURLOPT_SHARE, sh->share); } } break; #if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */ case CURLOPT_FNMATCH_FUNCTION: curl_easy_setopt(ch->cp, CURLOPT_FNMATCH_FUNCTION, curl_fnmatch); curl_easy_setopt(ch->cp, CURLOPT_FNMATCH_DATA, ch); if (ch->handlers->fnmatch == NULL) { ch->handlers->fnmatch = ecalloc(1, sizeof(php_curl_fnmatch)); } else if (!Z_ISUNDEF(ch->handlers->fnmatch->func_name)) { zval_ptr_dtor(&ch->handlers->fnmatch->func_name); ch->handlers->fnmatch->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->fnmatch->func_name, zvalue); ch->handlers->fnmatch->method = PHP_CURL_USER; break; #endif } SAVE_CURL_ERROR(ch, error); if (error != CURLE_OK) { return FAILURE; } else { return SUCCESS; } } /* }}} */ /* {{{ proto bool curl_setopt(resource ch, int option, mixed value) Set an option for a cURL transfer */ PHP_FUNCTION(curl_setopt) { zval *zid, *zvalue; zend_long options; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rlz", &zid, &options, &zvalue) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (options <= 0 && options != CURLOPT_SAFE_UPLOAD) { php_error_docref(NULL, E_WARNING, "Invalid curl configuration option"); RETURN_FALSE; } if (_php_curl_setopt(ch, options, zvalue) == SUCCESS) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool curl_setopt_array(resource ch, array options) Set an array of option for a cURL transfer */ PHP_FUNCTION(curl_setopt_array) { zval *zid, *arr, *entry; php_curl *ch; zend_ulong option; zend_string *string_key; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ra", &zid, &arr) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(arr), option, string_key, entry) { if (string_key) { php_error_docref(NULL, E_WARNING, "Array keys must be CURLOPT constants or equivalent integer values"); RETURN_FALSE; } if (_php_curl_setopt(ch, (zend_long) option, entry) == FAILURE) { RETURN_FALSE; } } ZEND_HASH_FOREACH_END(); RETURN_TRUE; } /* }}} */ /* {{{ _php_curl_cleanup_handle(ch) Cleanup an execution phase */ void _php_curl_cleanup_handle(php_curl *ch) { smart_str_free(&ch->handlers->write->buf); if (ch->header.str) { zend_string_release(ch->header.str); ch->header.str = NULL; } memset(ch->err.str, 0, CURL_ERROR_SIZE + 1); ch->err.no = 0; } /* }}} */ /* {{{ proto bool curl_exec(resource ch) Perform a cURL session */ PHP_FUNCTION(curl_exec) { CURLcode error; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } _php_curl_verify_handlers(ch, 1); _php_curl_cleanup_handle(ch); error = curl_easy_perform(ch->cp); SAVE_CURL_ERROR(ch, error); /* CURLE_PARTIAL_FILE is returned by HEAD requests */ if (error != CURLE_OK && error != CURLE_PARTIAL_FILE) { smart_str_free(&ch->handlers->write->buf); RETURN_FALSE; } if (!Z_ISUNDEF(ch->handlers->std_err)) { php_stream *stream; stream = (php_stream*)zend_fetch_resource2_ex(&ch->handlers->std_err, NULL, php_file_le_stream(), php_file_le_pstream()); if (stream) { php_stream_flush(stream); } } if (ch->handlers->write->method == PHP_CURL_RETURN && ch->handlers->write->buf.s) { smart_str_0(&ch->handlers->write->buf); RETURN_STR_COPY(ch->handlers->write->buf.s); } /* flush the file handle, so any remaining data is synched to disk */ if (ch->handlers->write->method == PHP_CURL_FILE && ch->handlers->write->fp) { fflush(ch->handlers->write->fp); } if (ch->handlers->write_header->method == PHP_CURL_FILE && ch->handlers->write_header->fp) { fflush(ch->handlers->write_header->fp); } if (ch->handlers->write->method == PHP_CURL_RETURN) { RETURN_EMPTY_STRING(); } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto mixed curl_getinfo(resource ch [, int option]) Get information regarding a specific transfer */ PHP_FUNCTION(curl_getinfo) { zval *zid; php_curl *ch; zend_long option = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &zid, &option) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (ZEND_NUM_ARGS() < 2) { char *s_code; /* libcurl expects long datatype. So far no cases are known where it would be an issue. Using zend_long would truncate a 64-bit var on Win64, so the exact long datatype fits everywhere, as long as there's no 32-bit int overflow. */ long l_code; double d_code; #if LIBCURL_VERSION_NUM > 0x071301 struct curl_certinfo *ci = NULL; zval listcode; #endif array_init(return_value); if (curl_easy_getinfo(ch->cp, CURLINFO_EFFECTIVE_URL, &s_code) == CURLE_OK) { CAAS("url", s_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_CONTENT_TYPE, &s_code) == CURLE_OK) { if (s_code != NULL) { CAAS("content_type", s_code); } else { zval retnull; ZVAL_NULL(&retnull); CAAZ("content_type", &retnull); } } if (curl_easy_getinfo(ch->cp, CURLINFO_HTTP_CODE, &l_code) == CURLE_OK) { CAAL("http_code", l_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_HEADER_SIZE, &l_code) == CURLE_OK) { CAAL("header_size", l_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_REQUEST_SIZE, &l_code) == CURLE_OK) { CAAL("request_size", l_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_FILETIME, &l_code) == CURLE_OK) { CAAL("filetime", l_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_SSL_VERIFYRESULT, &l_code) == CURLE_OK) { CAAL("ssl_verify_result", l_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_REDIRECT_COUNT, &l_code) == CURLE_OK) { CAAL("redirect_count", l_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_TOTAL_TIME, &d_code) == CURLE_OK) { CAAD("total_time", d_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_NAMELOOKUP_TIME, &d_code) == CURLE_OK) { CAAD("namelookup_time", d_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_CONNECT_TIME, &d_code) == CURLE_OK) { CAAD("connect_time", d_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_PRETRANSFER_TIME, &d_code) == CURLE_OK) { CAAD("pretransfer_time", d_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_SIZE_UPLOAD, &d_code) == CURLE_OK) { CAAD("size_upload", d_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_SIZE_DOWNLOAD, &d_code) == CURLE_OK) { CAAD("size_download", d_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_SPEED_DOWNLOAD, &d_code) == CURLE_OK) { CAAD("speed_download", d_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_SPEED_UPLOAD, &d_code) == CURLE_OK) { CAAD("speed_upload", d_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d_code) == CURLE_OK) { CAAD("download_content_length", d_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_CONTENT_LENGTH_UPLOAD, &d_code) == CURLE_OK) { CAAD("upload_content_length", d_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_STARTTRANSFER_TIME, &d_code) == CURLE_OK) { CAAD("starttransfer_time", d_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_REDIRECT_TIME, &d_code) == CURLE_OK) { CAAD("redirect_time", d_code); } #if LIBCURL_VERSION_NUM >= 0x071202 /* Available since 7.18.2 */ if (curl_easy_getinfo(ch->cp, CURLINFO_REDIRECT_URL, &s_code) == CURLE_OK) { CAAS("redirect_url", s_code); } #endif #if LIBCURL_VERSION_NUM >= 0x071300 /* Available since 7.19.0 */ if (curl_easy_getinfo(ch->cp, CURLINFO_PRIMARY_IP, &s_code) == CURLE_OK) { CAAS("primary_ip", s_code); } #endif #if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */ if (curl_easy_getinfo(ch->cp, CURLINFO_CERTINFO, &ci) == CURLE_OK) { array_init(&listcode); create_certinfo(ci, &listcode); CAAZ("certinfo", &listcode); } #endif #if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */ if (curl_easy_getinfo(ch->cp, CURLINFO_PRIMARY_PORT, &l_code) == CURLE_OK) { CAAL("primary_port", l_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_LOCAL_IP, &s_code) == CURLE_OK) { CAAS("local_ip", s_code); } if (curl_easy_getinfo(ch->cp, CURLINFO_LOCAL_PORT, &l_code) == CURLE_OK) { CAAL("local_port", l_code); } #endif if (ch->header.str) { CAASTR("request_header", ch->header.str); } } else { switch (option) { case CURLINFO_HEADER_OUT: if (ch->header.str) { RETURN_STR_COPY(ch->header.str); } else { RETURN_FALSE; } #if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */ case CURLINFO_CERTINFO: { struct curl_certinfo *ci = NULL; array_init(return_value); if (curl_easy_getinfo(ch->cp, CURLINFO_CERTINFO, &ci) == CURLE_OK) { create_certinfo(ci, return_value); } else { RETURN_FALSE; } break; } #endif default: { int type = CURLINFO_TYPEMASK & option; switch (type) { case CURLINFO_STRING: { char *s_code = NULL; if (curl_easy_getinfo(ch->cp, option, &s_code) == CURLE_OK && s_code) { RETURN_STRING(s_code); } else { RETURN_FALSE; } break; } case CURLINFO_LONG: { zend_long code = 0; if (curl_easy_getinfo(ch->cp, option, &code) == CURLE_OK) { RETURN_LONG(code); } else { RETURN_FALSE; } break; } case CURLINFO_DOUBLE: { double code = 0.0; if (curl_easy_getinfo(ch->cp, option, &code) == CURLE_OK) { RETURN_DOUBLE(code); } else { RETURN_FALSE; } break; } #if LIBCURL_VERSION_NUM >= 0x070c03 /* Available since 7.12.3 */ case CURLINFO_SLIST: { struct curl_slist *slist; array_init(return_value); if (curl_easy_getinfo(ch->cp, option, &slist) == CURLE_OK) { while (slist) { add_next_index_string(return_value, slist->data); slist = slist->next; } curl_slist_free_all(slist); } else { RETURN_FALSE; } break; } #endif default: RETURN_FALSE; } } } } } /* }}} */ /* {{{ proto string curl_error(resource ch) Return a string contain the last error for the current session */ PHP_FUNCTION(curl_error) { zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } ch->err.str[CURL_ERROR_SIZE] = 0; RETURN_STRING(ch->err.str); } /* }}} */ /* {{{ proto int curl_errno(resource ch) Return an integer containing the last error number */ PHP_FUNCTION(curl_errno) { zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } RETURN_LONG(ch->err.no); } /* }}} */ /* {{{ proto void curl_close(resource ch) Close a cURL session */ PHP_FUNCTION(curl_close) { zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (ch->in_callback) { php_error_docref(NULL, E_WARNING, "Attempt to close cURL handle from a callback"); return; } if (Z_REFCOUNT_P(zid) <= 2) { zend_list_close(Z_RES_P(zid)); } } /* }}} */ /* {{{ _php_curl_close_ex() List destructor for curl handles */ static void _php_curl_close_ex(php_curl *ch) { #if PHP_CURL_DEBUG fprintf(stderr, "DTOR CALLED, ch = %x\n", ch); #endif _php_curl_verify_handlers(ch, 0); /* * Libcurl is doing connection caching. When easy handle is cleaned up, * if the handle was previously used by the curl_multi_api, the connection * remains open un the curl multi handle is cleaned up. Some protocols are * sending content like the FTP one, and libcurl try to use the * WRITEFUNCTION or the HEADERFUNCTION. Since structures used in those * callback are freed, we need to use an other callback to which avoid * segfaults. * * Libcurl commit d021f2e8a00 fix this issue and should be part of 7.28.2 */ curl_easy_setopt(ch->cp, CURLOPT_HEADERFUNCTION, curl_write_nothing); curl_easy_setopt(ch->cp, CURLOPT_WRITEFUNCTION, curl_write_nothing); curl_easy_cleanup(ch->cp); /* cURL destructors should be invoked only by last curl handle */ if (--(*ch->clone) == 0) { zend_llist_clean(&ch->to_free->str); zend_llist_clean(&ch->to_free->post); zend_hash_destroy(ch->to_free->slist); efree(ch->to_free->slist); efree(ch->to_free); efree(ch->clone); } smart_str_free(&ch->handlers->write->buf); zval_ptr_dtor(&ch->handlers->write->func_name); zval_ptr_dtor(&ch->handlers->read->func_name); zval_ptr_dtor(&ch->handlers->write_header->func_name); #if CURLOPT_PASSWDFUNCTION != 0 zval_ptr_dtor(&ch->handlers->passwd); #endif zval_ptr_dtor(&ch->handlers->std_err); if (ch->header.str) { zend_string_release(ch->header.str); } zval_ptr_dtor(&ch->handlers->write_header->stream); zval_ptr_dtor(&ch->handlers->write->stream); zval_ptr_dtor(&ch->handlers->read->stream); efree(ch->handlers->write); efree(ch->handlers->write_header); efree(ch->handlers->read); if (ch->handlers->progress) { zval_ptr_dtor(&ch->handlers->progress->func_name); efree(ch->handlers->progress); } #if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */ if (ch->handlers->fnmatch) { zval_ptr_dtor(&ch->handlers->fnmatch->func_name); efree(ch->handlers->fnmatch); } #endif efree(ch->handlers); efree(ch); } /* }}} */ /* {{{ _php_curl_close() List destructor for curl handles */ static void _php_curl_close(zend_resource *rsrc) { php_curl *ch = (php_curl *) rsrc->ptr; _php_curl_close_ex(ch); } /* }}} */ #if LIBCURL_VERSION_NUM >= 0x070c00 /* Available since 7.12.0 */ /* {{{ proto bool curl_strerror(int code) return string describing error code */ PHP_FUNCTION(curl_strerror) { zend_long code; const char *str; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &code) == FAILURE) { return; } str = curl_easy_strerror(code); if (str) { RETURN_STRING(str); } else { RETURN_NULL(); } } /* }}} */ #endif #if LIBCURL_VERSION_NUM >= 0x070c01 /* 7.12.1 */ /* {{{ _php_curl_reset_handlers() Reset all handlers of a given php_curl */ static void _php_curl_reset_handlers(php_curl *ch) { if (!Z_ISUNDEF(ch->handlers->write->stream)) { zval_ptr_dtor(&ch->handlers->write->stream); ZVAL_UNDEF(&ch->handlers->write->stream); } ch->handlers->write->fp = NULL; ch->handlers->write->method = PHP_CURL_STDOUT; if (!Z_ISUNDEF(ch->handlers->write_header->stream)) { zval_ptr_dtor(&ch->handlers->write_header->stream); ZVAL_UNDEF(&ch->handlers->write_header->stream); } ch->handlers->write_header->fp = NULL; ch->handlers->write_header->method = PHP_CURL_IGNORE; if (!Z_ISUNDEF(ch->handlers->read->stream)) { zval_ptr_dtor(&ch->handlers->read->stream); ZVAL_UNDEF(&ch->handlers->read->stream); } ch->handlers->read->fp = NULL; ch->handlers->read->res = NULL; ch->handlers->read->method = PHP_CURL_DIRECT; if (!Z_ISUNDEF(ch->handlers->std_err)) { zval_ptr_dtor(&ch->handlers->std_err); ZVAL_UNDEF(&ch->handlers->std_err); } if (ch->handlers->progress) { zval_ptr_dtor(&ch->handlers->progress->func_name); efree(ch->handlers->progress); ch->handlers->progress = NULL; } #if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */ if (ch->handlers->fnmatch) { zval_ptr_dtor(&ch->handlers->fnmatch->func_name); efree(ch->handlers->fnmatch); ch->handlers->fnmatch = NULL; } #endif } /* }}} */ /* {{{ proto void curl_reset(resource ch) Reset all options of a libcurl session handle */ PHP_FUNCTION(curl_reset) { zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (ch->in_callback) { php_error_docref(NULL, E_WARNING, "Attempt to reset cURL handle from a callback"); return; } curl_easy_reset(ch->cp); _php_curl_reset_handlers(ch); _php_curl_set_default_options(ch); } /* }}} */ #endif #if LIBCURL_VERSION_NUM > 0x070f03 /* 7.15.4 */ /* {{{ proto void curl_escape(resource ch, string str) URL encodes the given string */ PHP_FUNCTION(curl_escape) { char *str = NULL, *res = NULL; size_t str_len = 0; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (ZEND_SIZE_T_INT_OVFL(str_len)) { RETURN_FALSE; } if ((res = curl_easy_escape(ch->cp, str, str_len))) { RETVAL_STRING(res); curl_free(res); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto void curl_unescape(resource ch, string str) URL decodes the given string */ PHP_FUNCTION(curl_unescape) { char *str = NULL, *out = NULL; size_t str_len = 0; int out_len; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (ZEND_SIZE_T_INT_OVFL(str_len)) { RETURN_FALSE; } if ((out = curl_easy_unescape(ch->cp, str, str_len, &out_len))) { RETVAL_STRINGL(out, out_len); curl_free(out); } else { RETURN_FALSE; } } /* }}} */ #endif #if LIBCURL_VERSION_NUM >= 0x071200 /* 7.18.0 */ /* {{{ proto void curl_pause(resource ch, int bitmask) pause and unpause a connection */ PHP_FUNCTION(curl_pause) { zend_long bitmask; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &zid, &bitmask) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } RETURN_LONG(curl_easy_pause(ch->cp, bitmask)); } /* }}} */ #endif #endif /* HAVE_CURL */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-119/c/good_5263_0
crossvul-cpp_data_bad_2131_5
/* * HID driver for some sunplus "special" devices * * Copyright (c) 1999 Andreas Gal * Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz> * Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc * Copyright (c) 2006-2007 Jiri Kosina * Copyright (c) 2008 Jiri Slaby */ /* * 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. */ #include <linux/device.h> #include <linux/hid.h> #include <linux/module.h> #include "hid-ids.h" static __u8 *sp_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 107 && rdesc[104] == 0x26 && rdesc[105] == 0x80 && rdesc[106] == 0x03) { hid_info(hdev, "fixing up Sunplus Wireless Desktop report descriptor\n"); rdesc[105] = rdesc[110] = 0x03; rdesc[106] = rdesc[111] = 0x21; } return rdesc; } #define sp_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \ EV_KEY, (c)) static int sp_input_mapping(struct hid_device *hdev, struct hid_input *hi, struct hid_field *field, struct hid_usage *usage, unsigned long **bit, int *max) { if ((usage->hid & HID_USAGE_PAGE) != HID_UP_CONSUMER) return 0; switch (usage->hid & HID_USAGE) { case 0x2003: sp_map_key_clear(KEY_ZOOMIN); break; case 0x2103: sp_map_key_clear(KEY_ZOOMOUT); break; default: return 0; } return 1; } static const struct hid_device_id sp_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_SUNPLUS, USB_DEVICE_ID_SUNPLUS_WDESKTOP) }, { } }; MODULE_DEVICE_TABLE(hid, sp_devices); static struct hid_driver sp_driver = { .name = "sunplus", .id_table = sp_devices, .report_fixup = sp_report_fixup, .input_mapping = sp_input_mapping, }; module_hid_driver(sp_driver); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2131_5
crossvul-cpp_data_bad_5128_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W W PPPP GGGG % % W W P P G % % W W W PPPP G GGG % % WW WW P G G % % W W P GGG % % % % % % Read WordPerfect Image Format % % % % Software Design % % Jaroslav Fojtik % % June 2000 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/constitute.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/cache.h" #include "MagickCore/distort.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/resource_.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" typedef struct { unsigned char Red; unsigned char Blue; unsigned char Green; } RGB_Record; /* Default palette for WPG level 1 */ static const RGB_Record WPG1_Palette[256]={ { 0, 0, 0}, { 0, 0,168}, { 0,168, 0}, { 0,168,168}, {168, 0, 0}, {168, 0,168}, {168, 84, 0}, {168,168,168}, { 84, 84, 84}, { 84, 84,252}, { 84,252, 84}, { 84,252,252}, {252, 84, 84}, {252, 84,252}, {252,252, 84}, {252,252,252}, /*16*/ { 0, 0, 0}, { 20, 20, 20}, { 32, 32, 32}, { 44, 44, 44}, { 56, 56, 56}, { 68, 68, 68}, { 80, 80, 80}, { 96, 96, 96}, {112,112,112}, {128,128,128}, {144,144,144}, {160,160,160}, {180,180,180}, {200,200,200}, {224,224,224}, {252,252,252}, /*32*/ { 0, 0,252}, { 64, 0,252}, {124, 0,252}, {188, 0,252}, {252, 0,252}, {252, 0,188}, {252, 0,124}, {252, 0, 64}, {252, 0, 0}, {252, 64, 0}, {252,124, 0}, {252,188, 0}, {252,252, 0}, {188,252, 0}, {124,252, 0}, { 64,252, 0}, /*48*/ { 0,252, 0}, { 0,252, 64}, { 0,252,124}, { 0,252,188}, { 0,252,252}, { 0,188,252}, { 0,124,252}, { 0, 64,252}, {124,124,252}, {156,124,252}, {188,124,252}, {220,124,252}, {252,124,252}, {252,124,220}, {252,124,188}, {252,124,156}, /*64*/ {252,124,124}, {252,156,124}, {252,188,124}, {252,220,124}, {252,252,124}, {220,252,124}, {188,252,124}, {156,252,124}, {124,252,124}, {124,252,156}, {124,252,188}, {124,252,220}, {124,252,252}, {124,220,252}, {124,188,252}, {124,156,252}, /*80*/ {180,180,252}, {196,180,252}, {216,180,252}, {232,180,252}, {252,180,252}, {252,180,232}, {252,180,216}, {252,180,196}, {252,180,180}, {252,196,180}, {252,216,180}, {252,232,180}, {252,252,180}, {232,252,180}, {216,252,180}, {196,252,180}, /*96*/ {180,220,180}, {180,252,196}, {180,252,216}, {180,252,232}, {180,252,252}, {180,232,252}, {180,216,252}, {180,196,252}, {0,0,112}, {28,0,112}, {56,0,112}, {84,0,112}, {112,0,112}, {112,0,84}, {112,0,56}, {112,0,28}, /*112*/ {112,0,0}, {112,28,0}, {112,56,0}, {112,84,0}, {112,112,0}, {84,112,0}, {56,112,0}, {28,112,0}, {0,112,0}, {0,112,28}, {0,112,56}, {0,112,84}, {0,112,112}, {0,84,112}, {0,56,112}, {0,28,112}, /*128*/ {56,56,112}, {68,56,112}, {84,56,112}, {96,56,112}, {112,56,112}, {112,56,96}, {112,56,84}, {112,56,68}, {112,56,56}, {112,68,56}, {112,84,56}, {112,96,56}, {112,112,56}, {96,112,56}, {84,112,56}, {68,112,56}, /*144*/ {56,112,56}, {56,112,69}, {56,112,84}, {56,112,96}, {56,112,112}, {56,96,112}, {56,84,112}, {56,68,112}, {80,80,112}, {88,80,112}, {96,80,112}, {104,80,112}, {112,80,112}, {112,80,104}, {112,80,96}, {112,80,88}, /*160*/ {112,80,80}, {112,88,80}, {112,96,80}, {112,104,80}, {112,112,80}, {104,112,80}, {96,112,80}, {88,112,80}, {80,112,80}, {80,112,88}, {80,112,96}, {80,112,104}, {80,112,112}, {80,114,112}, {80,96,112}, {80,88,112}, /*176*/ {0,0,64}, {16,0,64}, {32,0,64}, {48,0,64}, {64,0,64}, {64,0,48}, {64,0,32}, {64,0,16}, {64,0,0}, {64,16,0}, {64,32,0}, {64,48,0}, {64,64,0}, {48,64,0}, {32,64,0}, {16,64,0}, /*192*/ {0,64,0}, {0,64,16}, {0,64,32}, {0,64,48}, {0,64,64}, {0,48,64}, {0,32,64}, {0,16,64}, {32,32,64}, {40,32,64}, {48,32,64}, {56,32,64}, {64,32,64}, {64,32,56}, {64,32,48}, {64,32,40}, /*208*/ {64,32,32}, {64,40,32}, {64,48,32}, {64,56,32}, {64,64,32}, {56,64,32}, {48,64,32}, {40,64,32}, {32,64,32}, {32,64,40}, {32,64,48}, {32,64,56}, {32,64,64}, {32,56,64}, {32,48,64}, {32,40,64}, /*224*/ {44,44,64}, {48,44,64}, {52,44,64}, {60,44,64}, {64,44,64}, {64,44,60}, {64,44,52}, {64,44,48}, {64,44,44}, {64,48,44}, {64,52,44}, {64,60,44}, {64,64,44}, {60,64,44}, {52,64,44}, {48,64,44}, /*240*/ {44,64,44}, {44,64,48}, {44,64,52}, {44,64,60}, {44,64,64}, {44,60,64}, {44,55,64}, {44,48,64}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} /*256*/ }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s W P G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsWPG() returns True if the image format type, identified by the magick % string, is WPG. % % The format of the IsWPG method is: % % unsigned int IsWPG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o status: Method IsWPG returns True if the image format type is WPG. % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static unsigned int IsWPG(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\377WPC",4) == 0) return(MagickTrue); return(MagickFalse); } static void Rd_WP_DWORD(Image *image,size_t *d) { unsigned char b; b=ReadBlobByte(image); *d=b; if (b < 0xFFU) return; b=ReadBlobByte(image); *d=(size_t) b; b=ReadBlobByte(image); *d+=(size_t) b*256l; if (*d < 0x8000) return; *d=(*d & 0x7FFF) << 16; b=ReadBlobByte(image); *d+=(size_t) b; b=ReadBlobByte(image); *d+=(size_t) b*256l; return; } static void InsertRow(Image *image,unsigned char *p,ssize_t y,int bpp, ExceptionInfo *exception) { int bit; Quantum index; register Quantum *q; ssize_t x; switch (bpp) { case 1: /* Convert bitmap scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } p++; } if (!SyncAuthenticPixels(image,exception)) break; break; } case 2: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-3); x+=4) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x3,exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); if ((image->columns % 4) > 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); if ((image->columns % 4) > 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3, exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 4: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x0f,exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 8: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p,exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } break; case 24: /* Convert DirectColor scanline. */ q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (!SyncAuthenticPixels(image,exception)) break; break; } } /* Helper for WPG1 raster reader. */ #define InsertByte(b) \ { \ BImgBuff[x]=b; \ x++; \ if((ssize_t) x>=ldblk) \ { \ InsertRow(image,BImgBuff,(ssize_t) y,bpp,exception); \ x=0; \ y++; \ } \ } /* WPG1 raster reader. */ static int UnpackWPGRaster(Image *image,int bpp,ExceptionInfo *exception) { int x, y, i; unsigned char bbuf, *BImgBuff, RunCount; ssize_t ldblk; x=0; y=0; ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, 8*sizeof(*BImgBuff)); if(BImgBuff==NULL) return(-2); while(y<(ssize_t) image->rows) { int c; c=ReadBlobByte(image); if (c == EOF) break; bbuf=(unsigned char) c; RunCount=bbuf & 0x7F; if(bbuf & 0x80) { if(RunCount) /* repeat next byte runcount * */ { bbuf=ReadBlobByte(image); for(i=0;i<(int) RunCount;i++) InsertByte(bbuf); } else { /* read next byte as RunCount; repeat 0xFF runcount* */ c=ReadBlobByte(image); if (c < 0) break; RunCount=(unsigned char) c; for(i=0;i<(int) RunCount;i++) InsertByte(0xFF); } } else { if(RunCount) /* next runcount byte are readed directly */ { for(i=0;i < (int) RunCount;i++) { bbuf=ReadBlobByte(image); InsertByte(bbuf); } } else { /* repeat previous line runcount* */ c=ReadBlobByte(image); if (c < 0) break; RunCount=(unsigned char) c; if(x) { /* attempt to duplicate row from x position: */ /* I do not know what to do here */ BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(-3); } for(i=0;i < (int) RunCount;i++) { x=0; y++; /* Here I need to duplicate previous row RUNCOUNT* */ if(y<2) continue; if(y>(ssize_t) image->rows) { BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(-4); } InsertRow(image,BImgBuff,y-1,bpp,exception); } } } if (EOFBlob(image) != MagickFalse) break; } BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(y <(ssize_t) image->rows ? -5 : 0); } /* Helper for WPG2 reader. */ #define InsertByte6(b) \ { \ DisableMSCWarning(4310) \ if(XorMe)\ BImgBuff[x] = (unsigned char)~b;\ else\ BImgBuff[x] = b;\ RestoreMSCWarning \ x++; \ if((ssize_t) x >= ldblk) \ { \ InsertRow(image,BImgBuff,(ssize_t) y,bpp,exception); \ x=0; \ y++; \ } \ } /* WPG2 raster reader. */ static int UnpackWPG2Raster(Image *image,int bpp,ExceptionInfo *exception) { int RunCount, XorMe = 0; size_t x, y; ssize_t i, ldblk; unsigned int SampleSize=1; unsigned char bbuf, *BImgBuff, SampleBuffer[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; x=0; y=0; ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, sizeof(*BImgBuff)); if(BImgBuff==NULL) return(-2); while( y< image->rows) { bbuf=ReadBlobByte(image); switch(bbuf) { case 0x7D: SampleSize=ReadBlobByte(image); /* DSZ */ if(SampleSize>8) return(-2); if(SampleSize<1) return(-2); break; case 0x7E: (void) FormatLocaleFile(stderr, "\nUnsupported WPG token XOR, please report!"); XorMe=!XorMe; break; case 0x7F: RunCount=ReadBlobByte(image); /* BLK */ if (RunCount < 0) break; for(i=0; i < SampleSize*(RunCount+1); i++) { InsertByte6(0); } break; case 0xFD: RunCount=ReadBlobByte(image); /* EXT */ if (RunCount < 0) break; for(i=0; i<= RunCount;i++) for(bbuf=0; bbuf < SampleSize; bbuf++) InsertByte6(SampleBuffer[bbuf]); break; case 0xFE: RunCount=ReadBlobByte(image); /* RST */ if (RunCount < 0) break; if(x!=0) { (void) FormatLocaleFile(stderr, "\nUnsupported WPG2 unaligned token RST x=%.20g, please report!\n" ,(double) x); return(-3); } { /* duplicate the previous row RunCount x */ for(i=0;i<=RunCount;i++) { InsertRow(image,BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1), bpp,exception); y++; } } break; case 0xFF: RunCount=ReadBlobByte(image); /* WHT */ if (RunCount < 0) break; for(i=0; i < SampleSize*(RunCount+1); i++) { InsertByte6(0xFF); } break; default: RunCount=bbuf & 0x7F; if(bbuf & 0x80) /* REP */ { for(i=0; i < SampleSize; i++) SampleBuffer[i]=ReadBlobByte(image); for(i=0;i<=RunCount;i++) for(bbuf=0;bbuf<SampleSize;bbuf++) InsertByte6(SampleBuffer[bbuf]); } else { /* NRP */ for(i=0; i< SampleSize*(RunCount+1);i++) { bbuf=ReadBlobByte(image); InsertByte6(bbuf); } } } if (EOFBlob(image) != MagickFalse) break; } BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(0); } typedef float tCTM[3][3]; static unsigned LoadWPG2Flags(Image *image,char Precision,float *Angle,tCTM *CTM) { const unsigned char TPR=1,TRN=2,SKW=4,SCL=8,ROT=0x10,OID=0x20,LCK=0x80; ssize_t x; unsigned DenX; unsigned Flags; (void) memset(*CTM,0,sizeof(*CTM)); /*CTM.erase();CTM.resize(3,3);*/ (*CTM)[0][0]=1; (*CTM)[1][1]=1; (*CTM)[2][2]=1; Flags=ReadBlobLSBShort(image); if(Flags & LCK) (void) ReadBlobLSBLong(image); /*Edit lock*/ if(Flags & OID) { if(Precision==0) {(void) ReadBlobLSBShort(image);} /*ObjectID*/ else {(void) ReadBlobLSBLong(image);} /*ObjectID (Double precision)*/ } if(Flags & ROT) { x=ReadBlobLSBLong(image); /*Rot Angle*/ if(Angle) *Angle=x/65536.0; } if(Flags & (ROT|SCL)) { x=ReadBlobLSBLong(image); /*Sx*cos()*/ (*CTM)[0][0] = (float)x/0x10000; x=ReadBlobLSBLong(image); /*Sy*cos()*/ (*CTM)[1][1] = (float)x/0x10000; } if(Flags & (ROT|SKW)) { x=ReadBlobLSBLong(image); /*Kx*sin()*/ (*CTM)[1][0] = (float)x/0x10000; x=ReadBlobLSBLong(image); /*Ky*sin()*/ (*CTM)[0][1] = (float)x/0x10000; } if(Flags & TRN) { x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Tx*/ if(x>=0) (*CTM)[0][2] = (float)x+(float)DenX/0x10000; else (*CTM)[0][2] = (float)x-(float)DenX/0x10000; x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Ty*/ (*CTM)[1][2]=(float)x + ((x>=0)?1:-1)*(float)DenX/0x10000; if(x>=0) (*CTM)[1][2] = (float)x+(float)DenX/0x10000; else (*CTM)[1][2] = (float)x-(float)DenX/0x10000; } if(Flags & TPR) { x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Px*/ (*CTM)[2][0] = x + (float)DenX/0x10000;; x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Py*/ (*CTM)[2][1] = x + (float)DenX/0x10000; } return(Flags); } static Image *ExtractPostscript(Image *image,const ImageInfo *image_info, MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception) { char postscript_file[MagickPathExtent]; const MagicInfo *magic_info; FILE *ps_file; ImageInfo *clone_info; Image *image2; unsigned char magick[2*MagickPathExtent]; if ((clone_info=CloneImageInfo(image_info)) == NULL) return(image); clone_info->blob=(void *) NULL; clone_info->length=0; /* Obtain temporary file */ (void) AcquireUniqueFilename(postscript_file); ps_file=fopen_utf8(postscript_file,"wb"); if (ps_file == (FILE *) NULL) goto FINISH; /* Copy postscript to temporary file */ (void) SeekBlob(image,PS_Offset,SEEK_SET); (void) ReadBlob(image, 2*MagickPathExtent, magick); (void) SeekBlob(image,PS_Offset,SEEK_SET); while(PS_Size-- > 0) { (void) fputc(ReadBlobByte(image),ps_file); } (void) fclose(ps_file); /* Detect file format - Check magic.mgk configuration file. */ magic_info=GetMagicInfo(magick,2*MagickPathExtent,exception); if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL; /* printf("Detected:%s \n",magic_info->name); */ if(exception->severity != UndefinedException) goto FINISH_UNL; if(magic_info->name == (char *) NULL) goto FINISH_UNL; (void) strncpy(clone_info->magick,magic_info->name,MagickPathExtent); /* Read nested image */ /*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/ FormatLocaleString(clone_info->filename,MagickPathExtent,"%s",postscript_file); image2=ReadImage(clone_info,exception); if (!image2) goto FINISH_UNL; /* Replace current image with new image while copying base image attributes. */ (void) CopyMagickMemory(image2->filename,image->filename,MagickPathExtent); (void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MagickPathExtent); (void) CopyMagickMemory(image2->magick,image->magick,MagickPathExtent); image2->depth=image->depth; DestroyBlob(image2); image2->blob=ReferenceBlob(image->blob); if ((image->rows == 0) || (image->columns == 0)) DeleteImageFromList(&image); AppendImageToList(&image,image2); FINISH_UNL: (void) RelinquishUniqueFileResource(postscript_file); FINISH: DestroyImageInfo(clone_info); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d W P G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method ReadWPGImage reads an WPG X image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadWPGImage method is: % % Image *ReadWPGImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadWPGImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1; image=AcquireImage(image_info,exception); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported"); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->resolution.x=BitmapHeader1.HorzRes/470.0; image->resolution.y=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->resolution.x=BitmapHeader2.HorzRes/470.0; image->resolution.y=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: if ((image->colors == 0) && (bpp != 24)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) { NoMemory: ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* printf("Load default colormap \n"); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp,exception) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,"UnableToDecompressImage"); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; if ((image->colors == 0) && (bpp != 24)) { size_t one; one=1; image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk+1,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(image,BImgBuff,i,bpp,exception); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp,exception) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); } } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, "ImageFileDoesNotContainAnyImageData"); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r W P G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method RegisterWPGImage adds attributes for the WPG image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterWPGImage method is: % % size_t RegisterWPGImage(void) % */ ModuleExport size_t RegisterWPGImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("WPG","WPG","Word Perfect Graphics"); entry->decoder=(DecodeImageHandler *) ReadWPGImage; entry->magick=(IsImageFormatHandler *) IsWPG; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r W P G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method UnregisterWPGImage removes format registrations made by the % WPG module from the list of supported formats. % % The format of the UnregisterWPGImage method is: % % UnregisterWPGImage(void) % */ ModuleExport void UnregisterWPGImage(void) { (void) UnregisterMagickInfo("WPG"); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5128_0
crossvul-cpp_data_good_2308_0
/* ssl/d1_lib.c */ /* * DTLS implementation written by Nagendra Modadugu * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. */ /* ==================================================================== * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #define USE_SOCKETS #include <openssl/objects.h> #include "ssl_locl.h" #if defined(OPENSSL_SYS_VMS) #include <sys/timeb.h> #endif static void get_current_time(struct timeval *t); static void dtls1_set_handshake_header(SSL *s, int type, unsigned long len); static int dtls1_handshake_write(SSL *s); const char dtls1_version_str[]="DTLSv1" OPENSSL_VERSION_PTEXT; int dtls1_listen(SSL *s, struct sockaddr *client); SSL3_ENC_METHOD DTLSv1_enc_data={ tls1_enc, tls1_mac, tls1_setup_key_block, tls1_generate_master_secret, tls1_change_cipher_state, tls1_final_finish_mac, TLS1_FINISH_MAC_LENGTH, tls1_cert_verify_mac, TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE, TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE, tls1_alert_code, tls1_export_keying_material, SSL_ENC_FLAG_DTLS|SSL_ENC_FLAG_EXPLICIT_IV, DTLS1_HM_HEADER_LENGTH, dtls1_set_handshake_header, dtls1_handshake_write }; SSL3_ENC_METHOD DTLSv1_2_enc_data={ tls1_enc, tls1_mac, tls1_setup_key_block, tls1_generate_master_secret, tls1_change_cipher_state, tls1_final_finish_mac, TLS1_FINISH_MAC_LENGTH, tls1_cert_verify_mac, TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE, TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE, tls1_alert_code, tls1_export_keying_material, SSL_ENC_FLAG_DTLS|SSL_ENC_FLAG_EXPLICIT_IV|SSL_ENC_FLAG_SIGALGS |SSL_ENC_FLAG_SHA256_PRF|SSL_ENC_FLAG_TLS1_2_CIPHERS, DTLS1_HM_HEADER_LENGTH, dtls1_set_handshake_header, dtls1_handshake_write }; long dtls1_default_timeout(void) { /* 2 hours, the 24 hours mentioned in the DTLSv1 spec * is way too long for http, the cache would over fill */ return(60*60*2); } int dtls1_new(SSL *s) { DTLS1_STATE *d1; if (!ssl3_new(s)) return(0); if ((d1=OPENSSL_malloc(sizeof *d1)) == NULL) return (0); memset(d1,0, sizeof *d1); /* d1->handshake_epoch=0; */ d1->unprocessed_rcds.q=pqueue_new(); d1->processed_rcds.q=pqueue_new(); d1->buffered_messages = pqueue_new(); d1->sent_messages=pqueue_new(); d1->buffered_app_data.q=pqueue_new(); if ( s->server) { d1->cookie_len = sizeof(s->d1->cookie); } if( ! d1->unprocessed_rcds.q || ! d1->processed_rcds.q || ! d1->buffered_messages || ! d1->sent_messages || ! d1->buffered_app_data.q) { if ( d1->unprocessed_rcds.q) pqueue_free(d1->unprocessed_rcds.q); if ( d1->processed_rcds.q) pqueue_free(d1->processed_rcds.q); if ( d1->buffered_messages) pqueue_free(d1->buffered_messages); if ( d1->sent_messages) pqueue_free(d1->sent_messages); if ( d1->buffered_app_data.q) pqueue_free(d1->buffered_app_data.q); OPENSSL_free(d1); return (0); } s->d1=d1; s->method->ssl_clear(s); return(1); } static void dtls1_clear_queues(SSL *s) { pitem *item = NULL; hm_fragment *frag = NULL; DTLS1_RECORD_DATA *rdata; while( (item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } while( (item = pqueue_pop(s->d1->processed_rcds.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } while( (item = pqueue_pop(s->d1->buffered_messages)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } while ( (item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } while ( (item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } } void dtls1_free(SSL *s) { ssl3_free(s); dtls1_clear_queues(s); pqueue_free(s->d1->unprocessed_rcds.q); pqueue_free(s->d1->processed_rcds.q); pqueue_free(s->d1->buffered_messages); pqueue_free(s->d1->sent_messages); pqueue_free(s->d1->buffered_app_data.q); OPENSSL_free(s->d1); s->d1 = NULL; } void dtls1_clear(SSL *s) { pqueue unprocessed_rcds; pqueue processed_rcds; pqueue buffered_messages; pqueue sent_messages; pqueue buffered_app_data; unsigned int mtu; if (s->d1) { unprocessed_rcds = s->d1->unprocessed_rcds.q; processed_rcds = s->d1->processed_rcds.q; buffered_messages = s->d1->buffered_messages; sent_messages = s->d1->sent_messages; buffered_app_data = s->d1->buffered_app_data.q; mtu = s->d1->mtu; dtls1_clear_queues(s); memset(s->d1, 0, sizeof(*(s->d1))); if (s->server) { s->d1->cookie_len = sizeof(s->d1->cookie); } if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) { s->d1->mtu = mtu; } s->d1->unprocessed_rcds.q = unprocessed_rcds; s->d1->processed_rcds.q = processed_rcds; s->d1->buffered_messages = buffered_messages; s->d1->sent_messages = sent_messages; s->d1->buffered_app_data.q = buffered_app_data; } ssl3_clear(s); if (s->options & SSL_OP_CISCO_ANYCONNECT) s->version=DTLS1_BAD_VER; else if (s->method->version == DTLS_ANY_VERSION) s->version=DTLS1_2_VERSION; else s->version=s->method->version; } long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg) { int ret=0; switch (cmd) { case DTLS_CTRL_GET_TIMEOUT: if (dtls1_get_timeout(s, (struct timeval*) parg) != NULL) { ret = 1; } break; case DTLS_CTRL_HANDLE_TIMEOUT: ret = dtls1_handle_timeout(s); break; case DTLS_CTRL_LISTEN: ret = dtls1_listen(s, parg); break; default: ret = ssl3_ctrl(s, cmd, larg, parg); break; } return(ret); } /* * As it's impossible to use stream ciphers in "datagram" mode, this * simple filter is designed to disengage them in DTLS. Unfortunately * there is no universal way to identify stream SSL_CIPHER, so we have * to explicitly list their SSL_* codes. Currently RC4 is the only one * available, but if new ones emerge, they will have to be added... */ const SSL_CIPHER *dtls1_get_cipher(unsigned int u) { const SSL_CIPHER *ciph = ssl3_get_cipher(u); if (ciph != NULL) { if (ciph->algorithm_enc == SSL_RC4) return NULL; } return ciph; } void dtls1_start_timer(SSL *s) { #ifndef OPENSSL_NO_SCTP /* Disable timer for SCTP */ if (BIO_dgram_is_sctp(SSL_get_wbio(s))) { memset(&(s->d1->next_timeout), 0, sizeof(struct timeval)); return; } #endif /* If timer is not set, initialize duration with 1 second */ if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) { s->d1->timeout_duration = 1; } /* Set timeout to current time */ get_current_time(&(s->d1->next_timeout)); /* Add duration to current time */ s->d1->next_timeout.tv_sec += s->d1->timeout_duration; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &(s->d1->next_timeout)); } struct timeval* dtls1_get_timeout(SSL *s, struct timeval* timeleft) { struct timeval timenow; /* If no timeout is set, just return NULL */ if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) { return NULL; } /* Get current time */ get_current_time(&timenow); /* If timer already expired, set remaining time to 0 */ if (s->d1->next_timeout.tv_sec < timenow.tv_sec || (s->d1->next_timeout.tv_sec == timenow.tv_sec && s->d1->next_timeout.tv_usec <= timenow.tv_usec)) { memset(timeleft, 0, sizeof(struct timeval)); return timeleft; } /* Calculate time left until timer expires */ memcpy(timeleft, &(s->d1->next_timeout), sizeof(struct timeval)); timeleft->tv_sec -= timenow.tv_sec; timeleft->tv_usec -= timenow.tv_usec; if (timeleft->tv_usec < 0) { timeleft->tv_sec--; timeleft->tv_usec += 1000000; } /* If remaining time is less than 15 ms, set it to 0 * to prevent issues because of small devergences with * socket timeouts. */ if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000) { memset(timeleft, 0, sizeof(struct timeval)); } return timeleft; } int dtls1_is_timer_expired(SSL *s) { struct timeval timeleft; /* Get time left until timeout, return false if no timer running */ if (dtls1_get_timeout(s, &timeleft) == NULL) { return 0; } /* Return false if timer is not expired yet */ if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) { return 0; } /* Timer expired, so return true */ return 1; } void dtls1_double_timeout(SSL *s) { s->d1->timeout_duration *= 2; if (s->d1->timeout_duration > 60) s->d1->timeout_duration = 60; dtls1_start_timer(s); } void dtls1_stop_timer(SSL *s) { /* Reset everything */ memset(&(s->d1->timeout), 0, sizeof(struct dtls1_timeout_st)); memset(&(s->d1->next_timeout), 0, sizeof(struct timeval)); s->d1->timeout_duration = 1; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &(s->d1->next_timeout)); /* Clear retransmission buffer */ dtls1_clear_record_buffer(s); } int dtls1_check_timeout_num(SSL *s) { s->d1->timeout.num_alerts++; /* Reduce MTU after 2 unsuccessful retransmissions */ if (s->d1->timeout.num_alerts > 2) { s->d1->mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0, NULL); } if (s->d1->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT) { /* fail the connection, enough alerts have been sent */ SSLerr(SSL_F_DTLS1_CHECK_TIMEOUT_NUM,SSL_R_READ_TIMEOUT_EXPIRED); return -1; } return 0; } int dtls1_handle_timeout(SSL *s) { /* if no timer is expired, don't do anything */ if (!dtls1_is_timer_expired(s)) { return 0; } dtls1_double_timeout(s); if (dtls1_check_timeout_num(s) < 0) return -1; s->d1->timeout.read_timeouts++; if (s->d1->timeout.read_timeouts > DTLS1_TMO_READ_COUNT) { s->d1->timeout.read_timeouts = 1; } #ifndef OPENSSL_NO_HEARTBEATS if (s->tlsext_hb_pending) { s->tlsext_hb_pending = 0; return dtls1_heartbeat(s); } #endif dtls1_start_timer(s); return dtls1_retransmit_buffered_messages(s); } static void get_current_time(struct timeval *t) { #if defined(_WIN32) SYSTEMTIME st; union { unsigned __int64 ul; FILETIME ft; } now; GetSystemTime(&st); SystemTimeToFileTime(&st,&now.ft); #ifdef __MINGW32__ now.ul -= 116444736000000000ULL; #else now.ul -= 116444736000000000UI64; /* re-bias to 1/1/1970 */ #endif t->tv_sec = (long)(now.ul/10000000); t->tv_usec = ((int)(now.ul%10000000))/10; #elif defined(OPENSSL_SYS_VMS) struct timeb tb; ftime(&tb); t->tv_sec = (long)tb.time; t->tv_usec = (long)tb.millitm * 1000; #else gettimeofday(t, NULL); #endif } int dtls1_listen(SSL *s, struct sockaddr *client) { int ret; SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE); s->d1->listen = 1; ret = SSL_accept(s); if (ret <= 0) return ret; (void) BIO_dgram_get_peer(SSL_get_rbio(s), client); return 1; } static void dtls1_set_handshake_header(SSL *s, int htype, unsigned long len) { unsigned char *p = (unsigned char *)s->init_buf->data; dtls1_set_message_header(s, p, htype, len, 0, len); s->init_num = (int)len + DTLS1_HM_HEADER_LENGTH; s->init_off = 0; /* Buffer the message to handle re-xmits */ dtls1_buffer_message(s, 0); } static int dtls1_handshake_write(SSL *s) { return dtls1_do_write(s, SSL3_RT_HANDSHAKE); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2308_0
crossvul-cpp_data_bad_4946_0
#include "builtin.h" #include "cache.h" #include "attr.h" #include "object.h" #include "blob.h" #include "commit.h" #include "tag.h" #include "tree.h" #include "delta.h" #include "pack.h" #include "pack-revindex.h" #include "csum-file.h" #include "tree-walk.h" #include "diff.h" #include "revision.h" #include "list-objects.h" #include "pack-objects.h" #include "progress.h" #include "refs.h" #include "streaming.h" #include "thread-utils.h" #include "pack-bitmap.h" #include "reachable.h" #include "sha1-array.h" #include "argv-array.h" static const char *pack_usage[] = { N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"), N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"), NULL }; /* * Objects we are going to pack are collected in the `to_pack` structure. * It contains an array (dynamically expanded) of the object data, and a map * that can resolve SHA1s to their position in the array. */ static struct packing_data to_pack; static struct pack_idx_entry **written_list; static uint32_t nr_result, nr_written; static int non_empty; static int reuse_delta = 1, reuse_object = 1; static int keep_unreachable, unpack_unreachable, include_tag; static unsigned long unpack_unreachable_expiration; static int local; static int incremental; static int ignore_packed_keep; static int allow_ofs_delta; static struct pack_idx_option pack_idx_opts; static const char *base_name; static int progress = 1; static int window = 10; static unsigned long pack_size_limit; static int depth = 50; static int delta_search_threads; static int pack_to_stdout; static int num_preferred_base; static struct progress *progress_state; static int pack_compression_level = Z_DEFAULT_COMPRESSION; static int pack_compression_seen; static struct packed_git *reuse_packfile; static uint32_t reuse_packfile_objects; static off_t reuse_packfile_offset; static int use_bitmap_index = 1; static int write_bitmap_index; static uint16_t write_bitmap_options; static unsigned long delta_cache_size = 0; static unsigned long max_delta_cache_size = 256 * 1024 * 1024; static unsigned long cache_max_small_delta_size = 1000; static unsigned long window_memory_limit = 0; /* * stats */ static uint32_t written, written_delta; static uint32_t reused, reused_delta; /* * Indexed commits */ static struct commit **indexed_commits; static unsigned int indexed_commits_nr; static unsigned int indexed_commits_alloc; static void index_commit_for_bitmap(struct commit *commit) { if (indexed_commits_nr >= indexed_commits_alloc) { indexed_commits_alloc = (indexed_commits_alloc + 32) * 2; REALLOC_ARRAY(indexed_commits, indexed_commits_alloc); } indexed_commits[indexed_commits_nr++] = commit; } static void *get_delta(struct object_entry *entry) { unsigned long size, base_size, delta_size; void *buf, *base_buf, *delta_buf; enum object_type type; buf = read_sha1_file(entry->idx.sha1, &type, &size); if (!buf) die("unable to read %s", sha1_to_hex(entry->idx.sha1)); base_buf = read_sha1_file(entry->delta->idx.sha1, &type, &base_size); if (!base_buf) die("unable to read %s", sha1_to_hex(entry->delta->idx.sha1)); delta_buf = diff_delta(base_buf, base_size, buf, size, &delta_size, 0); if (!delta_buf || delta_size != entry->delta_size) die("delta size changed"); free(buf); free(base_buf); return delta_buf; } static unsigned long do_compress(void **pptr, unsigned long size) { git_zstream stream; void *in, *out; unsigned long maxsize; git_deflate_init(&stream, pack_compression_level); maxsize = git_deflate_bound(&stream, size); in = *pptr; out = xmalloc(maxsize); *pptr = out; stream.next_in = in; stream.avail_in = size; stream.next_out = out; stream.avail_out = maxsize; while (git_deflate(&stream, Z_FINISH) == Z_OK) ; /* nothing */ git_deflate_end(&stream); free(in); return stream.total_out; } static unsigned long write_large_blob_data(struct git_istream *st, struct sha1file *f, const unsigned char *sha1) { git_zstream stream; unsigned char ibuf[1024 * 16]; unsigned char obuf[1024 * 16]; unsigned long olen = 0; git_deflate_init(&stream, pack_compression_level); for (;;) { ssize_t readlen; int zret = Z_OK; readlen = read_istream(st, ibuf, sizeof(ibuf)); if (readlen == -1) die(_("unable to read %s"), sha1_to_hex(sha1)); stream.next_in = ibuf; stream.avail_in = readlen; while ((stream.avail_in || readlen == 0) && (zret == Z_OK || zret == Z_BUF_ERROR)) { stream.next_out = obuf; stream.avail_out = sizeof(obuf); zret = git_deflate(&stream, readlen ? 0 : Z_FINISH); sha1write(f, obuf, stream.next_out - obuf); olen += stream.next_out - obuf; } if (stream.avail_in) die(_("deflate error (%d)"), zret); if (readlen == 0) { if (zret != Z_STREAM_END) die(_("deflate error (%d)"), zret); break; } } git_deflate_end(&stream); return olen; } /* * we are going to reuse the existing object data as is. make * sure it is not corrupt. */ static int check_pack_inflate(struct packed_git *p, struct pack_window **w_curs, off_t offset, off_t len, unsigned long expect) { git_zstream stream; unsigned char fakebuf[4096], *in; int st; memset(&stream, 0, sizeof(stream)); git_inflate_init(&stream); do { in = use_pack(p, w_curs, offset, &stream.avail_in); stream.next_in = in; stream.next_out = fakebuf; stream.avail_out = sizeof(fakebuf); st = git_inflate(&stream, Z_FINISH); offset += stream.next_in - in; } while (st == Z_OK || st == Z_BUF_ERROR); git_inflate_end(&stream); return (st == Z_STREAM_END && stream.total_out == expect && stream.total_in == len) ? 0 : -1; } static void copy_pack_data(struct sha1file *f, struct packed_git *p, struct pack_window **w_curs, off_t offset, off_t len) { unsigned char *in; unsigned long avail; while (len) { in = use_pack(p, w_curs, offset, &avail); if (avail > len) avail = (unsigned long)len; sha1write(f, in, avail); offset += avail; len -= avail; } } /* Return 0 if we will bust the pack-size limit */ static unsigned long write_no_reuse_object(struct sha1file *f, struct object_entry *entry, unsigned long limit, int usable_delta) { unsigned long size, datalen; unsigned char header[10], dheader[10]; unsigned hdrlen; enum object_type type; void *buf; struct git_istream *st = NULL; if (!usable_delta) { if (entry->type == OBJ_BLOB && entry->size > big_file_threshold && (st = open_istream(entry->idx.sha1, &type, &size, NULL)) != NULL) buf = NULL; else { buf = read_sha1_file(entry->idx.sha1, &type, &size); if (!buf) die(_("unable to read %s"), sha1_to_hex(entry->idx.sha1)); } /* * make sure no cached delta data remains from a * previous attempt before a pack split occurred. */ free(entry->delta_data); entry->delta_data = NULL; entry->z_delta_size = 0; } else if (entry->delta_data) { size = entry->delta_size; buf = entry->delta_data; entry->delta_data = NULL; type = (allow_ofs_delta && entry->delta->idx.offset) ? OBJ_OFS_DELTA : OBJ_REF_DELTA; } else { buf = get_delta(entry); size = entry->delta_size; type = (allow_ofs_delta && entry->delta->idx.offset) ? OBJ_OFS_DELTA : OBJ_REF_DELTA; } if (st) /* large blob case, just assume we don't compress well */ datalen = size; else if (entry->z_delta_size) datalen = entry->z_delta_size; else datalen = do_compress(&buf, size); /* * The object header is a byte of 'type' followed by zero or * more bytes of length. */ hdrlen = encode_in_pack_object_header(type, size, header); if (type == OBJ_OFS_DELTA) { /* * Deltas with relative base contain an additional * encoding of the relative offset for the delta * base from this object's position in the pack. */ off_t ofs = entry->idx.offset - entry->delta->idx.offset; unsigned pos = sizeof(dheader) - 1; dheader[pos] = ofs & 127; while (ofs >>= 7) dheader[--pos] = 128 | (--ofs & 127); if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) { if (st) close_istream(st); free(buf); return 0; } sha1write(f, header, hdrlen); sha1write(f, dheader + pos, sizeof(dheader) - pos); hdrlen += sizeof(dheader) - pos; } else if (type == OBJ_REF_DELTA) { /* * Deltas with a base reference contain * an additional 20 bytes for the base sha1. */ if (limit && hdrlen + 20 + datalen + 20 >= limit) { if (st) close_istream(st); free(buf); return 0; } sha1write(f, header, hdrlen); sha1write(f, entry->delta->idx.sha1, 20); hdrlen += 20; } else { if (limit && hdrlen + datalen + 20 >= limit) { if (st) close_istream(st); free(buf); return 0; } sha1write(f, header, hdrlen); } if (st) { datalen = write_large_blob_data(st, f, entry->idx.sha1); close_istream(st); } else { sha1write(f, buf, datalen); free(buf); } return hdrlen + datalen; } /* Return 0 if we will bust the pack-size limit */ static unsigned long write_reuse_object(struct sha1file *f, struct object_entry *entry, unsigned long limit, int usable_delta) { struct packed_git *p = entry->in_pack; struct pack_window *w_curs = NULL; struct revindex_entry *revidx; off_t offset; enum object_type type = entry->type; unsigned long datalen; unsigned char header[10], dheader[10]; unsigned hdrlen; if (entry->delta) type = (allow_ofs_delta && entry->delta->idx.offset) ? OBJ_OFS_DELTA : OBJ_REF_DELTA; hdrlen = encode_in_pack_object_header(type, entry->size, header); offset = entry->in_pack_offset; revidx = find_pack_revindex(p, offset); datalen = revidx[1].offset - offset; if (!pack_to_stdout && p->index_version > 1 && check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) { error("bad packed object CRC for %s", sha1_to_hex(entry->idx.sha1)); unuse_pack(&w_curs); return write_no_reuse_object(f, entry, limit, usable_delta); } offset += entry->in_pack_header_size; datalen -= entry->in_pack_header_size; if (!pack_to_stdout && p->index_version == 1 && check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) { error("corrupt packed object for %s", sha1_to_hex(entry->idx.sha1)); unuse_pack(&w_curs); return write_no_reuse_object(f, entry, limit, usable_delta); } if (type == OBJ_OFS_DELTA) { off_t ofs = entry->idx.offset - entry->delta->idx.offset; unsigned pos = sizeof(dheader) - 1; dheader[pos] = ofs & 127; while (ofs >>= 7) dheader[--pos] = 128 | (--ofs & 127); if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) { unuse_pack(&w_curs); return 0; } sha1write(f, header, hdrlen); sha1write(f, dheader + pos, sizeof(dheader) - pos); hdrlen += sizeof(dheader) - pos; reused_delta++; } else if (type == OBJ_REF_DELTA) { if (limit && hdrlen + 20 + datalen + 20 >= limit) { unuse_pack(&w_curs); return 0; } sha1write(f, header, hdrlen); sha1write(f, entry->delta->idx.sha1, 20); hdrlen += 20; reused_delta++; } else { if (limit && hdrlen + datalen + 20 >= limit) { unuse_pack(&w_curs); return 0; } sha1write(f, header, hdrlen); } copy_pack_data(f, p, &w_curs, offset, datalen); unuse_pack(&w_curs); reused++; return hdrlen + datalen; } /* Return 0 if we will bust the pack-size limit */ static unsigned long write_object(struct sha1file *f, struct object_entry *entry, off_t write_offset) { unsigned long limit, len; int usable_delta, to_reuse; if (!pack_to_stdout) crc32_begin(f); /* apply size limit if limited packsize and not first object */ if (!pack_size_limit || !nr_written) limit = 0; else if (pack_size_limit <= write_offset) /* * the earlier object did not fit the limit; avoid * mistaking this with unlimited (i.e. limit = 0). */ limit = 1; else limit = pack_size_limit - write_offset; if (!entry->delta) usable_delta = 0; /* no delta */ else if (!pack_size_limit) usable_delta = 1; /* unlimited packfile */ else if (entry->delta->idx.offset == (off_t)-1) usable_delta = 0; /* base was written to another pack */ else if (entry->delta->idx.offset) usable_delta = 1; /* base already exists in this pack */ else usable_delta = 0; /* base could end up in another pack */ if (!reuse_object) to_reuse = 0; /* explicit */ else if (!entry->in_pack) to_reuse = 0; /* can't reuse what we don't have */ else if (entry->type == OBJ_REF_DELTA || entry->type == OBJ_OFS_DELTA) /* check_object() decided it for us ... */ to_reuse = usable_delta; /* ... but pack split may override that */ else if (entry->type != entry->in_pack_type) to_reuse = 0; /* pack has delta which is unusable */ else if (entry->delta) to_reuse = 0; /* we want to pack afresh */ else to_reuse = 1; /* we have it in-pack undeltified, * and we do not need to deltify it. */ if (!to_reuse) len = write_no_reuse_object(f, entry, limit, usable_delta); else len = write_reuse_object(f, entry, limit, usable_delta); if (!len) return 0; if (usable_delta) written_delta++; written++; if (!pack_to_stdout) entry->idx.crc32 = crc32_end(f); return len; } enum write_one_status { WRITE_ONE_SKIP = -1, /* already written */ WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */ WRITE_ONE_WRITTEN = 1, /* normal */ WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */ }; static enum write_one_status write_one(struct sha1file *f, struct object_entry *e, off_t *offset) { unsigned long size; int recursing; /* * we set offset to 1 (which is an impossible value) to mark * the fact that this object is involved in "write its base * first before writing a deltified object" recursion. */ recursing = (e->idx.offset == 1); if (recursing) { warning("recursive delta detected for object %s", sha1_to_hex(e->idx.sha1)); return WRITE_ONE_RECURSIVE; } else if (e->idx.offset || e->preferred_base) { /* offset is non zero if object is written already. */ return WRITE_ONE_SKIP; } /* if we are deltified, write out base object first. */ if (e->delta) { e->idx.offset = 1; /* now recurse */ switch (write_one(f, e->delta, offset)) { case WRITE_ONE_RECURSIVE: /* we cannot depend on this one */ e->delta = NULL; break; default: break; case WRITE_ONE_BREAK: e->idx.offset = recursing; return WRITE_ONE_BREAK; } } e->idx.offset = *offset; size = write_object(f, e, *offset); if (!size) { e->idx.offset = recursing; return WRITE_ONE_BREAK; } written_list[nr_written++] = &e->idx; /* make sure off_t is sufficiently large not to wrap */ if (signed_add_overflows(*offset, size)) die("pack too large for current definition of off_t"); *offset += size; return WRITE_ONE_WRITTEN; } static int mark_tagged(const char *path, const struct object_id *oid, int flag, void *cb_data) { unsigned char peeled[20]; struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL); if (entry) entry->tagged = 1; if (!peel_ref(path, peeled)) { entry = packlist_find(&to_pack, peeled, NULL); if (entry) entry->tagged = 1; } return 0; } static inline void add_to_write_order(struct object_entry **wo, unsigned int *endp, struct object_entry *e) { if (e->filled) return; wo[(*endp)++] = e; e->filled = 1; } static void add_descendants_to_write_order(struct object_entry **wo, unsigned int *endp, struct object_entry *e) { int add_to_order = 1; while (e) { if (add_to_order) { struct object_entry *s; /* add this node... */ add_to_write_order(wo, endp, e); /* all its siblings... */ for (s = e->delta_sibling; s; s = s->delta_sibling) { add_to_write_order(wo, endp, s); } } /* drop down a level to add left subtree nodes if possible */ if (e->delta_child) { add_to_order = 1; e = e->delta_child; } else { add_to_order = 0; /* our sibling might have some children, it is next */ if (e->delta_sibling) { e = e->delta_sibling; continue; } /* go back to our parent node */ e = e->delta; while (e && !e->delta_sibling) { /* we're on the right side of a subtree, keep * going up until we can go right again */ e = e->delta; } if (!e) { /* done- we hit our original root node */ return; } /* pass it off to sibling at this level */ e = e->delta_sibling; } }; } static void add_family_to_write_order(struct object_entry **wo, unsigned int *endp, struct object_entry *e) { struct object_entry *root; for (root = e; root->delta; root = root->delta) ; /* nothing */ add_descendants_to_write_order(wo, endp, root); } static struct object_entry **compute_write_order(void) { unsigned int i, wo_end, last_untagged; struct object_entry **wo = xmalloc(to_pack.nr_objects * sizeof(*wo)); struct object_entry *objects = to_pack.objects; for (i = 0; i < to_pack.nr_objects; i++) { objects[i].tagged = 0; objects[i].filled = 0; objects[i].delta_child = NULL; objects[i].delta_sibling = NULL; } /* * Fully connect delta_child/delta_sibling network. * Make sure delta_sibling is sorted in the original * recency order. */ for (i = to_pack.nr_objects; i > 0;) { struct object_entry *e = &objects[--i]; if (!e->delta) continue; /* Mark me as the first child */ e->delta_sibling = e->delta->delta_child; e->delta->delta_child = e; } /* * Mark objects that are at the tip of tags. */ for_each_tag_ref(mark_tagged, NULL); /* * Give the objects in the original recency order until * we see a tagged tip. */ for (i = wo_end = 0; i < to_pack.nr_objects; i++) { if (objects[i].tagged) break; add_to_write_order(wo, &wo_end, &objects[i]); } last_untagged = i; /* * Then fill all the tagged tips. */ for (; i < to_pack.nr_objects; i++) { if (objects[i].tagged) add_to_write_order(wo, &wo_end, &objects[i]); } /* * And then all remaining commits and tags. */ for (i = last_untagged; i < to_pack.nr_objects; i++) { if (objects[i].type != OBJ_COMMIT && objects[i].type != OBJ_TAG) continue; add_to_write_order(wo, &wo_end, &objects[i]); } /* * And then all the trees. */ for (i = last_untagged; i < to_pack.nr_objects; i++) { if (objects[i].type != OBJ_TREE) continue; add_to_write_order(wo, &wo_end, &objects[i]); } /* * Finally all the rest in really tight order */ for (i = last_untagged; i < to_pack.nr_objects; i++) { if (!objects[i].filled) add_family_to_write_order(wo, &wo_end, &objects[i]); } if (wo_end != to_pack.nr_objects) die("ordered %u objects, expected %"PRIu32, wo_end, to_pack.nr_objects); return wo; } static off_t write_reused_pack(struct sha1file *f) { unsigned char buffer[8192]; off_t to_write, total; int fd; if (!is_pack_valid(reuse_packfile)) die("packfile is invalid: %s", reuse_packfile->pack_name); fd = git_open_noatime(reuse_packfile->pack_name); if (fd < 0) die_errno("unable to open packfile for reuse: %s", reuse_packfile->pack_name); if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1) die_errno("unable to seek in reused packfile"); if (reuse_packfile_offset < 0) reuse_packfile_offset = reuse_packfile->pack_size - 20; total = to_write = reuse_packfile_offset - sizeof(struct pack_header); while (to_write) { int read_pack = xread(fd, buffer, sizeof(buffer)); if (read_pack <= 0) die_errno("unable to read from reused packfile"); if (read_pack > to_write) read_pack = to_write; sha1write(f, buffer, read_pack); to_write -= read_pack; /* * We don't know the actual number of objects written, * only how many bytes written, how many bytes total, and * how many objects total. So we can fake it by pretending all * objects we are writing are the same size. This gives us a * smooth progress meter, and at the end it matches the true * answer. */ written = reuse_packfile_objects * (((double)(total - to_write)) / total); display_progress(progress_state, written); } close(fd); written = reuse_packfile_objects; display_progress(progress_state, written); return reuse_packfile_offset - sizeof(struct pack_header); } static void write_pack_file(void) { uint32_t i = 0, j; struct sha1file *f; off_t offset; uint32_t nr_remaining = nr_result; time_t last_mtime = 0; struct object_entry **write_order; if (progress > pack_to_stdout) progress_state = start_progress(_("Writing objects"), nr_result); written_list = xmalloc(to_pack.nr_objects * sizeof(*written_list)); write_order = compute_write_order(); do { unsigned char sha1[20]; char *pack_tmp_name = NULL; if (pack_to_stdout) f = sha1fd_throughput(1, "<stdout>", progress_state); else f = create_tmp_packfile(&pack_tmp_name); offset = write_pack_header(f, nr_remaining); if (reuse_packfile) { off_t packfile_size; assert(pack_to_stdout); packfile_size = write_reused_pack(f); offset += packfile_size; } nr_written = 0; for (; i < to_pack.nr_objects; i++) { struct object_entry *e = write_order[i]; if (write_one(f, e, &offset) == WRITE_ONE_BREAK) break; display_progress(progress_state, written); } /* * Did we write the wrong # entries in the header? * If so, rewrite it like in fast-import */ if (pack_to_stdout) { sha1close(f, sha1, CSUM_CLOSE); } else if (nr_written == nr_remaining) { sha1close(f, sha1, CSUM_FSYNC); } else { int fd = sha1close(f, sha1, 0); fixup_pack_header_footer(fd, sha1, pack_tmp_name, nr_written, sha1, offset); close(fd); write_bitmap_index = 0; } if (!pack_to_stdout) { struct stat st; struct strbuf tmpname = STRBUF_INIT; /* * Packs are runtime accessed in their mtime * order since newer packs are more likely to contain * younger objects. So if we are creating multiple * packs then we should modify the mtime of later ones * to preserve this property. */ if (stat(pack_tmp_name, &st) < 0) { warning("failed to stat %s: %s", pack_tmp_name, strerror(errno)); } else if (!last_mtime) { last_mtime = st.st_mtime; } else { struct utimbuf utb; utb.actime = st.st_atime; utb.modtime = --last_mtime; if (utime(pack_tmp_name, &utb) < 0) warning("failed utime() on %s: %s", pack_tmp_name, strerror(errno)); } strbuf_addf(&tmpname, "%s-", base_name); if (write_bitmap_index) { bitmap_writer_set_checksum(sha1); bitmap_writer_build_type_index(written_list, nr_written); } finish_tmp_packfile(&tmpname, pack_tmp_name, written_list, nr_written, &pack_idx_opts, sha1); if (write_bitmap_index) { strbuf_addf(&tmpname, "%s.bitmap", sha1_to_hex(sha1)); stop_progress(&progress_state); bitmap_writer_show_progress(progress); bitmap_writer_reuse_bitmaps(&to_pack); bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1); bitmap_writer_build(&to_pack); bitmap_writer_finish(written_list, nr_written, tmpname.buf, write_bitmap_options); write_bitmap_index = 0; } strbuf_release(&tmpname); free(pack_tmp_name); puts(sha1_to_hex(sha1)); } /* mark written objects as written to previous pack */ for (j = 0; j < nr_written; j++) { written_list[j]->offset = (off_t)-1; } nr_remaining -= nr_written; } while (nr_remaining && i < to_pack.nr_objects); free(written_list); free(write_order); stop_progress(&progress_state); if (written != nr_result) die("wrote %"PRIu32" objects while expecting %"PRIu32, written, nr_result); } static void setup_delta_attr_check(struct git_attr_check *check) { static struct git_attr *attr_delta; if (!attr_delta) attr_delta = git_attr("delta"); check[0].attr = attr_delta; } static int no_try_delta(const char *path) { struct git_attr_check check[1]; setup_delta_attr_check(check); if (git_check_attr(path, ARRAY_SIZE(check), check)) return 0; if (ATTR_FALSE(check->value)) return 1; return 0; } /* * When adding an object, check whether we have already added it * to our packing list. If so, we can skip. However, if we are * being asked to excludei t, but the previous mention was to include * it, make sure to adjust its flags and tweak our numbers accordingly. * * As an optimization, we pass out the index position where we would have * found the item, since that saves us from having to look it up again a * few lines later when we want to add the new entry. */ static int have_duplicate_entry(const unsigned char *sha1, int exclude, uint32_t *index_pos) { struct object_entry *entry; entry = packlist_find(&to_pack, sha1, index_pos); if (!entry) return 0; if (exclude) { if (!entry->preferred_base) nr_result--; entry->preferred_base = 1; } return 1; } /* * Check whether we want the object in the pack (e.g., we do not want * objects found in non-local stores if the "--local" option was used). * * As a side effect of this check, we will find the packed version of this * object, if any. We therefore pass out the pack information to avoid having * to look it up again later. */ static int want_object_in_pack(const unsigned char *sha1, int exclude, struct packed_git **found_pack, off_t *found_offset) { struct packed_git *p; if (!exclude && local && has_loose_object_nonlocal(sha1)) return 0; *found_pack = NULL; *found_offset = 0; for (p = packed_git; p; p = p->next) { off_t offset = find_pack_entry_one(sha1, p); if (offset) { if (!*found_pack) { if (!is_pack_valid(p)) continue; *found_offset = offset; *found_pack = p; } if (exclude) return 1; if (incremental) return 0; if (local && !p->pack_local) return 0; if (ignore_packed_keep && p->pack_local && p->pack_keep) return 0; } } return 1; } static void create_object_entry(const unsigned char *sha1, enum object_type type, uint32_t hash, int exclude, int no_try_delta, uint32_t index_pos, struct packed_git *found_pack, off_t found_offset) { struct object_entry *entry; entry = packlist_alloc(&to_pack, sha1, index_pos); entry->hash = hash; if (type) entry->type = type; if (exclude) entry->preferred_base = 1; else nr_result++; if (found_pack) { entry->in_pack = found_pack; entry->in_pack_offset = found_offset; } entry->no_try_delta = no_try_delta; } static const char no_closure_warning[] = N_( "disabling bitmap writing, as some objects are not being packed" ); static int add_object_entry(const unsigned char *sha1, enum object_type type, const char *name, int exclude) { struct packed_git *found_pack; off_t found_offset; uint32_t index_pos; if (have_duplicate_entry(sha1, exclude, &index_pos)) return 0; if (!want_object_in_pack(sha1, exclude, &found_pack, &found_offset)) { /* The pack is missing an object, so it will not have closure */ if (write_bitmap_index) { warning(_(no_closure_warning)); write_bitmap_index = 0; } return 0; } create_object_entry(sha1, type, pack_name_hash(name), exclude, name && no_try_delta(name), index_pos, found_pack, found_offset); display_progress(progress_state, nr_result); return 1; } static int add_object_entry_from_bitmap(const unsigned char *sha1, enum object_type type, int flags, uint32_t name_hash, struct packed_git *pack, off_t offset) { uint32_t index_pos; if (have_duplicate_entry(sha1, 0, &index_pos)) return 0; create_object_entry(sha1, type, name_hash, 0, 0, index_pos, pack, offset); display_progress(progress_state, nr_result); return 1; } struct pbase_tree_cache { unsigned char sha1[20]; int ref; int temporary; void *tree_data; unsigned long tree_size; }; static struct pbase_tree_cache *(pbase_tree_cache[256]); static int pbase_tree_cache_ix(const unsigned char *sha1) { return sha1[0] % ARRAY_SIZE(pbase_tree_cache); } static int pbase_tree_cache_ix_incr(int ix) { return (ix+1) % ARRAY_SIZE(pbase_tree_cache); } static struct pbase_tree { struct pbase_tree *next; /* This is a phony "cache" entry; we are not * going to evict it or find it through _get() * mechanism -- this is for the toplevel node that * would almost always change with any commit. */ struct pbase_tree_cache pcache; } *pbase_tree; static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1) { struct pbase_tree_cache *ent, *nent; void *data; unsigned long size; enum object_type type; int neigh; int my_ix = pbase_tree_cache_ix(sha1); int available_ix = -1; /* pbase-tree-cache acts as a limited hashtable. * your object will be found at your index or within a few * slots after that slot if it is cached. */ for (neigh = 0; neigh < 8; neigh++) { ent = pbase_tree_cache[my_ix]; if (ent && !hashcmp(ent->sha1, sha1)) { ent->ref++; return ent; } else if (((available_ix < 0) && (!ent || !ent->ref)) || ((0 <= available_ix) && (!ent && pbase_tree_cache[available_ix]))) available_ix = my_ix; if (!ent) break; my_ix = pbase_tree_cache_ix_incr(my_ix); } /* Did not find one. Either we got a bogus request or * we need to read and perhaps cache. */ data = read_sha1_file(sha1, &type, &size); if (!data) return NULL; if (type != OBJ_TREE) { free(data); return NULL; } /* We need to either cache or return a throwaway copy */ if (available_ix < 0) ent = NULL; else { ent = pbase_tree_cache[available_ix]; my_ix = available_ix; } if (!ent) { nent = xmalloc(sizeof(*nent)); nent->temporary = (available_ix < 0); } else { /* evict and reuse */ free(ent->tree_data); nent = ent; } hashcpy(nent->sha1, sha1); nent->tree_data = data; nent->tree_size = size; nent->ref = 1; if (!nent->temporary) pbase_tree_cache[my_ix] = nent; return nent; } static void pbase_tree_put(struct pbase_tree_cache *cache) { if (!cache->temporary) { cache->ref--; return; } free(cache->tree_data); free(cache); } static int name_cmp_len(const char *name) { int i; for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++) ; return i; } static void add_pbase_object(struct tree_desc *tree, const char *name, int cmplen, const char *fullname) { struct name_entry entry; int cmp; while (tree_entry(tree,&entry)) { if (S_ISGITLINK(entry.mode)) continue; cmp = tree_entry_len(&entry) != cmplen ? 1 : memcmp(name, entry.path, cmplen); if (cmp > 0) continue; if (cmp < 0) return; if (name[cmplen] != '/') { add_object_entry(entry.sha1, object_type(entry.mode), fullname, 1); return; } if (S_ISDIR(entry.mode)) { struct tree_desc sub; struct pbase_tree_cache *tree; const char *down = name+cmplen+1; int downlen = name_cmp_len(down); tree = pbase_tree_get(entry.sha1); if (!tree) return; init_tree_desc(&sub, tree->tree_data, tree->tree_size); add_pbase_object(&sub, down, downlen, fullname); pbase_tree_put(tree); } } } static unsigned *done_pbase_paths; static int done_pbase_paths_num; static int done_pbase_paths_alloc; static int done_pbase_path_pos(unsigned hash) { int lo = 0; int hi = done_pbase_paths_num; while (lo < hi) { int mi = (hi + lo) / 2; if (done_pbase_paths[mi] == hash) return mi; if (done_pbase_paths[mi] < hash) hi = mi; else lo = mi + 1; } return -lo-1; } static int check_pbase_path(unsigned hash) { int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash); if (0 <= pos) return 1; pos = -pos - 1; ALLOC_GROW(done_pbase_paths, done_pbase_paths_num + 1, done_pbase_paths_alloc); done_pbase_paths_num++; if (pos < done_pbase_paths_num) memmove(done_pbase_paths + pos + 1, done_pbase_paths + pos, (done_pbase_paths_num - pos - 1) * sizeof(unsigned)); done_pbase_paths[pos] = hash; return 0; } static void add_preferred_base_object(const char *name) { struct pbase_tree *it; int cmplen; unsigned hash = pack_name_hash(name); if (!num_preferred_base || check_pbase_path(hash)) return; cmplen = name_cmp_len(name); for (it = pbase_tree; it; it = it->next) { if (cmplen == 0) { add_object_entry(it->pcache.sha1, OBJ_TREE, NULL, 1); } else { struct tree_desc tree; init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size); add_pbase_object(&tree, name, cmplen, name); } } } static void add_preferred_base(unsigned char *sha1) { struct pbase_tree *it; void *data; unsigned long size; unsigned char tree_sha1[20]; if (window <= num_preferred_base++) return; data = read_object_with_reference(sha1, tree_type, &size, tree_sha1); if (!data) return; for (it = pbase_tree; it; it = it->next) { if (!hashcmp(it->pcache.sha1, tree_sha1)) { free(data); return; } } it = xcalloc(1, sizeof(*it)); it->next = pbase_tree; pbase_tree = it; hashcpy(it->pcache.sha1, tree_sha1); it->pcache.tree_data = data; it->pcache.tree_size = size; } static void cleanup_preferred_base(void) { struct pbase_tree *it; unsigned i; it = pbase_tree; pbase_tree = NULL; while (it) { struct pbase_tree *this = it; it = this->next; free(this->pcache.tree_data); free(this); } for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) { if (!pbase_tree_cache[i]) continue; free(pbase_tree_cache[i]->tree_data); free(pbase_tree_cache[i]); pbase_tree_cache[i] = NULL; } free(done_pbase_paths); done_pbase_paths = NULL; done_pbase_paths_num = done_pbase_paths_alloc = 0; } static void check_object(struct object_entry *entry) { if (entry->in_pack) { struct packed_git *p = entry->in_pack; struct pack_window *w_curs = NULL; const unsigned char *base_ref = NULL; struct object_entry *base_entry; unsigned long used, used_0; unsigned long avail; off_t ofs; unsigned char *buf, c; buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail); /* * We want in_pack_type even if we do not reuse delta * since non-delta representations could still be reused. */ used = unpack_object_header_buffer(buf, avail, &entry->in_pack_type, &entry->size); if (used == 0) goto give_up; /* * Determine if this is a delta and if so whether we can * reuse it or not. Otherwise let's find out as cheaply as * possible what the actual type and size for this object is. */ switch (entry->in_pack_type) { default: /* Not a delta hence we've already got all we need. */ entry->type = entry->in_pack_type; entry->in_pack_header_size = used; if (entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB) goto give_up; unuse_pack(&w_curs); return; case OBJ_REF_DELTA: if (reuse_delta && !entry->preferred_base) base_ref = use_pack(p, &w_curs, entry->in_pack_offset + used, NULL); entry->in_pack_header_size = used + 20; break; case OBJ_OFS_DELTA: buf = use_pack(p, &w_curs, entry->in_pack_offset + used, NULL); used_0 = 0; c = buf[used_0++]; ofs = c & 127; while (c & 128) { ofs += 1; if (!ofs || MSB(ofs, 7)) { error("delta base offset overflow in pack for %s", sha1_to_hex(entry->idx.sha1)); goto give_up; } c = buf[used_0++]; ofs = (ofs << 7) + (c & 127); } ofs = entry->in_pack_offset - ofs; if (ofs <= 0 || ofs >= entry->in_pack_offset) { error("delta base offset out of bound for %s", sha1_to_hex(entry->idx.sha1)); goto give_up; } if (reuse_delta && !entry->preferred_base) { struct revindex_entry *revidx; revidx = find_pack_revindex(p, ofs); if (!revidx) goto give_up; base_ref = nth_packed_object_sha1(p, revidx->nr); } entry->in_pack_header_size = used + used_0; break; } if (base_ref && (base_entry = packlist_find(&to_pack, base_ref, NULL))) { /* * If base_ref was set above that means we wish to * reuse delta data, and we even found that base * in the list of objects we want to pack. Goodie! * * Depth value does not matter - find_deltas() will * never consider reused delta as the base object to * deltify other objects against, in order to avoid * circular deltas. */ entry->type = entry->in_pack_type; entry->delta = base_entry; entry->delta_size = entry->size; entry->delta_sibling = base_entry->delta_child; base_entry->delta_child = entry; unuse_pack(&w_curs); return; } if (entry->type) { /* * This must be a delta and we already know what the * final object type is. Let's extract the actual * object size from the delta header. */ entry->size = get_size_from_delta(p, &w_curs, entry->in_pack_offset + entry->in_pack_header_size); if (entry->size == 0) goto give_up; unuse_pack(&w_curs); return; } /* * No choice but to fall back to the recursive delta walk * with sha1_object_info() to find about the object type * at this point... */ give_up: unuse_pack(&w_curs); } entry->type = sha1_object_info(entry->idx.sha1, &entry->size); /* * The error condition is checked in prepare_pack(). This is * to permit a missing preferred base object to be ignored * as a preferred base. Doing so can result in a larger * pack file, but the transfer will still take place. */ } static int pack_offset_sort(const void *_a, const void *_b) { const struct object_entry *a = *(struct object_entry **)_a; const struct object_entry *b = *(struct object_entry **)_b; /* avoid filesystem trashing with loose objects */ if (!a->in_pack && !b->in_pack) return hashcmp(a->idx.sha1, b->idx.sha1); if (a->in_pack < b->in_pack) return -1; if (a->in_pack > b->in_pack) return 1; return a->in_pack_offset < b->in_pack_offset ? -1 : (a->in_pack_offset > b->in_pack_offset); } static void get_object_details(void) { uint32_t i; struct object_entry **sorted_by_offset; sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *)); for (i = 0; i < to_pack.nr_objects; i++) sorted_by_offset[i] = to_pack.objects + i; qsort(sorted_by_offset, to_pack.nr_objects, sizeof(*sorted_by_offset), pack_offset_sort); for (i = 0; i < to_pack.nr_objects; i++) { struct object_entry *entry = sorted_by_offset[i]; check_object(entry); if (big_file_threshold < entry->size) entry->no_try_delta = 1; } free(sorted_by_offset); } /* * We search for deltas in a list sorted by type, by filename hash, and then * by size, so that we see progressively smaller and smaller files. * That's because we prefer deltas to be from the bigger file * to the smaller -- deletes are potentially cheaper, but perhaps * more importantly, the bigger file is likely the more recent * one. The deepest deltas are therefore the oldest objects which are * less susceptible to be accessed often. */ static int type_size_sort(const void *_a, const void *_b) { const struct object_entry *a = *(struct object_entry **)_a; const struct object_entry *b = *(struct object_entry **)_b; if (a->type > b->type) return -1; if (a->type < b->type) return 1; if (a->hash > b->hash) return -1; if (a->hash < b->hash) return 1; if (a->preferred_base > b->preferred_base) return -1; if (a->preferred_base < b->preferred_base) return 1; if (a->size > b->size) return -1; if (a->size < b->size) return 1; return a < b ? -1 : (a > b); /* newest first */ } struct unpacked { struct object_entry *entry; void *data; struct delta_index *index; unsigned depth; }; static int delta_cacheable(unsigned long src_size, unsigned long trg_size, unsigned long delta_size) { if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size) return 0; if (delta_size < cache_max_small_delta_size) return 1; /* cache delta, if objects are large enough compared to delta size */ if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10)) return 1; return 0; } #ifndef NO_PTHREADS static pthread_mutex_t read_mutex; #define read_lock() pthread_mutex_lock(&read_mutex) #define read_unlock() pthread_mutex_unlock(&read_mutex) static pthread_mutex_t cache_mutex; #define cache_lock() pthread_mutex_lock(&cache_mutex) #define cache_unlock() pthread_mutex_unlock(&cache_mutex) static pthread_mutex_t progress_mutex; #define progress_lock() pthread_mutex_lock(&progress_mutex) #define progress_unlock() pthread_mutex_unlock(&progress_mutex) #else #define read_lock() (void)0 #define read_unlock() (void)0 #define cache_lock() (void)0 #define cache_unlock() (void)0 #define progress_lock() (void)0 #define progress_unlock() (void)0 #endif static int try_delta(struct unpacked *trg, struct unpacked *src, unsigned max_depth, unsigned long *mem_usage) { struct object_entry *trg_entry = trg->entry; struct object_entry *src_entry = src->entry; unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz; unsigned ref_depth; enum object_type type; void *delta_buf; /* Don't bother doing diffs between different types */ if (trg_entry->type != src_entry->type) return -1; /* * We do not bother to try a delta that we discarded on an * earlier try, but only when reusing delta data. Note that * src_entry that is marked as the preferred_base should always * be considered, as even if we produce a suboptimal delta against * it, we will still save the transfer cost, as we already know * the other side has it and we won't send src_entry at all. */ if (reuse_delta && trg_entry->in_pack && trg_entry->in_pack == src_entry->in_pack && !src_entry->preferred_base && trg_entry->in_pack_type != OBJ_REF_DELTA && trg_entry->in_pack_type != OBJ_OFS_DELTA) return 0; /* Let's not bust the allowed depth. */ if (src->depth >= max_depth) return 0; /* Now some size filtering heuristics. */ trg_size = trg_entry->size; if (!trg_entry->delta) { max_size = trg_size/2 - 20; ref_depth = 1; } else { max_size = trg_entry->delta_size; ref_depth = trg->depth; } max_size = (uint64_t)max_size * (max_depth - src->depth) / (max_depth - ref_depth + 1); if (max_size == 0) return 0; src_size = src_entry->size; sizediff = src_size < trg_size ? trg_size - src_size : 0; if (sizediff >= max_size) return 0; if (trg_size < src_size / 32) return 0; /* Load data if not already done */ if (!trg->data) { read_lock(); trg->data = read_sha1_file(trg_entry->idx.sha1, &type, &sz); read_unlock(); if (!trg->data) die("object %s cannot be read", sha1_to_hex(trg_entry->idx.sha1)); if (sz != trg_size) die("object %s inconsistent object length (%lu vs %lu)", sha1_to_hex(trg_entry->idx.sha1), sz, trg_size); *mem_usage += sz; } if (!src->data) { read_lock(); src->data = read_sha1_file(src_entry->idx.sha1, &type, &sz); read_unlock(); if (!src->data) { if (src_entry->preferred_base) { static int warned = 0; if (!warned++) warning("object %s cannot be read", sha1_to_hex(src_entry->idx.sha1)); /* * Those objects are not included in the * resulting pack. Be resilient and ignore * them if they can't be read, in case the * pack could be created nevertheless. */ return 0; } die("object %s cannot be read", sha1_to_hex(src_entry->idx.sha1)); } if (sz != src_size) die("object %s inconsistent object length (%lu vs %lu)", sha1_to_hex(src_entry->idx.sha1), sz, src_size); *mem_usage += sz; } if (!src->index) { src->index = create_delta_index(src->data, src_size); if (!src->index) { static int warned = 0; if (!warned++) warning("suboptimal pack - out of memory"); return 0; } *mem_usage += sizeof_delta_index(src->index); } delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size); if (!delta_buf) return 0; if (trg_entry->delta) { /* Prefer only shallower same-sized deltas. */ if (delta_size == trg_entry->delta_size && src->depth + 1 >= trg->depth) { free(delta_buf); return 0; } } /* * Handle memory allocation outside of the cache * accounting lock. Compiler will optimize the strangeness * away when NO_PTHREADS is defined. */ free(trg_entry->delta_data); cache_lock(); if (trg_entry->delta_data) { delta_cache_size -= trg_entry->delta_size; trg_entry->delta_data = NULL; } if (delta_cacheable(src_size, trg_size, delta_size)) { delta_cache_size += delta_size; cache_unlock(); trg_entry->delta_data = xrealloc(delta_buf, delta_size); } else { cache_unlock(); free(delta_buf); } trg_entry->delta = src_entry; trg_entry->delta_size = delta_size; trg->depth = src->depth + 1; return 1; } static unsigned int check_delta_limit(struct object_entry *me, unsigned int n) { struct object_entry *child = me->delta_child; unsigned int m = n; while (child) { unsigned int c = check_delta_limit(child, n + 1); if (m < c) m = c; child = child->delta_sibling; } return m; } static unsigned long free_unpacked(struct unpacked *n) { unsigned long freed_mem = sizeof_delta_index(n->index); free_delta_index(n->index); n->index = NULL; if (n->data) { freed_mem += n->entry->size; free(n->data); n->data = NULL; } n->entry = NULL; n->depth = 0; return freed_mem; } static void find_deltas(struct object_entry **list, unsigned *list_size, int window, int depth, unsigned *processed) { uint32_t i, idx = 0, count = 0; struct unpacked *array; unsigned long mem_usage = 0; array = xcalloc(window, sizeof(struct unpacked)); for (;;) { struct object_entry *entry; struct unpacked *n = array + idx; int j, max_depth, best_base = -1; progress_lock(); if (!*list_size) { progress_unlock(); break; } entry = *list++; (*list_size)--; if (!entry->preferred_base) { (*processed)++; display_progress(progress_state, *processed); } progress_unlock(); mem_usage -= free_unpacked(n); n->entry = entry; while (window_memory_limit && mem_usage > window_memory_limit && count > 1) { uint32_t tail = (idx + window - count) % window; mem_usage -= free_unpacked(array + tail); count--; } /* We do not compute delta to *create* objects we are not * going to pack. */ if (entry->preferred_base) goto next; /* * If the current object is at pack edge, take the depth the * objects that depend on the current object into account * otherwise they would become too deep. */ max_depth = depth; if (entry->delta_child) { max_depth -= check_delta_limit(entry, 0); if (max_depth <= 0) goto next; } j = window; while (--j > 0) { int ret; uint32_t other_idx = idx + j; struct unpacked *m; if (other_idx >= window) other_idx -= window; m = array + other_idx; if (!m->entry) break; ret = try_delta(n, m, max_depth, &mem_usage); if (ret < 0) break; else if (ret > 0) best_base = other_idx; } /* * If we decided to cache the delta data, then it is best * to compress it right away. First because we have to do * it anyway, and doing it here while we're threaded will * save a lot of time in the non threaded write phase, * as well as allow for caching more deltas within * the same cache size limit. * ... * But only if not writing to stdout, since in that case * the network is most likely throttling writes anyway, * and therefore it is best to go to the write phase ASAP * instead, as we can afford spending more time compressing * between writes at that moment. */ if (entry->delta_data && !pack_to_stdout) { entry->z_delta_size = do_compress(&entry->delta_data, entry->delta_size); cache_lock(); delta_cache_size -= entry->delta_size; delta_cache_size += entry->z_delta_size; cache_unlock(); } /* if we made n a delta, and if n is already at max * depth, leaving it in the window is pointless. we * should evict it first. */ if (entry->delta && max_depth <= n->depth) continue; /* * Move the best delta base up in the window, after the * currently deltified object, to keep it longer. It will * be the first base object to be attempted next. */ if (entry->delta) { struct unpacked swap = array[best_base]; int dist = (window + idx - best_base) % window; int dst = best_base; while (dist--) { int src = (dst + 1) % window; array[dst] = array[src]; dst = src; } array[dst] = swap; } next: idx++; if (count + 1 < window) count++; if (idx >= window) idx = 0; } for (i = 0; i < window; ++i) { free_delta_index(array[i].index); free(array[i].data); } free(array); } #ifndef NO_PTHREADS static void try_to_free_from_threads(size_t size) { read_lock(); release_pack_memory(size); read_unlock(); } static try_to_free_t old_try_to_free_routine; /* * The main thread waits on the condition that (at least) one of the workers * has stopped working (which is indicated in the .working member of * struct thread_params). * When a work thread has completed its work, it sets .working to 0 and * signals the main thread and waits on the condition that .data_ready * becomes 1. */ struct thread_params { pthread_t thread; struct object_entry **list; unsigned list_size; unsigned remaining; int window; int depth; int working; int data_ready; pthread_mutex_t mutex; pthread_cond_t cond; unsigned *processed; }; static pthread_cond_t progress_cond; /* * Mutex and conditional variable can't be statically-initialized on Windows. */ static void init_threaded_search(void) { init_recursive_mutex(&read_mutex); pthread_mutex_init(&cache_mutex, NULL); pthread_mutex_init(&progress_mutex, NULL); pthread_cond_init(&progress_cond, NULL); old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads); } static void cleanup_threaded_search(void) { set_try_to_free_routine(old_try_to_free_routine); pthread_cond_destroy(&progress_cond); pthread_mutex_destroy(&read_mutex); pthread_mutex_destroy(&cache_mutex); pthread_mutex_destroy(&progress_mutex); } static void *threaded_find_deltas(void *arg) { struct thread_params *me = arg; while (me->remaining) { find_deltas(me->list, &me->remaining, me->window, me->depth, me->processed); progress_lock(); me->working = 0; pthread_cond_signal(&progress_cond); progress_unlock(); /* * We must not set ->data_ready before we wait on the * condition because the main thread may have set it to 1 * before we get here. In order to be sure that new * work is available if we see 1 in ->data_ready, it * was initialized to 0 before this thread was spawned * and we reset it to 0 right away. */ pthread_mutex_lock(&me->mutex); while (!me->data_ready) pthread_cond_wait(&me->cond, &me->mutex); me->data_ready = 0; pthread_mutex_unlock(&me->mutex); } /* leave ->working 1 so that this doesn't get more work assigned */ return NULL; } static void ll_find_deltas(struct object_entry **list, unsigned list_size, int window, int depth, unsigned *processed) { struct thread_params *p; int i, ret, active_threads = 0; init_threaded_search(); if (delta_search_threads <= 1) { find_deltas(list, &list_size, window, depth, processed); cleanup_threaded_search(); return; } if (progress > pack_to_stdout) fprintf(stderr, "Delta compression using up to %d threads.\n", delta_search_threads); p = xcalloc(delta_search_threads, sizeof(*p)); /* Partition the work amongst work threads. */ for (i = 0; i < delta_search_threads; i++) { unsigned sub_size = list_size / (delta_search_threads - i); /* don't use too small segments or no deltas will be found */ if (sub_size < 2*window && i+1 < delta_search_threads) sub_size = 0; p[i].window = window; p[i].depth = depth; p[i].processed = processed; p[i].working = 1; p[i].data_ready = 0; /* try to split chunks on "path" boundaries */ while (sub_size && sub_size < list_size && list[sub_size]->hash && list[sub_size]->hash == list[sub_size-1]->hash) sub_size++; p[i].list = list; p[i].list_size = sub_size; p[i].remaining = sub_size; list += sub_size; list_size -= sub_size; } /* Start work threads. */ for (i = 0; i < delta_search_threads; i++) { if (!p[i].list_size) continue; pthread_mutex_init(&p[i].mutex, NULL); pthread_cond_init(&p[i].cond, NULL); ret = pthread_create(&p[i].thread, NULL, threaded_find_deltas, &p[i]); if (ret) die("unable to create thread: %s", strerror(ret)); active_threads++; } /* * Now let's wait for work completion. Each time a thread is done * with its work, we steal half of the remaining work from the * thread with the largest number of unprocessed objects and give * it to that newly idle thread. This ensure good load balancing * until the remaining object list segments are simply too short * to be worth splitting anymore. */ while (active_threads) { struct thread_params *target = NULL; struct thread_params *victim = NULL; unsigned sub_size = 0; progress_lock(); for (;;) { for (i = 0; !target && i < delta_search_threads; i++) if (!p[i].working) target = &p[i]; if (target) break; pthread_cond_wait(&progress_cond, &progress_mutex); } for (i = 0; i < delta_search_threads; i++) if (p[i].remaining > 2*window && (!victim || victim->remaining < p[i].remaining)) victim = &p[i]; if (victim) { sub_size = victim->remaining / 2; list = victim->list + victim->list_size - sub_size; while (sub_size && list[0]->hash && list[0]->hash == list[-1]->hash) { list++; sub_size--; } if (!sub_size) { /* * It is possible for some "paths" to have * so many objects that no hash boundary * might be found. Let's just steal the * exact half in that case. */ sub_size = victim->remaining / 2; list -= sub_size; } target->list = list; victim->list_size -= sub_size; victim->remaining -= sub_size; } target->list_size = sub_size; target->remaining = sub_size; target->working = 1; progress_unlock(); pthread_mutex_lock(&target->mutex); target->data_ready = 1; pthread_cond_signal(&target->cond); pthread_mutex_unlock(&target->mutex); if (!sub_size) { pthread_join(target->thread, NULL); pthread_cond_destroy(&target->cond); pthread_mutex_destroy(&target->mutex); active_threads--; } } cleanup_threaded_search(); free(p); } #else #define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p) #endif static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data) { struct object_id peeled; if (starts_with(path, "refs/tags/") && /* is a tag? */ !peel_ref(path, peeled.hash) && /* peelable? */ packlist_find(&to_pack, peeled.hash, NULL)) /* object packed? */ add_object_entry(oid->hash, OBJ_TAG, NULL, 0); return 0; } static void prepare_pack(int window, int depth) { struct object_entry **delta_list; uint32_t i, nr_deltas; unsigned n; get_object_details(); /* * If we're locally repacking then we need to be doubly careful * from now on in order to make sure no stealth corruption gets * propagated to the new pack. Clients receiving streamed packs * should validate everything they get anyway so no need to incur * the additional cost here in that case. */ if (!pack_to_stdout) do_check_packed_object_crc = 1; if (!to_pack.nr_objects || !window || !depth) return; delta_list = xmalloc(to_pack.nr_objects * sizeof(*delta_list)); nr_deltas = n = 0; for (i = 0; i < to_pack.nr_objects; i++) { struct object_entry *entry = to_pack.objects + i; if (entry->delta) /* This happens if we decided to reuse existing * delta from a pack. "reuse_delta &&" is implied. */ continue; if (entry->size < 50) continue; if (entry->no_try_delta) continue; if (!entry->preferred_base) { nr_deltas++; if (entry->type < 0) die("unable to get type of object %s", sha1_to_hex(entry->idx.sha1)); } else { if (entry->type < 0) { /* * This object is not found, but we * don't have to include it anyway. */ continue; } } delta_list[n++] = entry; } if (nr_deltas && n > 1) { unsigned nr_done = 0; if (progress) progress_state = start_progress(_("Compressing objects"), nr_deltas); qsort(delta_list, n, sizeof(*delta_list), type_size_sort); ll_find_deltas(delta_list, n, window+1, depth, &nr_done); stop_progress(&progress_state); if (nr_done != nr_deltas) die("inconsistency with delta count"); } free(delta_list); } static int git_pack_config(const char *k, const char *v, void *cb) { if (!strcmp(k, "pack.window")) { window = git_config_int(k, v); return 0; } if (!strcmp(k, "pack.windowmemory")) { window_memory_limit = git_config_ulong(k, v); return 0; } if (!strcmp(k, "pack.depth")) { depth = git_config_int(k, v); return 0; } if (!strcmp(k, "pack.compression")) { int level = git_config_int(k, v); if (level == -1) level = Z_DEFAULT_COMPRESSION; else if (level < 0 || level > Z_BEST_COMPRESSION) die("bad pack compression level %d", level); pack_compression_level = level; pack_compression_seen = 1; return 0; } if (!strcmp(k, "pack.deltacachesize")) { max_delta_cache_size = git_config_int(k, v); return 0; } if (!strcmp(k, "pack.deltacachelimit")) { cache_max_small_delta_size = git_config_int(k, v); return 0; } if (!strcmp(k, "pack.writebitmaphashcache")) { if (git_config_bool(k, v)) write_bitmap_options |= BITMAP_OPT_HASH_CACHE; else write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE; } if (!strcmp(k, "pack.usebitmaps")) { use_bitmap_index = git_config_bool(k, v); return 0; } if (!strcmp(k, "pack.threads")) { delta_search_threads = git_config_int(k, v); if (delta_search_threads < 0) die("invalid number of threads specified (%d)", delta_search_threads); #ifdef NO_PTHREADS if (delta_search_threads != 1) warning("no threads support, ignoring %s", k); #endif return 0; } if (!strcmp(k, "pack.indexversion")) { pack_idx_opts.version = git_config_int(k, v); if (pack_idx_opts.version > 2) die("bad pack.indexversion=%"PRIu32, pack_idx_opts.version); return 0; } return git_default_config(k, v, cb); } static void read_object_list_from_stdin(void) { char line[40 + 1 + PATH_MAX + 2]; unsigned char sha1[20]; for (;;) { if (!fgets(line, sizeof(line), stdin)) { if (feof(stdin)) break; if (!ferror(stdin)) die("fgets returned NULL, not EOF, not error!"); if (errno != EINTR) die_errno("fgets"); clearerr(stdin); continue; } if (line[0] == '-') { if (get_sha1_hex(line+1, sha1)) die("expected edge sha1, got garbage:\n %s", line); add_preferred_base(sha1); continue; } if (get_sha1_hex(line, sha1)) die("expected sha1, got garbage:\n %s", line); add_preferred_base_object(line+41); add_object_entry(sha1, 0, line+41, 0); } } #define OBJECT_ADDED (1u<<20) static void show_commit(struct commit *commit, void *data) { add_object_entry(commit->object.oid.hash, OBJ_COMMIT, NULL, 0); commit->object.flags |= OBJECT_ADDED; if (write_bitmap_index) index_commit_for_bitmap(commit); } static void show_object(struct object *obj, struct strbuf *path, const char *last, void *data) { char *name = path_name(path, last); add_preferred_base_object(name); add_object_entry(obj->oid.hash, obj->type, name, 0); obj->flags |= OBJECT_ADDED; /* * We will have generated the hash from the name, * but not saved a pointer to it - we can free it */ free((char *)name); } static void show_edge(struct commit *commit) { add_preferred_base(commit->object.oid.hash); } struct in_pack_object { off_t offset; struct object *object; }; struct in_pack { int alloc; int nr; struct in_pack_object *array; }; static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack) { in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p); in_pack->array[in_pack->nr].object = object; in_pack->nr++; } /* * Compare the objects in the offset order, in order to emulate the * "git rev-list --objects" output that produced the pack originally. */ static int ofscmp(const void *a_, const void *b_) { struct in_pack_object *a = (struct in_pack_object *)a_; struct in_pack_object *b = (struct in_pack_object *)b_; if (a->offset < b->offset) return -1; else if (a->offset > b->offset) return 1; else return oidcmp(&a->object->oid, &b->object->oid); } static void add_objects_in_unpacked_packs(struct rev_info *revs) { struct packed_git *p; struct in_pack in_pack; uint32_t i; memset(&in_pack, 0, sizeof(in_pack)); for (p = packed_git; p; p = p->next) { const unsigned char *sha1; struct object *o; if (!p->pack_local || p->pack_keep) continue; if (open_pack_index(p)) die("cannot open pack index"); ALLOC_GROW(in_pack.array, in_pack.nr + p->num_objects, in_pack.alloc); for (i = 0; i < p->num_objects; i++) { sha1 = nth_packed_object_sha1(p, i); o = lookup_unknown_object(sha1); if (!(o->flags & OBJECT_ADDED)) mark_in_pack_object(o, p, &in_pack); o->flags |= OBJECT_ADDED; } } if (in_pack.nr) { qsort(in_pack.array, in_pack.nr, sizeof(in_pack.array[0]), ofscmp); for (i = 0; i < in_pack.nr; i++) { struct object *o = in_pack.array[i].object; add_object_entry(o->oid.hash, o->type, "", 0); } } free(in_pack.array); } static int has_sha1_pack_kept_or_nonlocal(const unsigned char *sha1) { static struct packed_git *last_found = (void *)1; struct packed_git *p; p = (last_found != (void *)1) ? last_found : packed_git; while (p) { if ((!p->pack_local || p->pack_keep) && find_pack_entry_one(sha1, p)) { last_found = p; return 1; } if (p == last_found) p = packed_git; else p = p->next; if (p == last_found) p = p->next; } return 0; } /* * Store a list of sha1s that are should not be discarded * because they are either written too recently, or are * reachable from another object that was. * * This is filled by get_object_list. */ static struct sha1_array recent_objects; static int loosened_object_can_be_discarded(const unsigned char *sha1, unsigned long mtime) { if (!unpack_unreachable_expiration) return 0; if (mtime > unpack_unreachable_expiration) return 0; if (sha1_array_lookup(&recent_objects, sha1) >= 0) return 0; return 1; } static void loosen_unused_packed_objects(struct rev_info *revs) { struct packed_git *p; uint32_t i; const unsigned char *sha1; for (p = packed_git; p; p = p->next) { if (!p->pack_local || p->pack_keep) continue; if (open_pack_index(p)) die("cannot open pack index"); for (i = 0; i < p->num_objects; i++) { sha1 = nth_packed_object_sha1(p, i); if (!packlist_find(&to_pack, sha1, NULL) && !has_sha1_pack_kept_or_nonlocal(sha1) && !loosened_object_can_be_discarded(sha1, p->mtime)) if (force_object_loose(sha1, p->mtime)) die("unable to force loose object"); } } } /* * This tracks any options which a reader of the pack might * not understand, and which would therefore prevent blind reuse * of what we have on disk. */ static int pack_options_allow_reuse(void) { return allow_ofs_delta; } static int get_object_list_from_bitmap(struct rev_info *revs) { if (prepare_bitmap_walk(revs) < 0) return -1; if (pack_options_allow_reuse() && !reuse_partial_packfile_from_bitmap( &reuse_packfile, &reuse_packfile_objects, &reuse_packfile_offset)) { assert(reuse_packfile_objects); nr_result += reuse_packfile_objects; display_progress(progress_state, nr_result); } traverse_bitmap_commit_list(&add_object_entry_from_bitmap); return 0; } static void record_recent_object(struct object *obj, struct strbuf *path, const char *last, void *data) { sha1_array_append(&recent_objects, obj->oid.hash); } static void record_recent_commit(struct commit *commit, void *data) { sha1_array_append(&recent_objects, commit->object.oid.hash); } static void get_object_list(int ac, const char **av) { struct rev_info revs; char line[1000]; int flags = 0; init_revisions(&revs, NULL); save_commit_buffer = 0; setup_revisions(ac, av, &revs, NULL); /* make sure shallows are read */ is_repository_shallow(); while (fgets(line, sizeof(line), stdin) != NULL) { int len = strlen(line); if (len && line[len - 1] == '\n') line[--len] = 0; if (!len) break; if (*line == '-') { if (!strcmp(line, "--not")) { flags ^= UNINTERESTING; write_bitmap_index = 0; continue; } if (starts_with(line, "--shallow ")) { unsigned char sha1[20]; if (get_sha1_hex(line + 10, sha1)) die("not an SHA-1 '%s'", line + 10); register_shallow(sha1); use_bitmap_index = 0; continue; } die("not a rev '%s'", line); } if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME)) die("bad revision '%s'", line); } if (use_bitmap_index && !get_object_list_from_bitmap(&revs)) return; if (prepare_revision_walk(&revs)) die("revision walk setup failed"); mark_edges_uninteresting(&revs, show_edge); traverse_commit_list(&revs, show_commit, show_object, NULL); if (unpack_unreachable_expiration) { revs.ignore_missing_links = 1; if (add_unseen_recent_objects_to_traversal(&revs, unpack_unreachable_expiration)) die("unable to add recent objects"); if (prepare_revision_walk(&revs)) die("revision walk setup failed"); traverse_commit_list(&revs, record_recent_commit, record_recent_object, NULL); } if (keep_unreachable) add_objects_in_unpacked_packs(&revs); if (unpack_unreachable) loosen_unused_packed_objects(&revs); sha1_array_clear(&recent_objects); } static int option_parse_index_version(const struct option *opt, const char *arg, int unset) { char *c; const char *val = arg; pack_idx_opts.version = strtoul(val, &c, 10); if (pack_idx_opts.version > 2) die(_("unsupported index version %s"), val); if (*c == ',' && c[1]) pack_idx_opts.off32_limit = strtoul(c+1, &c, 0); if (*c || pack_idx_opts.off32_limit & 0x80000000) die(_("bad index version '%s'"), val); return 0; } static int option_parse_unpack_unreachable(const struct option *opt, const char *arg, int unset) { if (unset) { unpack_unreachable = 0; unpack_unreachable_expiration = 0; } else { unpack_unreachable = 1; if (arg) unpack_unreachable_expiration = approxidate(arg); } return 0; } int cmd_pack_objects(int argc, const char **argv, const char *prefix) { int use_internal_rev_list = 0; int thin = 0; int shallow = 0; int all_progress_implied = 0; struct argv_array rp = ARGV_ARRAY_INIT; int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0; int rev_list_index = 0; struct option pack_objects_options[] = { OPT_SET_INT('q', "quiet", &progress, N_("do not show progress meter"), 0), OPT_SET_INT(0, "progress", &progress, N_("show progress meter"), 1), OPT_SET_INT(0, "all-progress", &progress, N_("show progress meter during object writing phase"), 2), OPT_BOOL(0, "all-progress-implied", &all_progress_implied, N_("similar to --all-progress when progress meter is shown")), { OPTION_CALLBACK, 0, "index-version", NULL, N_("version[,offset]"), N_("write the pack index file in the specified idx format version"), 0, option_parse_index_version }, OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit, N_("maximum size of each output pack file")), OPT_BOOL(0, "local", &local, N_("ignore borrowed objects from alternate object store")), OPT_BOOL(0, "incremental", &incremental, N_("ignore packed objects")), OPT_INTEGER(0, "window", &window, N_("limit pack window by objects")), OPT_MAGNITUDE(0, "window-memory", &window_memory_limit, N_("limit pack window by memory in addition to object limit")), OPT_INTEGER(0, "depth", &depth, N_("maximum length of delta chain allowed in the resulting pack")), OPT_BOOL(0, "reuse-delta", &reuse_delta, N_("reuse existing deltas")), OPT_BOOL(0, "reuse-object", &reuse_object, N_("reuse existing objects")), OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta, N_("use OFS_DELTA objects")), OPT_INTEGER(0, "threads", &delta_search_threads, N_("use threads when searching for best delta matches")), OPT_BOOL(0, "non-empty", &non_empty, N_("do not create an empty pack output")), OPT_BOOL(0, "revs", &use_internal_rev_list, N_("read revision arguments from standard input")), { OPTION_SET_INT, 0, "unpacked", &rev_list_unpacked, NULL, N_("limit the objects to those that are not yet packed"), PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 }, { OPTION_SET_INT, 0, "all", &rev_list_all, NULL, N_("include objects reachable from any reference"), PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 }, { OPTION_SET_INT, 0, "reflog", &rev_list_reflog, NULL, N_("include objects referred by reflog entries"), PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 }, { OPTION_SET_INT, 0, "indexed-objects", &rev_list_index, NULL, N_("include objects referred to by the index"), PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 }, OPT_BOOL(0, "stdout", &pack_to_stdout, N_("output pack to stdout")), OPT_BOOL(0, "include-tag", &include_tag, N_("include tag objects that refer to objects to be packed")), OPT_BOOL(0, "keep-unreachable", &keep_unreachable, N_("keep unreachable objects")), { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"), N_("unpack unreachable objects newer than <time>"), PARSE_OPT_OPTARG, option_parse_unpack_unreachable }, OPT_BOOL(0, "thin", &thin, N_("create thin packs")), OPT_BOOL(0, "shallow", &shallow, N_("create packs suitable for shallow fetches")), OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep, N_("ignore packs that have companion .keep file")), OPT_INTEGER(0, "compression", &pack_compression_level, N_("pack compression level")), OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents, N_("do not hide commits by grafts"), 0), OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index, N_("use a bitmap index if available to speed up counting objects")), OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index, N_("write a bitmap index together with the pack index")), OPT_END(), }; check_replace_refs = 0; reset_pack_idx_option(&pack_idx_opts); git_config(git_pack_config, NULL); if (!pack_compression_seen && core_compression_seen) pack_compression_level = core_compression_level; progress = isatty(2); argc = parse_options(argc, argv, prefix, pack_objects_options, pack_usage, 0); if (argc) { base_name = argv[0]; argc--; } if (pack_to_stdout != !base_name || argc) usage_with_options(pack_usage, pack_objects_options); argv_array_push(&rp, "pack-objects"); if (thin) { use_internal_rev_list = 1; argv_array_push(&rp, shallow ? "--objects-edge-aggressive" : "--objects-edge"); } else argv_array_push(&rp, "--objects"); if (rev_list_all) { use_internal_rev_list = 1; argv_array_push(&rp, "--all"); } if (rev_list_reflog) { use_internal_rev_list = 1; argv_array_push(&rp, "--reflog"); } if (rev_list_index) { use_internal_rev_list = 1; argv_array_push(&rp, "--indexed-objects"); } if (rev_list_unpacked) { use_internal_rev_list = 1; argv_array_push(&rp, "--unpacked"); } if (!reuse_object) reuse_delta = 0; if (pack_compression_level == -1) pack_compression_level = Z_DEFAULT_COMPRESSION; else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION) die("bad pack compression level %d", pack_compression_level); if (!delta_search_threads) /* --threads=0 means autodetect */ delta_search_threads = online_cpus(); #ifdef NO_PTHREADS if (delta_search_threads != 1) warning("no threads support, ignoring --threads"); #endif if (!pack_to_stdout && !pack_size_limit) pack_size_limit = pack_size_limit_cfg; if (pack_to_stdout && pack_size_limit) die("--max-pack-size cannot be used to build a pack for transfer."); if (pack_size_limit && pack_size_limit < 1024*1024) { warning("minimum pack size limit is 1 MiB"); pack_size_limit = 1024*1024; } if (!pack_to_stdout && thin) die("--thin cannot be used to build an indexable pack."); if (keep_unreachable && unpack_unreachable) die("--keep-unreachable and --unpack-unreachable are incompatible."); if (!rev_list_all || !rev_list_reflog || !rev_list_index) unpack_unreachable_expiration = 0; if (!use_internal_rev_list || !pack_to_stdout || is_repository_shallow()) use_bitmap_index = 0; if (pack_to_stdout || !rev_list_all) write_bitmap_index = 0; if (progress && all_progress_implied) progress = 2; prepare_packed_git(); if (progress) progress_state = start_progress(_("Counting objects"), 0); if (!use_internal_rev_list) read_object_list_from_stdin(); else { get_object_list(rp.argc, rp.argv); argv_array_clear(&rp); } cleanup_preferred_base(); if (include_tag && nr_result) for_each_ref(add_ref_tag, NULL); stop_progress(&progress_state); if (non_empty && !nr_result) return 0; if (nr_result) prepare_pack(window, depth); write_pack_file(); if (progress) fprintf(stderr, "Total %"PRIu32" (delta %"PRIu32")," " reused %"PRIu32" (delta %"PRIu32")\n", written, written_delta, reused, reused_delta); return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4946_0
crossvul-cpp_data_bad_5062_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <assert.h> #include "opj_apps_config.h" #include "openjpeg.h" #include "color.h" #ifdef OPJ_HAVE_LIBLCMS2 #include <lcms2.h> #endif #ifdef OPJ_HAVE_LIBLCMS1 #include <lcms.h> #endif #ifdef OPJ_USE_LEGACY #define OPJ_CLRSPC_GRAY CLRSPC_GRAY #define OPJ_CLRSPC_SRGB CLRSPC_SRGB #endif /*-------------------------------------------------------- Matrix for sYCC, Amendment 1 to IEC 61966-2-1 Y : 0.299 0.587 0.114 :R Cb: -0.1687 -0.3312 0.5 :G Cr: 0.5 -0.4187 -0.0812 :B Inverse: R: 1 -3.68213e-05 1.40199 :Y G: 1.00003 -0.344125 -0.714128 :Cb - 2^(prec - 1) B: 0.999823 1.77204 -8.04142e-06 :Cr - 2^(prec - 1) -----------------------------------------------------------*/ static void sycc_to_rgb(int offset, int upb, int y, int cb, int cr, int *out_r, int *out_g, int *out_b) { int r, g, b; cb -= offset; cr -= offset; r = y + (int)(1.402 * (float)cr); if(r < 0) r = 0; else if(r > upb) r = upb; *out_r = r; g = y - (int)(0.344 * (float)cb + 0.714 * (float)cr); if(g < 0) g = 0; else if(g > upb) g = upb; *out_g = g; b = y + (int)(1.772 * (float)cb); if(b < 0) b = 0; else if(b > upb) b = upb; *out_b = b; } static void sycc444_to_rgb(opj_image_t *img) { int *d0, *d1, *d2, *r, *g, *b; const int *y, *cb, *cr; size_t maxw, maxh, max, i; int offset, upb; upb = (int)img->comps[0].prec; offset = 1<<(upb - 1); upb = (1<<upb)-1; maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h; max = maxw * maxh; y = img->comps[0].data; cb = img->comps[1].data; cr = img->comps[2].data; d0 = r = (int*)malloc(sizeof(int) * max); d1 = g = (int*)malloc(sizeof(int) * max); d2 = b = (int*)malloc(sizeof(int) * max); if(r == NULL || g == NULL || b == NULL) goto fails; for(i = 0U; i < max; ++i) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++cb; ++cr; ++r; ++g; ++b; } free(img->comps[0].data); img->comps[0].data = d0; free(img->comps[1].data); img->comps[1].data = d1; free(img->comps[2].data); img->comps[2].data = d2; img->color_space = OPJ_CLRSPC_SRGB; return; fails: free(r); free(g); free(b); }/* sycc444_to_rgb() */ static void sycc422_to_rgb(opj_image_t *img) { int *d0, *d1, *d2, *r, *g, *b; const int *y, *cb, *cr; size_t maxw, maxh, max, offx, loopmaxw; int offset, upb; size_t i; upb = (int)img->comps[0].prec; offset = 1<<(upb - 1); upb = (1<<upb)-1; maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h; max = maxw * maxh; y = img->comps[0].data; cb = img->comps[1].data; cr = img->comps[2].data; d0 = r = (int*)malloc(sizeof(int) * max); d1 = g = (int*)malloc(sizeof(int) * max); d2 = b = (int*)malloc(sizeof(int) * max); if(r == NULL || g == NULL || b == NULL) goto fails; /* if img->x0 is odd, then first column shall use Cb/Cr = 0 */ offx = img->x0 & 1U; loopmaxw = maxw - offx; for(i=0U; i < maxh; ++i) { size_t j; if (offx > 0U) { sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b); ++y; ++r; ++g; ++b; } for(j=0U; j < (loopmaxw & ~(size_t)1U); j += 2U) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; ++cb; ++cr; } if (j < loopmaxw) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; ++cb; ++cr; } } free(img->comps[0].data); img->comps[0].data = d0; free(img->comps[1].data); img->comps[1].data = d1; free(img->comps[2].data); img->comps[2].data = d2; img->comps[1].w = img->comps[2].w = img->comps[0].w; img->comps[1].h = img->comps[2].h = img->comps[0].h; img->comps[1].dx = img->comps[2].dx = img->comps[0].dx; img->comps[1].dy = img->comps[2].dy = img->comps[0].dy; img->color_space = OPJ_CLRSPC_SRGB; return; fails: free(r); free(g); free(b); }/* sycc422_to_rgb() */ static void sycc420_to_rgb(opj_image_t *img) { int *d0, *d1, *d2, *r, *g, *b, *nr, *ng, *nb; const int *y, *cb, *cr, *ny; size_t maxw, maxh, max, offx, loopmaxw, offy, loopmaxh; int offset, upb; size_t i; upb = (int)img->comps[0].prec; offset = 1<<(upb - 1); upb = (1<<upb)-1; maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h; max = maxw * maxh; y = img->comps[0].data; cb = img->comps[1].data; cr = img->comps[2].data; d0 = r = (int*)malloc(sizeof(int) * max); d1 = g = (int*)malloc(sizeof(int) * max); d2 = b = (int*)malloc(sizeof(int) * max); if (r == NULL || g == NULL || b == NULL) goto fails; /* if img->x0 is odd, then first column shall use Cb/Cr = 0 */ offx = img->x0 & 1U; loopmaxw = maxw - offx; /* if img->y0 is odd, then first line shall use Cb/Cr = 0 */ offy = img->y0 & 1U; loopmaxh = maxh - offy; if (offy > 0U) { size_t j; for(j=0; j < maxw; ++j) { sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b); ++y; ++r; ++g; ++b; } } for(i=0U; i < (loopmaxh & ~(size_t)1U); i += 2U) { size_t j; ny = y + maxw; nr = r + maxw; ng = g + maxw; nb = b + maxw; if (offx > 0U) { sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b); ++y; ++r; ++g; ++b; sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb); ++ny; ++nr; ++ng; ++nb; } for(j=0; j < (loopmaxw & ~(size_t)1U); j += 2U) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb); ++ny; ++nr; ++ng; ++nb; sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb); ++ny; ++nr; ++ng; ++nb; ++cb; ++cr; } if(j < loopmaxw) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb); ++ny; ++nr; ++ng; ++nb; ++cb; ++cr; } y += maxw; r += maxw; g += maxw; b += maxw; } if(i < loopmaxh) { size_t j; for(j=0U; j < (maxw & ~(size_t)1U); j += 2U) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; ++cb; ++cr; } if(j < maxw) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); } } free(img->comps[0].data); img->comps[0].data = d0; free(img->comps[1].data); img->comps[1].data = d1; free(img->comps[2].data); img->comps[2].data = d2; img->comps[1].w = img->comps[2].w = img->comps[0].w; img->comps[1].h = img->comps[2].h = img->comps[0].h; img->comps[1].dx = img->comps[2].dx = img->comps[0].dx; img->comps[1].dy = img->comps[2].dy = img->comps[0].dy; img->color_space = OPJ_CLRSPC_SRGB; return; fails: free(r); free(g); free(b); }/* sycc420_to_rgb() */ void color_sycc_to_rgb(opj_image_t *img) { if(img->numcomps < 3) { img->color_space = OPJ_CLRSPC_GRAY; return; } if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 2) && (img->comps[2].dy == 2))/* horizontal and vertical sub-sample */ { sycc420_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* horizontal sub-sample only */ { sycc422_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 1) && (img->comps[2].dx == 1) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* no sub-sample */ { sycc444_to_rgb(img); } else { fprintf(stderr,"%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__); return; } }/* color_sycc_to_rgb() */ #if defined(OPJ_HAVE_LIBLCMS2) || defined(OPJ_HAVE_LIBLCMS1) #ifdef OPJ_HAVE_LIBLCMS1 /* Bob Friesenhahn proposed:*/ #define cmsSigXYZData icSigXYZData #define cmsSigLabData icSigLabData #define cmsSigCmykData icSigCmykData #define cmsSigYCbCrData icSigYCbCrData #define cmsSigLuvData icSigLuvData #define cmsSigGrayData icSigGrayData #define cmsSigRgbData icSigRgbData #define cmsUInt32Number DWORD #define cmsColorSpaceSignature icColorSpaceSignature #define cmsGetHeaderRenderingIntent cmsTakeRenderingIntent #endif /* OPJ_HAVE_LIBLCMS1 */ /*#define DEBUG_PROFILE*/ void color_apply_icc_profile(opj_image_t *image) { cmsHPROFILE in_prof, out_prof; cmsHTRANSFORM transform; cmsColorSpaceSignature in_space, out_space; cmsUInt32Number intent, in_type, out_type; int *r, *g, *b; size_t nr_samples, i, max, max_w, max_h; int prec, ok = 0; OPJ_COLOR_SPACE new_space; in_prof = cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len); #ifdef DEBUG_PROFILE FILE *icm = fopen("debug.icm","wb"); fwrite( image->icc_profile_buf,1, image->icc_profile_len,icm); fclose(icm); #endif if(in_prof == NULL) return; in_space = cmsGetPCS(in_prof); out_space = cmsGetColorSpace(in_prof); intent = cmsGetHeaderRenderingIntent(in_prof); max_w = image->comps[0].w; max_h = image->comps[0].h; prec = (int)image->comps[0].prec; if(out_space == cmsSigRgbData) /* enumCS 16 */ { if( prec <= 8 ) { in_type = TYPE_RGB_8; out_type = TYPE_RGB_8; } else { in_type = TYPE_RGB_16; out_type = TYPE_RGB_16; } out_prof = cmsCreate_sRGBProfile(); new_space = OPJ_CLRSPC_SRGB; } else if(out_space == cmsSigGrayData) /* enumCS 17 */ { in_type = TYPE_GRAY_8; out_type = TYPE_RGB_8; out_prof = cmsCreate_sRGBProfile(); new_space = OPJ_CLRSPC_SRGB; } else if(out_space == cmsSigYCbCrData) /* enumCS 18 */ { in_type = TYPE_YCbCr_16; out_type = TYPE_RGB_16; out_prof = cmsCreate_sRGBProfile(); new_space = OPJ_CLRSPC_SRGB; } else { #ifdef DEBUG_PROFILE fprintf(stderr,"%s:%d: color_apply_icc_profile\n\tICC Profile has unknown " "output colorspace(%#x)(%c%c%c%c)\n\tICC Profile ignored.\n", __FILE__,__LINE__,out_space, (out_space>>24) & 0xff,(out_space>>16) & 0xff, (out_space>>8) & 0xff, out_space & 0xff); #endif cmsCloseProfile(in_prof); return; } if(out_prof == NULL) { cmsCloseProfile(in_prof); return; } #ifdef DEBUG_PROFILE fprintf(stderr,"%s:%d:color_apply_icc_profile\n\tchannels(%d) prec(%d) w(%d) h(%d)" "\n\tprofile: in(%p) out(%p)\n",__FILE__,__LINE__,image->numcomps,prec, max_w,max_h, (void*)in_prof,(void*)out_prof); fprintf(stderr,"\trender_intent (%u)\n\t" "color_space: in(%#x)(%c%c%c%c) out:(%#x)(%c%c%c%c)\n\t" " type: in(%u) out:(%u)\n", intent, in_space, (in_space>>24) & 0xff,(in_space>>16) & 0xff, (in_space>>8) & 0xff, in_space & 0xff, out_space, (out_space>>24) & 0xff,(out_space>>16) & 0xff, (out_space>>8) & 0xff, out_space & 0xff, in_type,out_type ); #else (void)prec; (void)in_space; #endif /* DEBUG_PROFILE */ transform = cmsCreateTransform(in_prof, in_type, out_prof, out_type, intent, 0); #ifdef OPJ_HAVE_LIBLCMS2 /* Possible for: LCMS_VERSION >= 2000 :*/ cmsCloseProfile(in_prof); cmsCloseProfile(out_prof); #endif if(transform == NULL) { #ifdef DEBUG_PROFILE fprintf(stderr,"%s:%d:color_apply_icc_profile\n\tcmsCreateTransform failed. " "ICC Profile ignored.\n",__FILE__,__LINE__); #endif #ifdef OPJ_HAVE_LIBLCMS1 cmsCloseProfile(in_prof); cmsCloseProfile(out_prof); #endif return; } if(image->numcomps > 2)/* RGB, RGBA */ { if( prec <= 8 ) { unsigned char *inbuf, *outbuf, *in, *out; max = max_w * max_h; nr_samples = (size_t)(max * 3U * sizeof(unsigned char)); in = inbuf = (unsigned char*)malloc(nr_samples); out = outbuf = (unsigned char*)malloc(nr_samples); if(inbuf == NULL || outbuf == NULL) goto fails0; r = image->comps[0].data; g = image->comps[1].data; b = image->comps[2].data; for(i = 0U; i < max; ++i) { *in++ = (unsigned char)*r++; *in++ = (unsigned char)*g++; *in++ = (unsigned char)*b++; } cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max); r = image->comps[0].data; g = image->comps[1].data; b = image->comps[2].data; for(i = 0U; i < max; ++i) { *r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++; } ok = 1; fails0: free(inbuf); free(outbuf); } else /* prec > 8 */ { unsigned short *inbuf, *outbuf, *in, *out; max = max_w * max_h; nr_samples = (size_t)(max * 3U * sizeof(unsigned short)); in = inbuf = (unsigned short*)malloc(nr_samples); out = outbuf = (unsigned short*)malloc(nr_samples); if(inbuf == NULL || outbuf == NULL) goto fails1; r = image->comps[0].data; g = image->comps[1].data; b = image->comps[2].data; for(i = 0U ; i < max; ++i) { *in++ = (unsigned short)*r++; *in++ = (unsigned short)*g++; *in++ = (unsigned short)*b++; } cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max); r = image->comps[0].data; g = image->comps[1].data; b = image->comps[2].data; for(i = 0; i < max; ++i) { *r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++; } ok = 1; fails1: free(inbuf); free(outbuf); } } else /* image->numcomps <= 2 : GRAY, GRAYA */ { if(prec <= 8) { unsigned char *in, *inbuf, *out, *outbuf; opj_image_comp_t *new_comps; max = max_w * max_h; nr_samples = (size_t)(max * 3 * sizeof(unsigned char)); in = inbuf = (unsigned char*)malloc(nr_samples); out = outbuf = (unsigned char*)malloc(nr_samples); g = (int*)calloc((size_t)max, sizeof(int)); b = (int*)calloc((size_t)max, sizeof(int)); if(inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) goto fails2; new_comps = (opj_image_comp_t*)realloc(image->comps, (image->numcomps+2)*sizeof(opj_image_comp_t)); if(new_comps == NULL) goto fails2; image->comps = new_comps; if(image->numcomps == 2) image->comps[3] = image->comps[1]; image->comps[1] = image->comps[0]; image->comps[2] = image->comps[0]; image->comps[1].data = g; image->comps[2].data = b; image->numcomps += 2; r = image->comps[0].data; for(i = 0U; i < max; ++i) { *in++ = (unsigned char)*r++; } cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max); r = image->comps[0].data; g = image->comps[1].data; b = image->comps[2].data; for(i = 0U; i < max; ++i) { *r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++; } r = g = b = NULL; ok = 1; fails2: free(inbuf); free(outbuf); free(g); free(b); } else /* prec > 8 */ { unsigned short *in, *inbuf, *out, *outbuf; opj_image_comp_t *new_comps; max = max_w * max_h; nr_samples = (size_t)(max * 3U * sizeof(unsigned short)); in = inbuf = (unsigned short*)malloc(nr_samples); out = outbuf = (unsigned short*)malloc(nr_samples); g = (int*)calloc((size_t)max, sizeof(int)); b = (int*)calloc((size_t)max, sizeof(int)); if(inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) goto fails3; new_comps = (opj_image_comp_t*)realloc(image->comps, (image->numcomps+2)*sizeof(opj_image_comp_t)); if(new_comps == NULL) goto fails3; image->comps = new_comps; if(image->numcomps == 2) image->comps[3] = image->comps[1]; image->comps[1] = image->comps[0]; image->comps[2] = image->comps[0]; image->comps[1].data = g; image->comps[2].data = b; image->numcomps += 2; r = image->comps[0].data; for(i = 0U; i < max; ++i) { *in++ = (unsigned short)*r++; } cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max); r = image->comps[0].data; g = image->comps[1].data; b = image->comps[2].data; for(i = 0; i < max; ++i) { *r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++; } r = g = b = NULL; ok = 1; fails3: free(inbuf); free(outbuf); free(g); free(b); } }/* if(image->numcomps > 2) */ cmsDeleteTransform(transform); #ifdef OPJ_HAVE_LIBLCMS1 cmsCloseProfile(in_prof); cmsCloseProfile(out_prof); #endif if(ok) { image->color_space = new_space; } }/* color_apply_icc_profile() */ void color_cielab_to_rgb(opj_image_t *image) { int *row; int enumcs, numcomps; OPJ_COLOR_SPACE new_space; numcomps = (int)image->numcomps; if(numcomps != 3) { fprintf(stderr,"%s:%d:\n\tnumcomps %d not handled. Quitting.\n", __FILE__,__LINE__,numcomps); return; } row = (int*)image->icc_profile_buf; enumcs = row[0]; if(enumcs == 14) /* CIELab */ { int *L, *a, *b, *red, *green, *blue; int *src0, *src1, *src2, *dst0, *dst1, *dst2; double rl, ol, ra, oa, rb, ob, prec0, prec1, prec2; double minL, maxL, mina, maxa, minb, maxb; unsigned int default_type; unsigned int i, max; cmsHPROFILE in, out; cmsHTRANSFORM transform; cmsUInt16Number RGB[3]; cmsCIELab Lab; in = cmsCreateLab4Profile(NULL); if(in == NULL){ return; } out = cmsCreate_sRGBProfile(); if(out == NULL){ cmsCloseProfile(in); return; } transform = cmsCreateTransform(in, TYPE_Lab_DBL, out, TYPE_RGB_16, INTENT_PERCEPTUAL, 0); #ifdef OPJ_HAVE_LIBLCMS2 cmsCloseProfile(in); cmsCloseProfile(out); #endif if(transform == NULL) { #ifdef OPJ_HAVE_LIBLCMS1 cmsCloseProfile(in); cmsCloseProfile(out); #endif return; } new_space = OPJ_CLRSPC_SRGB; prec0 = (double)image->comps[0].prec; prec1 = (double)image->comps[1].prec; prec2 = (double)image->comps[2].prec; default_type = (unsigned int)row[1]; if(default_type == 0x44454600)/* DEF : default */ { rl = 100; ra = 170; rb = 200; ol = 0; oa = pow(2, prec1 - 1); ob = pow(2, prec2 - 2) + pow(2, prec2 - 3); } else { rl = row[2]; ra = row[4]; rb = row[6]; ol = row[3]; oa = row[5]; ob = row[7]; } L = src0 = image->comps[0].data; a = src1 = image->comps[1].data; b = src2 = image->comps[2].data; max = image->comps[0].w * image->comps[0].h; red = dst0 = (int*)malloc(max * sizeof(int)); green = dst1 = (int*)malloc(max * sizeof(int)); blue = dst2 = (int*)malloc(max * sizeof(int)); if(red == NULL || green == NULL || blue == NULL) goto fails; minL = -(rl * ol)/(pow(2, prec0)-1); maxL = minL + rl; mina = -(ra * oa)/(pow(2, prec1)-1); maxa = mina + ra; minb = -(rb * ob)/(pow(2, prec2)-1); maxb = minb + rb; for(i = 0; i < max; ++i) { Lab.L = minL + (double)(*L) * (maxL - minL)/(pow(2, prec0)-1); ++L; Lab.a = mina + (double)(*a) * (maxa - mina)/(pow(2, prec1)-1); ++a; Lab.b = minb + (double)(*b) * (maxb - minb)/(pow(2, prec2)-1); ++b; cmsDoTransform(transform, &Lab, RGB, 1); *red++ = RGB[0]; *green++ = RGB[1]; *blue++ = RGB[2]; } cmsDeleteTransform(transform); #ifdef OPJ_HAVE_LIBLCMS1 cmsCloseProfile(in); cmsCloseProfile(out); #endif free(src0); image->comps[0].data = dst0; free(src1); image->comps[1].data = dst1; free(src2); image->comps[2].data = dst2; image->color_space = new_space; image->comps[0].prec = 16; image->comps[1].prec = 16; image->comps[2].prec = 16; return; fails: cmsDeleteTransform(transform); #ifdef OPJ_HAVE_LIBLCMS1 cmsCloseProfile(in); cmsCloseProfile(out); #endif if(red) free(red); if(green) free(green); if(blue) free(blue); return; } fprintf(stderr,"%s:%d:\n\tenumCS %d not handled. Ignoring.\n", __FILE__,__LINE__, enumcs); }/* color_cielab_to_rgb() */ #endif /* OPJ_HAVE_LIBLCMS2 || OPJ_HAVE_LIBLCMS1 */ void color_cmyk_to_rgb(opj_image_t *image) { float C, M, Y, K; float sC, sM, sY, sK; unsigned int w, h, max, i; w = image->comps[0].w; h = image->comps[0].h; if(image->numcomps < 4) return; max = w * h; sC = 1.0F / (float)((1 << image->comps[0].prec) - 1); sM = 1.0F / (float)((1 << image->comps[1].prec) - 1); sY = 1.0F / (float)((1 << image->comps[2].prec) - 1); sK = 1.0F / (float)((1 << image->comps[3].prec) - 1); for(i = 0; i < max; ++i) { /* CMYK values from 0 to 1 */ C = (float)(image->comps[0].data[i]) * sC; M = (float)(image->comps[1].data[i]) * sM; Y = (float)(image->comps[2].data[i]) * sY; K = (float)(image->comps[3].data[i]) * sK; /* Invert all CMYK values */ C = 1.0F - C; M = 1.0F - M; Y = 1.0F - Y; K = 1.0F - K; /* CMYK -> RGB : RGB results from 0 to 255 */ image->comps[0].data[i] = (int)(255.0F * C * K); /* R */ image->comps[1].data[i] = (int)(255.0F * M * K); /* G */ image->comps[2].data[i] = (int)(255.0F * Y * K); /* B */ } free(image->comps[3].data); image->comps[3].data = NULL; image->comps[0].prec = 8; image->comps[1].prec = 8; image->comps[2].prec = 8; image->numcomps -= 1; image->color_space = OPJ_CLRSPC_SRGB; for (i = 3; i < image->numcomps; ++i) { memcpy(&(image->comps[i]), &(image->comps[i+1]), sizeof(image->comps[i])); } }/* color_cmyk_to_rgb() */ /* * This code has been adopted from sjpx_openjpeg.c of ghostscript */ void color_esycc_to_rgb(opj_image_t *image) { int y, cb, cr, sign1, sign2, val; unsigned int w, h, max, i; int flip_value = (1 << (image->comps[0].prec-1)); int max_value = (1 << image->comps[0].prec) - 1; if ( (image->numcomps < 3) || (image->comps[0].dx != image->comps[1].dx) || (image->comps[0].dx != image->comps[2].dx) || (image->comps[0].dy != image->comps[1].dy) || (image->comps[0].dy != image->comps[2].dy) ) { fprintf(stderr,"%s:%d:color_esycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__); return; } w = image->comps[0].w; h = image->comps[0].h; sign1 = (int)image->comps[1].sgnd; sign2 = (int)image->comps[2].sgnd; max = w * h; for(i = 0; i < max; ++i) { y = image->comps[0].data[i]; cb = image->comps[1].data[i]; cr = image->comps[2].data[i]; if( !sign1) cb -= flip_value; if( !sign2) cr -= flip_value; val = (int) ((float)y - (float)0.0000368 * (float)cb + (float)1.40199 * (float)cr + (float)0.5); if(val > max_value) val = max_value; else if(val < 0) val = 0; image->comps[0].data[i] = val; val = (int) ((float)1.0003 * (float)y - (float)0.344125 * (float)cb - (float)0.7141128 * (float)cr + (float)0.5); if(val > max_value) val = max_value; else if(val < 0) val = 0; image->comps[1].data[i] = val; val = (int) ((float)0.999823 * (float)y + (float)1.77204 * (float)cb - (float)0.000008 *(float)cr + (float)0.5); if(val > max_value) val = max_value; else if(val < 0) val = 0; image->comps[2].data[i] = val; } image->color_space = OPJ_CLRSPC_SRGB; }/* color_esycc_to_rgb() */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5062_0
crossvul-cpp_data_good_525_3
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / Scene Management sub-project * * GPAC is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GPAC 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <gpac/scene_manager.h> #include <gpac/constants.h> #include <gpac/media_tools.h> #include <gpac/bifs.h> #include <gpac/xml.h> #include <gpac/internal/scenegraph_dev.h> #include <gpac/network.h> GF_EXPORT GF_SceneManager *gf_sm_new(GF_SceneGraph *graph) { GF_SceneManager *tmp; if (!graph) return NULL; GF_SAFEALLOC(tmp, GF_SceneManager); if (!tmp) return NULL; tmp->streams = gf_list_new(); tmp->scene_graph = graph; return tmp; } GF_EXPORT GF_StreamContext *gf_sm_stream_new(GF_SceneManager *ctx, u16 ES_ID, u8 streamType, u8 objectType) { u32 i; GF_StreamContext *tmp; i=0; while ((tmp = (GF_StreamContext*)gf_list_enum(ctx->streams, &i))) { /*we MUST use the same ST*/ if (tmp->streamType!=streamType) continue; /*if no ESID/OTI specified this is a base layer (default stream created by parsers) if ESID/OTI specified this is a stream already setup */ if ( tmp->ESID==ES_ID ) { //tmp->objectType = objectType; return tmp; } } GF_SAFEALLOC(tmp, GF_StreamContext); if (!tmp) return NULL; tmp->AUs = gf_list_new(); tmp->ESID = ES_ID; tmp->streamType = streamType; tmp->objectType = objectType ? objectType : 1; tmp->timeScale = 1000; gf_list_add(ctx->streams, tmp); return tmp; } GF_StreamContext *gf_sm_stream_find(GF_SceneManager *ctx, u16 ES_ID) { u32 i, count; if (!ES_ID) return NULL; count = gf_list_count(ctx->streams); for (i=0; i<count; i++) { GF_StreamContext *tmp = (GF_StreamContext *)gf_list_get(ctx->streams, i); if (tmp->ESID==ES_ID) return tmp; } return NULL; } GF_EXPORT GF_MuxInfo *gf_sm_get_mux_info(GF_ESD *src) { u32 i; GF_MuxInfo *mux; i=0; while ((mux = (GF_MuxInfo *)gf_list_enum(src->extensionDescriptors, &i))) { if (mux->tag == GF_ODF_MUXINFO_TAG) return mux; } return NULL; } static void gf_sm_au_del(GF_StreamContext *sc, GF_AUContext *au) { while (gf_list_count(au->commands)) { void *comptr = gf_list_last(au->commands); gf_list_rem_last(au->commands); switch (sc->streamType) { case GF_STREAM_OD: gf_odf_com_del((GF_ODCom**) & comptr); break; case GF_STREAM_SCENE: gf_sg_command_del((GF_Command *)comptr); break; } } gf_list_del(au->commands); gf_free(au); } static void gf_sm_reset_stream(GF_StreamContext *sc) { while (gf_list_count(sc->AUs)) { GF_AUContext *au = (GF_AUContext *)gf_list_last(sc->AUs); gf_list_rem_last(sc->AUs); gf_sm_au_del(sc, au); } } static void gf_sm_delete_stream(GF_StreamContext *sc) { gf_sm_reset_stream(sc); gf_list_del(sc->AUs); if (sc->name) gf_free(sc->name); if (sc->dec_cfg) gf_free(sc->dec_cfg); gf_free(sc); } GF_EXPORT void gf_sm_stream_del(GF_SceneManager *ctx, GF_StreamContext *sc) { if (gf_list_del_item(ctx->streams, sc)>=0) { gf_sm_delete_stream(sc); } } GF_EXPORT void gf_sm_del(GF_SceneManager *ctx) { u32 count; while ( (count = gf_list_count(ctx->streams)) ) { GF_StreamContext *sc = (GF_StreamContext *)gf_list_get(ctx->streams, count-1); gf_list_rem(ctx->streams, count-1); gf_sm_delete_stream(sc); } gf_list_del(ctx->streams); if (ctx->root_od) gf_odf_desc_del((GF_Descriptor *) ctx->root_od); gf_free(ctx); } GF_EXPORT void gf_sm_reset(GF_SceneManager *ctx) { GF_StreamContext *sc; u32 i=0; while ( (sc = gf_list_enum(ctx->streams, &i)) ) { gf_sm_reset_stream(sc); } if (ctx->root_od) gf_odf_desc_del((GF_Descriptor *) ctx->root_od); ctx->root_od = NULL; } GF_EXPORT GF_AUContext *gf_sm_stream_au_new(GF_StreamContext *stream, u64 timing, Double time_sec, Bool isRap) { u32 i; GF_AUContext *tmp; u64 tmp_timing; tmp_timing = timing ? timing : (u64) (time_sec*1000); if (stream->imp_exp_time >= tmp_timing) { /*look for existing AU*/ i=0; while ((tmp = (GF_AUContext *)gf_list_enum(stream->AUs, &i))) { if (timing && (tmp->timing==timing)) return tmp; else if (time_sec && (tmp->timing_sec == time_sec)) return tmp; else if (!time_sec && !timing && !tmp->timing && !tmp->timing_sec) return tmp; /*insert AU*/ else if ((time_sec && time_sec<tmp->timing_sec) || (timing && timing<tmp->timing)) { GF_SAFEALLOC(tmp, GF_AUContext); if (!tmp) return NULL; tmp->commands = gf_list_new(); if (isRap) tmp->flags = GF_SM_AU_RAP; tmp->timing = timing; tmp->timing_sec = time_sec; tmp->owner = stream; gf_list_insert(stream->AUs, tmp, i-1); return tmp; } } } GF_SAFEALLOC(tmp, GF_AUContext); if (!tmp) return NULL; tmp->commands = gf_list_new(); if (isRap) tmp->flags = GF_SM_AU_RAP; tmp->timing = timing; tmp->timing_sec = time_sec; tmp->owner = stream; if (stream->disable_aggregation) tmp->flags |= GF_SM_AU_NOT_AGGREGATED; gf_list_add(stream->AUs, tmp); stream->imp_exp_time = tmp_timing; return tmp; } static Bool node_in_commands_subtree(GF_Node *node, GF_List *commands) { #ifndef GPAC_DISABLE_VRML u32 i, j, count, nb_fields; count = gf_list_count(commands); for (i=0; i<count; i++) { GF_Command *com = gf_list_get(commands, i); if (com->tag>=GF_SG_LAST_BIFS_COMMAND) { GF_LOG(GF_LOG_ERROR, GF_LOG_SCENE, ("[Scene Manager] Command check for LASeR/DIMS not supported\n")); return 0; } if (com->tag==GF_SG_SCENE_REPLACE) { if (gf_node_parent_of(com->node, node)) return 1; continue; } nb_fields = gf_list_count(com->command_fields); for (j=0; j<nb_fields; j++) { GF_CommandField *field = gf_list_get(com->command_fields, j); switch (field->fieldType) { case GF_SG_VRML_SFNODE: if (field->new_node) { if (gf_node_parent_of(field->new_node, node)) return 1; } break; case GF_SG_VRML_MFNODE: if (field->field_ptr) { GF_ChildNodeItem *child; child = field->node_list; while (child) { if (gf_node_parent_of(child->node, node)) return 1; child = child->next; } } break; } } } #endif return 0; } static u32 store_or_aggregate(GF_StreamContext *sc, GF_Command *com, GF_List *commands, Bool *has_modif) { #ifndef GPAC_DISABLE_VRML u32 i, count, j, nb_fields; GF_CommandField *field, *check_field; /*if our command deals with a node inserted in the commands list, apply command list*/ if (node_in_commands_subtree(com->node, commands)) return 0; /*otherwise, check if we can substitute a previous command with this one*/ count = gf_list_count(commands); for (i=0; i<count; i++) { GF_Command *check = gf_list_get(commands, i); if (sc->streamType == GF_STREAM_SCENE) { Bool check_index=0; Bool original_is_index = 0; Bool apply; switch (com->tag) { case GF_SG_INDEXED_REPLACE: check_index=1; case GF_SG_MULTIPLE_INDEXED_REPLACE: case GF_SG_FIELD_REPLACE: case GF_SG_MULTIPLE_REPLACE: if (check->node != com->node) break; /*we may aggregate an indexed insertion and a replace one*/ if (check_index) { if (check->tag == GF_SG_INDEXED_REPLACE) {} else if (check->tag == GF_SG_INDEXED_INSERT) { original_is_index = 1; } else { break; } } else { if (check->tag != com->tag) break; } nb_fields = gf_list_count(com->command_fields); if (gf_list_count(check->command_fields) != nb_fields) break; apply=1; for (j=0; j<nb_fields; j++) { field = gf_list_get(com->command_fields, j); check_field = gf_list_get(check->command_fields, j); if ((field->pos != check_field->pos) || (field->fieldIndex != check_field->fieldIndex)) { apply=0; break; } } /*same target node+fields, destroy first command and store new one*/ if (apply) { /*if indexed, change command tag*/ if (original_is_index) com->tag = GF_SG_INDEXED_INSERT; gf_sg_command_del((GF_Command *)check); gf_list_rem(commands, i); if (has_modif) *has_modif = 1; return 1; } break; case GF_SG_NODE_REPLACE: if (check->tag != GF_SG_NODE_REPLACE) { break; } /*TODO - THIS IS NOT SUPPORTED IN GPAC SINCE WE NEVER ALLOW FOR DUPLICATE NODE IDs IN THE SCENE !!!*/ if (gf_node_get_id(check->node) != gf_node_get_id(com->node) ) { break; } /*same node ID, destroy first command and store new one*/ gf_sg_command_del((GF_Command *)check); gf_list_rem(commands, i); if (has_modif) *has_modif = 1; return 1; case GF_SG_INDEXED_DELETE: /*look for an indexed insert before the indexed delete with same target pos and node. If found, discard both commands!*/ if (check->tag != GF_SG_INDEXED_INSERT) break; if (com->node != check->node) break; field = gf_list_get(com->command_fields, 0); check_field = gf_list_get(check->command_fields, 0); if (!field || !check_field) break; if (field->pos != check_field->pos) break; if (field->fieldIndex != check_field->fieldIndex) break; gf_sg_command_del((GF_Command *)check); gf_list_rem(commands, i); if (has_modif) *has_modif = 1; return 2; default: GF_LOG(GF_LOG_ERROR, GF_LOG_SCENE, ("[Scene Manager] Stream Aggregation not implemented for command - aggregating on main scene\n")); break; } } } /*the command modifies another stream than associated current carousel stream, we have to store it.*/ if (has_modif) *has_modif=1; #endif return 1; } static GF_StreamContext *gf_sm_get_stream(GF_SceneManager *ctx, u16 ESID) { u32 i, count; count = gf_list_count(ctx->streams); for (i=0; i<count; i++) { GF_StreamContext *sc = gf_list_get(ctx->streams, i); if (sc->ESID==ESID) return sc; } return NULL; } GF_EXPORT GF_Err gf_sm_aggregate(GF_SceneManager *ctx, u16 ESID) { GF_Err e; u32 i, stream_count; #ifndef GPAC_DISABLE_VRML u32 j; GF_AUContext *au; GF_Command *com; #endif e = GF_OK; #if DEBUG_RAP com_count = 0; stream_count = gf_list_count(ctx->streams); for (i=0; i<stream_count; i++) { GF_StreamContext *sc = (GF_StreamContext *)gf_list_get(ctx->streams, i); if (sc->streamType == GF_STREAM_SCENE) { au_count = gf_list_count(sc->AUs); for (j=0; j<au_count; j++) { au = (GF_AUContext *)gf_list_get(sc->AUs, j); com_count += gf_list_count(au->commands); } } } GF_LOG(GF_LOG_INFO, GF_LOG_SCENE, ("[SceneManager] Making RAP with %d commands\n", com_count)); #endif stream_count = gf_list_count(ctx->streams); for (i=0; i<stream_count; i++) { GF_AUContext *carousel_au; GF_List *carousel_commands; GF_StreamContext *aggregate_on_stream; GF_StreamContext *sc = (GF_StreamContext *)gf_list_get(ctx->streams, i); if (ESID && (sc->ESID!=ESID)) continue; /*locate the AU in which our commands will be aggregated*/ carousel_au = NULL; carousel_commands = NULL; aggregate_on_stream = sc->aggregate_on_esid ? gf_sm_get_stream(ctx, sc->aggregate_on_esid) : NULL; if (aggregate_on_stream==sc) { carousel_commands = gf_list_new(); } else if (aggregate_on_stream) { if (!gf_list_count(aggregate_on_stream->AUs)) { carousel_au = gf_sm_stream_au_new(aggregate_on_stream, 0, 0, 1); } else { /* assert we already performed aggregation */ assert(gf_list_count(aggregate_on_stream->AUs)==1); carousel_au = gf_list_get(aggregate_on_stream->AUs, 0); } carousel_commands = carousel_au->commands; } /*TODO - do this as well for ODs*/ #ifndef GPAC_DISABLE_VRML if (sc->streamType == GF_STREAM_SCENE) { Bool has_modif = 0; /*we check for each stream if it is a base stream (SceneReplace ...) - several streams may carry RAPs if inline nodes are used*/ Bool base_stream_found = 0; /*in DIMS we use an empty initial AU with no commands to signal the RAP*/ if (sc->objectType == GPAC_OTI_SCENE_DIMS) base_stream_found = 1; /*apply all commands - this will also apply the SceneReplace*/ while (gf_list_count(sc->AUs)) { u32 count; au = (GF_AUContext *) gf_list_get(sc->AUs, 0); gf_list_rem(sc->AUs, 0); /*AU not aggregated*/ if (au->flags & GF_SM_AU_NOT_AGGREGATED) { gf_sm_au_del(sc, au); continue; } count = gf_list_count(au->commands); for (j=0; j<count; j++) { u32 store=0; com = gf_list_get(au->commands, j); if (!base_stream_found) { switch (com->tag) { case GF_SG_SCENE_REPLACE: case GF_SG_LSR_NEW_SCENE: case GF_SG_LSR_REFRESH_SCENE: base_stream_found = 1; break; } } /*aggregate the command*/ /*if stream doesn't carry a carousel or carries the base carousel (scene replace), always apply the command*/ if (base_stream_found || !sc->aggregate_on_esid) { store = 0; } /*otherwise, check wether the command should be kept in this stream as is, or can be aggregated on this stream*/ else { switch (com->tag) { /*the following commands do not impact a sub-tree (eg do not deal with nodes), we cannot aggregate them... */ case GF_SG_ROUTE_REPLACE: case GF_SG_ROUTE_DELETE: case GF_SG_ROUTE_INSERT: case GF_SG_PROTO_INSERT: case GF_SG_PROTO_DELETE: case GF_SG_PROTO_DELETE_ALL: case GF_SG_GLOBAL_QUANTIZER: case GF_SG_LSR_RESTORE: case GF_SG_LSR_SAVE: case GF_SG_LSR_SEND_EVENT: case GF_SG_LSR_CLEAN: /*todo check in which category to put these commands*/ // case GF_SG_LSR_ACTIVATE: // case GF_SG_LSR_DEACTIVATE: store = 1; break; /*other commands: !!! we need to know if the target node of the command has been inserted in this stream !!! This is a tedious task, for now we will consider the following cases: - locate a similar command in the stored list: remove the similar one and aggregate on stream - by default all AUs are stored if the stream is in aggregate mode - we should fix that by checking insertion points: if a command apllies on a node that has been inserted in this stream, we can aggregate, otherwise store */ default: /*check if we can directly store the command*/ assert(carousel_commands); store = store_or_aggregate(sc, com, carousel_commands, &has_modif); break; } } switch (store) { /*command has been merged with a previous command in carousel and needs to be destroyed*/ case 2: gf_list_rem(au->commands, j); j--; count--; gf_sg_command_del((GF_Command *)com); break; /*command shall be moved to carousel without being applied*/ case 1: gf_list_insert(carousel_commands, com, 0); gf_list_rem(au->commands, j); j--; count--; break; /*command can be applied*/ default: e = gf_sg_command_apply(ctx->scene_graph, com, 0); break; } } gf_sm_au_del(sc, au); } /*and recreate scene replace*/ if (base_stream_found) { au = gf_sm_stream_au_new(sc, 0, 0, 1); switch (sc->objectType) { case GPAC_OTI_SCENE_BIFS: case GPAC_OTI_SCENE_BIFS_V2: com = gf_sg_command_new(ctx->scene_graph, GF_SG_SCENE_REPLACE); break; case GPAC_OTI_SCENE_LASER: com = gf_sg_command_new(ctx->scene_graph, GF_SG_LSR_NEW_SCENE); break; case GPAC_OTI_SCENE_DIMS: /* We do not create a new command, empty AU is enough in DIMS*/ default: com = NULL; break; } if (com) { com->node = ctx->scene_graph->RootNode; ctx->scene_graph->RootNode = NULL; gf_list_del(com->new_proto_list); com->new_proto_list = ctx->scene_graph->protos; ctx->scene_graph->protos = NULL; /*indicate the command is the aggregated scene graph, so that PROTOs and ROUTEs are taken from the scenegraph when encoding*/ com->aggregated = 1; gf_list_add(au->commands, com); } } /*update carousel flags of the AU*/ else if (carousel_commands) { /*if current stream caries its own carousel*/ if (!carousel_au) { carousel_au = gf_sm_stream_au_new(sc, 0, 0, 1); gf_list_del(carousel_au->commands); carousel_au->commands = carousel_commands; } carousel_au->flags |= GF_SM_AU_RAP | GF_SM_AU_CAROUSEL; if (has_modif) carousel_au->flags |= GF_SM_AU_MODIFIED; } } #endif } return e; } #ifndef GPAC_DISABLE_LOADER_BT GF_Err gf_sm_load_init_bt(GF_SceneLoader *load); #endif #ifndef GPAC_DISABLE_LOADER_XMT GF_Err gf_sm_load_init_xmt(GF_SceneLoader *load); #endif #ifndef GPAC_DISABLE_LOADER_ISOM GF_Err gf_sm_load_init_isom(GF_SceneLoader *load); #endif #ifndef GPAC_DISABLE_SVG GF_Err gf_sm_load_init_svg(GF_SceneLoader *load); GF_Err gf_sm_load_init_xbl(GF_SceneLoader *load); GF_Err gf_sm_load_run_xbl(GF_SceneLoader *load); void gf_sm_load_done_xbl(GF_SceneLoader *load); #endif #ifndef GPAC_DISABLE_SWF_IMPORT GF_Err gf_sm_load_init_swf(GF_SceneLoader *load); #endif #ifndef GPAC_DISABLE_QTVR GF_Err gf_sm_load_init_qt(GF_SceneLoader *load); #endif GF_EXPORT GF_Err gf_sm_load_string(GF_SceneLoader *load, const char *str, Bool do_clean) { GF_Err e; if (!load->type) e = GF_BAD_PARAM; else if (load->parse_string) e = load->parse_string(load, str); else e = GF_NOT_SUPPORTED; return e; } /*initializes the context loader*/ GF_EXPORT GF_Err gf_sm_load_init(GF_SceneLoader *load) { GF_Err e = GF_NOT_SUPPORTED; char *ext, szExt[50]; /*we need at least a scene graph*/ if (!load || (!load->ctx && !load->scene_graph) #ifndef GPAC_DISABLE_ISOM || (!load->fileName && !load->isom && !(load->flags & GF_SM_LOAD_FOR_PLAYBACK) ) #endif ) return GF_BAD_PARAM; if (!load->type) { #ifndef GPAC_DISABLE_ISOM if (load->isom) { load->type = GF_SM_LOAD_MP4; } else #endif { ext = (char *)strrchr(load->fileName, '.'); if (!ext) return GF_NOT_SUPPORTED; if (!stricmp(ext, ".gz")) { char *anext; ext[0] = 0; anext = (char *)strrchr(load->fileName, '.'); ext[0] = '.'; ext = anext; } if (strlen(ext) < 2 || strlen(ext) > sizeof(szExt)) { GF_LOG(GF_LOG_ERROR, GF_LOG_SCENE, ("[Scene Manager] invalid extension in file name %s\n", load->fileName)); return GF_NOT_SUPPORTED; } strcpy(szExt, &ext[1]); strlwr(szExt); if (strstr(szExt, "bt")) load->type = GF_SM_LOAD_BT; else if (strstr(szExt, "wrl")) load->type = GF_SM_LOAD_VRML; else if (strstr(szExt, "x3dv")) load->type = GF_SM_LOAD_X3DV; #ifndef GPAC_DISABLE_LOADER_XMT else if (strstr(szExt, "xmt") || strstr(szExt, "xmta")) load->type = GF_SM_LOAD_XMTA; else if (strstr(szExt, "x3d")) load->type = GF_SM_LOAD_X3D; #endif else if (strstr(szExt, "swf")) load->type = GF_SM_LOAD_SWF; else if (strstr(szExt, "mov")) load->type = GF_SM_LOAD_QT; else if (strstr(szExt, "svg")) load->type = GF_SM_LOAD_SVG; else if (strstr(szExt, "xsr")) load->type = GF_SM_LOAD_XSR; else if (strstr(szExt, "xbl")) load->type = GF_SM_LOAD_XBL; else if (strstr(szExt, "xml")) { char *rtype = gf_xml_get_root_type(load->fileName, &e); if (rtype) { if (!strcmp(rtype, "SAFSession")) load->type = GF_SM_LOAD_XSR; else if (!strcmp(rtype, "XMT-A")) load->type = GF_SM_LOAD_XMTA; else if (!strcmp(rtype, "X3D")) load->type = GF_SM_LOAD_X3D; else if (!strcmp(rtype, "bindings")) load->type = GF_SM_LOAD_XBL; gf_free(rtype); } } } } if (!load->type) return e; if (!load->scene_graph) load->scene_graph = load->ctx->scene_graph; switch (load->type) { #ifndef GPAC_DISABLE_LOADER_BT case GF_SM_LOAD_BT: case GF_SM_LOAD_VRML: case GF_SM_LOAD_X3DV: return gf_sm_load_init_bt(load); #endif #ifndef GPAC_DISABLE_LOADER_XMT case GF_SM_LOAD_XMTA: case GF_SM_LOAD_X3D: return gf_sm_load_init_xmt(load); #endif #ifndef GPAC_DISABLE_SVG case GF_SM_LOAD_SVG: case GF_SM_LOAD_XSR: case GF_SM_LOAD_DIMS: return gf_sm_load_init_svg(load); case GF_SM_LOAD_XBL: e = gf_sm_load_init_xbl(load); load->process = gf_sm_load_run_xbl; load->done = gf_sm_load_done_xbl; return e; #endif #ifndef GPAC_DISABLE_SWF_IMPORT case GF_SM_LOAD_SWF: return gf_sm_load_init_swf(load); #endif #ifndef GPAC_DISABLE_LOADER_ISOM case GF_SM_LOAD_MP4: return gf_sm_load_init_isom(load); #endif #ifndef GPAC_DISABLE_QTVR case GF_SM_LOAD_QT: return gf_sm_load_init_qt(load); #endif default: return GF_NOT_SUPPORTED; } return GF_NOT_SUPPORTED; } GF_EXPORT void gf_sm_load_done(GF_SceneLoader *load) { if (load->done) load->done(load); } GF_EXPORT GF_Err gf_sm_load_run(GF_SceneLoader *load) { if (load->process) return load->process(load); return GF_OK; } GF_EXPORT GF_Err gf_sm_load_suspend(GF_SceneLoader *load, Bool suspend) { if (load->suspend) return load->suspend(load, suspend); return GF_OK; } #if !defined(GPAC_DISABLE_LOADER_BT) || !defined(GPAC_DISABLE_LOADER_XMT) #include <gpac/base_coding.h> void gf_sm_update_bitwrapper_buffer(GF_Node *node, const char *fileName) { u32 data_size = 0; char *data = NULL; char *buffer; M_BitWrapper *bw = (M_BitWrapper *)node; if (!bw->buffer.buffer) return; buffer = bw->buffer.buffer; if (!strnicmp(buffer, "file://", 7)) { char *url = gf_url_concatenate(fileName, buffer+7); if (url) { FILE *f = gf_fopen(url, "rb"); if (f) { fseek(f, 0, SEEK_END); data_size = (u32) ftell(f); fseek(f, 0, SEEK_SET); data = gf_malloc(sizeof(char)*data_size); if (data) { if (fread(data, 1, data_size, f) != data_size) { GF_LOG(GF_LOG_ERROR, GF_LOG_SCENE, ("[Scene Manager] error reading bitwrapper file %s\n", url)); } } gf_fclose(f); } gf_free(url); } } else { Bool base_64 = 0; if (!strnicmp(buffer, "data:application/octet-string", 29)) { char *sep = strchr(bw->buffer.buffer, ','); base_64 = strstr(bw->buffer.buffer, ";base64") ? 1 : 0; if (sep) buffer = sep+1; } if (base_64) { data_size = 2 * (u32) strlen(buffer); data = (char*)gf_malloc(sizeof(char)*data_size); if (data) data_size = gf_base64_decode(buffer, (u32) strlen(buffer), data, data_size); } else { u32 i, c; char s[3]; data_size = (u32) strlen(buffer) / 3; data = (char*)gf_malloc(sizeof(char) * data_size); if (data) { s[2] = 0; for (i=0; i<data_size; i++) { s[0] = buffer[3*i+1]; s[1] = buffer[3*i+2]; sscanf(s, "%02X", &c); data[i] = (unsigned char) c; } } } } gf_free(bw->buffer.buffer); bw->buffer.buffer = NULL; bw->buffer_len = 0; if (data) { bw->buffer.buffer = data; bw->buffer_len = data_size; } } #endif //!defined(GPAC_DISABLE_LOADER_BT) || !defined(GPAC_DISABLE_LOADER_XMT)
./CrossVul/dataset_final_sorted/CWE-119/c/good_525_3
crossvul-cpp_data_bad_715_0
/* Legal Notice: Some portions of the source code contained in this file were derived from the source code of TrueCrypt 7.1a, which is Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux and which is governed by the 'License Agreement for Encryption for the Masses' Modifications and additions to the original source code (contained in this file) and all other portions of this file are Copyright (c) 2013-2017 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #include "TCdefs.h" #include <ntddk.h> #include "Crypto.h" #include "Fat.h" #include "Tests.h" #include "cpu.h" #include "Crc.h" #include "Apidrvr.h" #include "Boot/Windows/BootDefs.h" #include "EncryptedIoQueue.h" #include "EncryptionThreadPool.h" #include "Ntdriver.h" #include "Ntvol.h" #include "DriveFilter.h" #include "DumpFilter.h" #include "Cache.h" #include "Volumes.h" #include "VolumeFilter.h" #include <tchar.h> #include <initguid.h> #include <mountmgr.h> #include <mountdev.h> #include <ntddvol.h> #include <Ntstrsafe.h> #include <Intsafe.h> #ifndef IOCTL_DISK_GET_CLUSTER_INFO #define IOCTL_DISK_GET_CLUSTER_INFO CTL_CODE(IOCTL_DISK_BASE, 0x0085, METHOD_BUFFERED, FILE_ANY_ACCESS) #endif #ifndef IOCTL_DISK_ARE_VOLUMES_READY #define IOCTL_DISK_ARE_VOLUMES_READY CTL_CODE(IOCTL_DISK_BASE, 0x0087, METHOD_BUFFERED, FILE_READ_ACCESS) #endif #ifndef FT_BALANCED_READ_MODE #define FTTYPE ((ULONG)'f') #define FT_BALANCED_READ_MODE CTL_CODE(FTTYPE, 6, METHOD_NEITHER, FILE_ANY_ACCESS) #endif #ifndef IOCTL_VOLUME_QUERY_ALLOCATION_HINT #define IOCTL_VOLUME_QUERY_ALLOCATION_HINT CTL_CODE(IOCTL_VOLUME_BASE, 20, METHOD_OUT_DIRECT, FILE_READ_ACCESS) #endif #ifndef IOCTL_DISK_IS_CLUSTERED #define IOCTL_DISK_IS_CLUSTERED CTL_CODE(IOCTL_DISK_BASE, 0x003e, METHOD_BUFFERED, FILE_ANY_ACCESS) #endif #ifndef IOCTL_VOLUME_POST_ONLINE #define IOCTL_VOLUME_POST_ONLINE CTL_CODE(IOCTL_VOLUME_BASE, 25, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) #endif #ifndef IOCTL_VOLUME_IS_DYNAMIC #define IOCTL_VOLUME_IS_DYNAMIC CTL_CODE(IOCTL_VOLUME_BASE, 18, METHOD_BUFFERED, FILE_ANY_ACCESS) #endif #ifndef StorageDeviceLBProvisioningProperty #define StorageDeviceLBProvisioningProperty 11 #endif #ifndef DeviceDsmAction_OffloadRead #define DeviceDsmAction_OffloadRead ( 3 | DeviceDsmActionFlag_NonDestructive) #endif #ifndef DeviceDsmAction_OffloadWrite #define DeviceDsmAction_OffloadWrite 4 #endif #ifndef DeviceDsmAction_Allocation #define DeviceDsmAction_Allocation ( 5 | DeviceDsmActionFlag_NonDestructive) #endif #ifndef DeviceDsmAction_Repair #define DeviceDsmAction_Repair ( 6 | DeviceDsmActionFlag_NonDestructive) #endif #ifndef DeviceDsmAction_Scrub #define DeviceDsmAction_Scrub ( 7 | DeviceDsmActionFlag_NonDestructive) #endif #ifndef DeviceDsmAction_DrtQuery #define DeviceDsmAction_DrtQuery ( 8 | DeviceDsmActionFlag_NonDestructive) #endif #ifndef DeviceDsmAction_DrtClear #define DeviceDsmAction_DrtClear ( 9 | DeviceDsmActionFlag_NonDestructive) #endif #ifndef DeviceDsmAction_DrtDisable #define DeviceDsmAction_DrtDisable (10 | DeviceDsmActionFlag_NonDestructive) #endif /* Init section, which is thrown away as soon as DriverEntry returns */ #pragma alloc_text(INIT,DriverEntry) #pragma alloc_text(INIT,TCCreateRootDeviceObject) /* We need to silence 'type cast' warning in order to use MmGetSystemRoutineAddress. * MmGetSystemRoutineAddress() should have been declare FARPROC instead of PVOID. */ #pragma warning(disable:4055) PDRIVER_OBJECT TCDriverObject; PDEVICE_OBJECT RootDeviceObject = NULL; static KMUTEX RootDeviceControlMutex; BOOL DriverShuttingDown = FALSE; BOOL SelfTestsPassed; int LastUniqueVolumeId; ULONG OsMajorVersion = 0; ULONG OsMinorVersion; BOOL DriverUnloadDisabled = FALSE; BOOL PortableMode = FALSE; BOOL VolumeClassFilterRegistered = FALSE; BOOL CacheBootPassword = FALSE; BOOL CacheBootPim = FALSE; BOOL NonAdminSystemFavoritesAccessDisabled = FALSE; BOOL BlockSystemTrimCommand = FALSE; BOOL AllowWindowsDefrag = FALSE; static size_t EncryptionThreadPoolFreeCpuCountLimit = 0; static BOOL SystemFavoriteVolumeDirty = FALSE; static BOOL PagingFileCreationPrevented = FALSE; static BOOL EnableExtendedIoctlSupport = FALSE; static BOOL AllowTrimCommand = FALSE; static KeSaveExtendedProcessorStateFn KeSaveExtendedProcessorStatePtr = NULL; static KeRestoreExtendedProcessorStateFn KeRestoreExtendedProcessorStatePtr = NULL; POOL_TYPE ExDefaultNonPagedPoolType = NonPagedPool; ULONG ExDefaultMdlProtection = 0; PDEVICE_OBJECT VirtualVolumeDeviceObjects[MAX_MOUNTED_VOLUME_DRIVE_NUMBER + 1]; NTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) { PKEY_VALUE_PARTIAL_INFORMATION startKeyValue; LONG version; int i; Dump ("DriverEntry " TC_APP_NAME " " VERSION_STRING "\n"); DetectX86Features (); PsGetVersion (&OsMajorVersion, &OsMinorVersion, NULL, NULL); Dump ("OsMajorVersion=%d OsMinorVersion=%d\n", OsMajorVersion, OsMinorVersion); // NX pool support is available starting from Windows 8 if ((OsMajorVersion > 6) || (OsMajorVersion == 6 && OsMinorVersion >= 2)) { ExDefaultNonPagedPoolType = (POOL_TYPE) NonPagedPoolNx; ExDefaultMdlProtection = MdlMappingNoExecute; } // KeSaveExtendedProcessorState/KeRestoreExtendedProcessorState are available starting from Windows 7 if ((OsMajorVersion > 6) || (OsMajorVersion == 6 && OsMinorVersion >= 1)) { UNICODE_STRING saveFuncName, restoreFuncName; RtlInitUnicodeString(&saveFuncName, L"KeSaveExtendedProcessorState"); RtlInitUnicodeString(&restoreFuncName, L"KeRestoreExtendedProcessorState"); KeSaveExtendedProcessorStatePtr = (KeSaveExtendedProcessorStateFn) MmGetSystemRoutineAddress(&saveFuncName); KeRestoreExtendedProcessorStatePtr = (KeRestoreExtendedProcessorStateFn) MmGetSystemRoutineAddress(&restoreFuncName); } // Load dump filter if the main driver is already loaded if (NT_SUCCESS (TCDeviceIoControl (NT_ROOT_PREFIX, TC_IOCTL_GET_DRIVER_VERSION, NULL, 0, &version, sizeof (version)))) return DumpFilterEntry ((PFILTER_EXTENSION) DriverObject, (PFILTER_INITIALIZATION_DATA) RegistryPath); TCDriverObject = DriverObject; memset (VirtualVolumeDeviceObjects, 0, sizeof (VirtualVolumeDeviceObjects)); ReadRegistryConfigFlags (TRUE); EncryptionThreadPoolStart (EncryptionThreadPoolFreeCpuCountLimit); SelfTestsPassed = AutoTestAlgorithms(); // Enable device class filters and load boot arguments if the driver is set to start at system boot if (NT_SUCCESS (TCReadRegistryKey (RegistryPath, L"Start", &startKeyValue))) { if (startKeyValue->Type == REG_DWORD && *((uint32 *) startKeyValue->Data) == SERVICE_BOOT_START) { if (!SelfTestsPassed) { // in case of system encryption, if self-tests fail, disable all extended CPU // features and try again in order to workaround faulty configurations DisableCPUExtendedFeatures (); SelfTestsPassed = AutoTestAlgorithms(); // BUG CHECK if the self-tests still fail if (!SelfTestsPassed) TC_BUG_CHECK (STATUS_INVALID_PARAMETER); } LoadBootArguments(); VolumeClassFilterRegistered = IsVolumeClassFilterRegistered(); DriverObject->DriverExtension->AddDevice = DriverAddDevice; } TCfree (startKeyValue); } for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; ++i) { DriverObject->MajorFunction[i] = TCDispatchQueueIRP; } DriverObject->DriverUnload = TCUnloadDriver; return TCCreateRootDeviceObject (DriverObject); } NTSTATUS DriverAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo) { #if defined(DEBUG) || defined (DEBUG_TRACE) char nameInfoBuffer[128]; POBJECT_NAME_INFORMATION nameInfo = (POBJECT_NAME_INFORMATION) nameInfoBuffer; ULONG nameInfoSize; Dump ("AddDevice pdo=%p type=%x name=%ws\n", pdo, pdo->DeviceType, NT_SUCCESS (ObQueryNameString (pdo, nameInfo, sizeof (nameInfoBuffer), &nameInfoSize)) ? nameInfo->Name.Buffer : L"?"); #endif if (VolumeClassFilterRegistered && BootArgsValid && BootArgs.HiddenSystemPartitionStart != 0) { PWSTR interfaceLinks = NULL; if (NT_SUCCESS (IoGetDeviceInterfaces (&GUID_DEVINTERFACE_VOLUME, pdo, DEVICE_INTERFACE_INCLUDE_NONACTIVE, &interfaceLinks)) && interfaceLinks) { if (interfaceLinks[0] != UNICODE_NULL) { Dump ("Volume pdo=%p interface=%ws\n", pdo, interfaceLinks); ExFreePool (interfaceLinks); return VolumeFilterAddDevice (driverObject, pdo); } ExFreePool (interfaceLinks); } } return DriveFilterAddDevice (driverObject, pdo); } // Dumps a memory region to debug output void DumpMemory (void *mem, int size) { unsigned char str[20]; unsigned char *m = mem; int i,j; for (j = 0; j < size / 8; j++) { memset (str,0,sizeof str); for (i = 0; i < 8; i++) { if (m[i] > ' ' && m[i] <= '~') str[i]=m[i]; else str[i]='.'; } Dump ("0x%08p %02x %02x %02x %02x %02x %02x %02x %02x %s\n", m, m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], str); m+=8; } } BOOL IsAllZeroes (unsigned char* pbData, DWORD dwDataLen) { while (dwDataLen--) { if (*pbData) return FALSE; pbData++; } return TRUE; } BOOL ValidateIOBufferSize (PIRP irp, size_t requiredBufferSize, ValidateIOBufferSizeType type) { PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (irp); BOOL input = (type == ValidateInput || type == ValidateInputOutput); BOOL output = (type == ValidateOutput || type == ValidateInputOutput); if ((input && irpSp->Parameters.DeviceIoControl.InputBufferLength < requiredBufferSize) || (output && irpSp->Parameters.DeviceIoControl.OutputBufferLength < requiredBufferSize)) { Dump ("STATUS_BUFFER_TOO_SMALL ioctl=0x%x,%d in=%d out=%d reqsize=%d insize=%d outsize=%d\n", (int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16), (int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2), input, output, requiredBufferSize, irpSp->Parameters.DeviceIoControl.InputBufferLength, irpSp->Parameters.DeviceIoControl.OutputBufferLength); irp->IoStatus.Status = STATUS_BUFFER_TOO_SMALL; irp->IoStatus.Information = 0; return FALSE; } if (!input && output) memset (irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength); return TRUE; } PDEVICE_OBJECT GetVirtualVolumeDeviceObject (int driveNumber) { if (driveNumber < MIN_MOUNTED_VOLUME_DRIVE_NUMBER || driveNumber > MAX_MOUNTED_VOLUME_DRIVE_NUMBER) return NULL; return VirtualVolumeDeviceObjects[driveNumber]; } /* TCDispatchQueueIRP queues any IRP's so that they can be processed later by the thread -- or in some cases handles them immediately! */ NTSTATUS TCDispatchQueueIRP (PDEVICE_OBJECT DeviceObject, PIRP Irp) { PEXTENSION Extension = (PEXTENSION) DeviceObject->DeviceExtension; PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); NTSTATUS ntStatus; #if defined(_DEBUG) || defined (_DEBUG_TRACE) if (irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL && (Extension->bRootDevice || Extension->IsVolumeDevice)) { switch (irpSp->Parameters.DeviceIoControl.IoControlCode) { case TC_IOCTL_GET_MOUNTED_VOLUMES: case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: case TC_IOCTL_GET_PORTABLE_MODE_STATUS: case TC_IOCTL_SET_PORTABLE_MODE_STATUS: case TC_IOCTL_OPEN_TEST: case TC_IOCTL_GET_RESOLVED_SYMLINK: case TC_IOCTL_GET_DEVICE_REFCOUNT: case TC_IOCTL_GET_DRIVE_PARTITION_INFO: case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS: case TC_IOCTL_GET_WARNING_FLAGS: case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: case IOCTL_DISK_CHECK_VERIFY: break; default: Dump ("%ls (0x%x %d)\n", TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode), (int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16), (int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2)); } } #endif if (!Extension->bRootDevice) { // Drive filter IRP if (Extension->IsDriveFilterDevice) return DriveFilterDispatchIrp (DeviceObject, Irp); // Volume filter IRP if (Extension->IsVolumeFilterDevice) return VolumeFilterDispatchIrp (DeviceObject, Irp); } switch (irpSp->MajorFunction) { case IRP_MJ_CLOSE: case IRP_MJ_CREATE: case IRP_MJ_CLEANUP: return COMPLETE_IRP (DeviceObject, Irp, STATUS_SUCCESS, 0); case IRP_MJ_SHUTDOWN: if (Extension->bRootDevice) { Dump ("Driver shutting down\n"); DriverShuttingDown = TRUE; if (EncryptionSetupThread) while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES); if (DecoySystemWipeThread) while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES); OnShutdownPending(); } return COMPLETE_IRP (DeviceObject, Irp, STATUS_SUCCESS, 0); case IRP_MJ_FLUSH_BUFFERS: case IRP_MJ_READ: case IRP_MJ_WRITE: case IRP_MJ_DEVICE_CONTROL: if (Extension->bRootDevice) { if (irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL) { NTSTATUS status = KeWaitForMutexObject (&RootDeviceControlMutex, Executive, KernelMode, FALSE, NULL); if (!NT_SUCCESS (status)) return status; status = ProcessMainDeviceControlIrp (DeviceObject, Extension, Irp); KeReleaseMutex (&RootDeviceControlMutex, FALSE); return status; } break; } if (Extension->bShuttingDown) { Dump ("Device %d shutting down: STATUS_DELETE_PENDING\n", Extension->nDosDriveNo); return TCCompleteDiskIrp (Irp, STATUS_DELETE_PENDING, 0); } if (Extension->bRemovable && (DeviceObject->Flags & DO_VERIFY_VOLUME) && !(irpSp->Flags & SL_OVERRIDE_VERIFY_VOLUME) && irpSp->MajorFunction != IRP_MJ_FLUSH_BUFFERS) { Dump ("Removable device %d has DO_VERIFY_VOLUME flag: STATUS_DEVICE_NOT_READY\n", Extension->nDosDriveNo); return TCCompleteDiskIrp (Irp, STATUS_DEVICE_NOT_READY, 0); } switch (irpSp->MajorFunction) { case IRP_MJ_READ: case IRP_MJ_WRITE: ntStatus = EncryptedIoQueueAddIrp (&Extension->Queue, Irp); if (ntStatus != STATUS_PENDING) TCCompleteDiskIrp (Irp, ntStatus, 0); return ntStatus; case IRP_MJ_DEVICE_CONTROL: ntStatus = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); if (!NT_SUCCESS (ntStatus)) return TCCompleteIrp (Irp, ntStatus, 0); IoMarkIrpPending (Irp); ExInterlockedInsertTailList (&Extension->ListEntry, &Irp->Tail.Overlay.ListEntry, &Extension->ListSpinLock); KeReleaseSemaphore (&Extension->RequestSemaphore, IO_DISK_INCREMENT, 1, FALSE); return STATUS_PENDING; case IRP_MJ_FLUSH_BUFFERS: return TCCompleteDiskIrp (Irp, STATUS_SUCCESS, 0); } break; case IRP_MJ_PNP: if (!Extension->bRootDevice && Extension->IsVolumeDevice && irpSp->MinorFunction == IRP_MN_DEVICE_USAGE_NOTIFICATION && irpSp->Parameters.UsageNotification.Type == DeviceUsageTypePaging && irpSp->Parameters.UsageNotification.InPath) { PagingFileCreationPrevented = TRUE; return TCCompleteIrp (Irp, STATUS_UNSUCCESSFUL, 0); } break; } return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); } NTSTATUS TCCreateRootDeviceObject (PDRIVER_OBJECT DriverObject) { UNICODE_STRING Win32NameString, ntUnicodeString; WCHAR dosname[32], ntname[32]; PDEVICE_OBJECT DeviceObject; NTSTATUS ntStatus; BOOL *bRootExtension; Dump ("TCCreateRootDeviceObject BEGIN\n"); ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL); RtlStringCbCopyW (dosname, sizeof(dosname),(LPWSTR) DOS_ROOT_PREFIX); RtlStringCbCopyW (ntname, sizeof(ntname),(LPWSTR) NT_ROOT_PREFIX); RtlInitUnicodeString (&ntUnicodeString, ntname); RtlInitUnicodeString (&Win32NameString, dosname); Dump ("Creating root device nt=%ls dos=%ls\n", ntname, dosname); ntStatus = IoCreateDevice ( DriverObject, sizeof (BOOL), &ntUnicodeString, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &DeviceObject); if (!NT_SUCCESS (ntStatus)) { Dump ("TCCreateRootDeviceObject NTSTATUS = 0x%08x END\n", ntStatus); return ntStatus;/* Failed to create DeviceObject */ } DeviceObject->Flags |= DO_DIRECT_IO; DeviceObject->AlignmentRequirement = FILE_WORD_ALIGNMENT; /* Setup the device extension */ bRootExtension = (BOOL *) DeviceObject->DeviceExtension; *bRootExtension = TRUE; KeInitializeMutex (&RootDeviceControlMutex, 0); ntStatus = IoCreateSymbolicLink (&Win32NameString, &ntUnicodeString); if (!NT_SUCCESS (ntStatus)) { Dump ("TCCreateRootDeviceObject NTSTATUS = 0x%08x END\n", ntStatus); IoDeleteDevice (DeviceObject); return ntStatus; } IoRegisterShutdownNotification (DeviceObject); RootDeviceObject = DeviceObject; Dump ("TCCreateRootDeviceObject STATUS_SUCCESS END\n"); return STATUS_SUCCESS; } NTSTATUS TCCreateDeviceObject (PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT * ppDeviceObject, MOUNT_STRUCT * mount) { UNICODE_STRING ntUnicodeString; WCHAR ntname[32]; PEXTENSION Extension; NTSTATUS ntStatus; ULONG devChars = 0; #if defined (DEBUG) || defined (DEBUG_TRACE) WCHAR dosname[32]; #endif Dump ("TCCreateDeviceObject BEGIN\n"); ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL); TCGetNTNameFromNumber (ntname, sizeof(ntname),mount->nDosDriveNo); RtlInitUnicodeString (&ntUnicodeString, ntname); #if defined (DEBUG) || defined (DEBUG_TRACE) TCGetDosNameFromNumber (dosname, sizeof(dosname),mount->nDosDriveNo, DeviceNamespaceDefault); #endif devChars = FILE_DEVICE_SECURE_OPEN; devChars |= mount->bMountReadOnly ? FILE_READ_ONLY_DEVICE : 0; devChars |= mount->bMountRemovable ? FILE_REMOVABLE_MEDIA : 0; #if defined (DEBUG) || defined (DEBUG_TRACE) Dump ("Creating device nt=%ls dos=%ls\n", ntname, dosname); #endif ntStatus = IoCreateDevice ( DriverObject, /* Our Driver Object */ sizeof (EXTENSION), /* Size of state information */ &ntUnicodeString, /* Device name "\Device\Name" */ FILE_DEVICE_DISK, /* Device type */ devChars, /* Device characteristics */ FALSE, /* Exclusive device */ ppDeviceObject); /* Returned ptr to Device Object */ if (!NT_SUCCESS (ntStatus)) { Dump ("TCCreateDeviceObject NTSTATUS = 0x%08x END\n", ntStatus); return ntStatus;/* Failed to create DeviceObject */ } /* Initialize device object and extension. */ (*ppDeviceObject)->Flags |= DO_DIRECT_IO; (*ppDeviceObject)->StackSize += 6; // Reduce occurrence of NO_MORE_IRP_STACK_LOCATIONS bug check caused by buggy drivers /* Setup the device extension */ Extension = (PEXTENSION) (*ppDeviceObject)->DeviceExtension; memset (Extension, 0, sizeof (EXTENSION)); Extension->IsVolumeDevice = TRUE; Extension->nDosDriveNo = mount->nDosDriveNo; Extension->bRemovable = mount->bMountRemovable; Extension->PartitionInInactiveSysEncScope = mount->bPartitionInInactiveSysEncScope; Extension->SystemFavorite = mount->SystemFavorite; KeInitializeEvent (&Extension->keCreateEvent, SynchronizationEvent, FALSE); KeInitializeSemaphore (&Extension->RequestSemaphore, 0L, MAXLONG); KeInitializeSpinLock (&Extension->ListSpinLock); InitializeListHead (&Extension->ListEntry); IoInitializeRemoveLock (&Extension->Queue.RemoveLock, 'LRCV', 0, 0); VirtualVolumeDeviceObjects[mount->nDosDriveNo] = *ppDeviceObject; Dump ("TCCreateDeviceObject STATUS_SUCCESS END\n"); return STATUS_SUCCESS; } BOOL RootDeviceControlMutexAcquireNoWait () { NTSTATUS status; LARGE_INTEGER timeout; timeout.QuadPart = 0; status = KeWaitForMutexObject (&RootDeviceControlMutex, Executive, KernelMode, FALSE, &timeout); return NT_SUCCESS (status) && status != STATUS_TIMEOUT; } void RootDeviceControlMutexRelease () { KeReleaseMutex (&RootDeviceControlMutex, FALSE); } /* IOCTL_STORAGE_GET_DEVICE_NUMBER 0x002D1080 IOCTL_STORAGE_GET_HOTPLUG_INFO 0x002D0C14 IOCTL_STORAGE_QUERY_PROPERTY 0x002D1400 */ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp) { PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); switch (irpSp->Parameters.DeviceIoControl.IoControlCode) { case IOCTL_MOUNTDEV_QUERY_DEVICE_NAME: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_MOUNTDEV_QUERY_DEVICE_NAME)\n"); if (!ValidateIOBufferSize (Irp, sizeof (MOUNTDEV_NAME), ValidateOutput)) { Irp->IoStatus.Information = sizeof (MOUNTDEV_NAME); Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; } else { ULONG outLength; UNICODE_STRING ntUnicodeString; WCHAR ntName[256]; PMOUNTDEV_NAME outputBuffer = (PMOUNTDEV_NAME) Irp->AssociatedIrp.SystemBuffer; TCGetNTNameFromNumber (ntName, sizeof(ntName),Extension->nDosDriveNo); RtlInitUnicodeString (&ntUnicodeString, ntName); outputBuffer->NameLength = ntUnicodeString.Length; outLength = ntUnicodeString.Length + sizeof(USHORT); if (irpSp->Parameters.DeviceIoControl.OutputBufferLength < outLength) { Irp->IoStatus.Information = sizeof (MOUNTDEV_NAME); Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; break; } RtlCopyMemory ((PCHAR)outputBuffer->Name,ntUnicodeString.Buffer, ntUnicodeString.Length); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = outLength; Dump ("name = %ls\n",ntName); } break; case IOCTL_MOUNTDEV_QUERY_UNIQUE_ID: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_MOUNTDEV_QUERY_UNIQUE_ID)\n"); if (!ValidateIOBufferSize (Irp, sizeof (MOUNTDEV_UNIQUE_ID), ValidateOutput)) { Irp->IoStatus.Information = sizeof (MOUNTDEV_UNIQUE_ID); Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; } else { ULONG outLength; UCHAR volId[128], tmp[] = { 0,0 }; PMOUNTDEV_UNIQUE_ID outputBuffer = (PMOUNTDEV_UNIQUE_ID) Irp->AssociatedIrp.SystemBuffer; RtlStringCbCopyA (volId, sizeof(volId),TC_UNIQUE_ID_PREFIX); tmp[0] = 'A' + (UCHAR) Extension->nDosDriveNo; RtlStringCbCatA (volId, sizeof(volId),tmp); outputBuffer->UniqueIdLength = (USHORT) strlen (volId); outLength = (ULONG) (strlen (volId) + sizeof (USHORT)); if (irpSp->Parameters.DeviceIoControl.OutputBufferLength < outLength) { Irp->IoStatus.Information = sizeof (MOUNTDEV_UNIQUE_ID); Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; break; } RtlCopyMemory ((PCHAR)outputBuffer->UniqueId, volId, strlen (volId)); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = outLength; Dump ("id = %s\n",volId); } break; case IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME)\n"); { ULONG outLength; UNICODE_STRING ntUnicodeString; WCHAR ntName[256]; PMOUNTDEV_SUGGESTED_LINK_NAME outputBuffer = (PMOUNTDEV_SUGGESTED_LINK_NAME) Irp->AssociatedIrp.SystemBuffer; if (!ValidateIOBufferSize (Irp, sizeof (MOUNTDEV_SUGGESTED_LINK_NAME), ValidateOutput)) { Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; break; } TCGetDosNameFromNumber (ntName, sizeof(ntName),Extension->nDosDriveNo, DeviceNamespaceDefault); RtlInitUnicodeString (&ntUnicodeString, ntName); outLength = FIELD_OFFSET(MOUNTDEV_SUGGESTED_LINK_NAME,Name) + ntUnicodeString.Length; outputBuffer->UseOnlyIfThereAreNoOtherLinks = FALSE; outputBuffer->NameLength = ntUnicodeString.Length; if(irpSp->Parameters.DeviceIoControl.OutputBufferLength < outLength) { Irp->IoStatus.Information = sizeof (MOUNTDEV_SUGGESTED_LINK_NAME); Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; break; } RtlCopyMemory ((PCHAR)outputBuffer->Name,ntUnicodeString.Buffer, ntUnicodeString.Length); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = outLength; Dump ("link = %ls\n",ntName); } break; case IOCTL_DISK_GET_MEDIA_TYPES: case IOCTL_DISK_GET_DRIVE_GEOMETRY: case IOCTL_STORAGE_GET_MEDIA_TYPES: case IOCTL_DISK_UPDATE_DRIVE_SIZE: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_DRIVE_GEOMETRY)\n"); /* Return the drive geometry for the disk. Note that we return values which were made up to suit the disk size. */ if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY), ValidateOutput)) { PDISK_GEOMETRY outputBuffer = (PDISK_GEOMETRY) Irp->AssociatedIrp.SystemBuffer; outputBuffer->MediaType = Extension->bRemovable ? RemovableMedia : FixedMedia; outputBuffer->Cylinders.QuadPart = Extension->NumberOfCylinders; outputBuffer->TracksPerCylinder = Extension->TracksPerCylinder; outputBuffer->SectorsPerTrack = Extension->SectorsPerTrack; outputBuffer->BytesPerSector = Extension->BytesPerSector; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (DISK_GEOMETRY); } break; case IOCTL_DISK_GET_DRIVE_GEOMETRY_EX: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_DRIVE_GEOMETRY_EX)\n"); { ULONG minOutputSize = IsOSAtLeast (WIN_SERVER_2003)? sizeof (DISK_GEOMETRY_EX) : sizeof (DISK_GEOMETRY) + sizeof (LARGE_INTEGER); ULONG fullOutputSize = sizeof (DISK_GEOMETRY) + sizeof (LARGE_INTEGER) + sizeof (DISK_PARTITION_INFO) + sizeof (DISK_DETECTION_INFO); if (ValidateIOBufferSize (Irp, minOutputSize, ValidateOutput)) { PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); BOOL bFullBuffer = (irpSp->Parameters.DeviceIoControl.OutputBufferLength >= fullOutputSize)? TRUE : FALSE; PDISK_GEOMETRY_EX outputBuffer = (PDISK_GEOMETRY_EX) Irp->AssociatedIrp.SystemBuffer; outputBuffer->Geometry.MediaType = Extension->bRemovable ? RemovableMedia : FixedMedia; outputBuffer->Geometry.Cylinders.QuadPart = Extension->NumberOfCylinders; outputBuffer->Geometry.TracksPerCylinder = Extension->TracksPerCylinder; outputBuffer->Geometry.SectorsPerTrack = Extension->SectorsPerTrack; outputBuffer->Geometry.BytesPerSector = Extension->BytesPerSector; /* add one sector to DiskLength since our partition size is DiskLength and its offset if BytesPerSector */ outputBuffer->DiskSize.QuadPart = Extension->DiskLength + Extension->BytesPerSector; if (bFullBuffer) { PDISK_PARTITION_INFO pPartInfo = (PDISK_PARTITION_INFO)(((ULONG_PTR) outputBuffer) + sizeof (DISK_GEOMETRY) + sizeof (LARGE_INTEGER)); PDISK_DETECTION_INFO pDetectInfo = ((PDISK_DETECTION_INFO)((((ULONG_PTR) pPartInfo) + sizeof (DISK_PARTITION_INFO)))); pPartInfo->SizeOfPartitionInfo = sizeof (DISK_PARTITION_INFO); pPartInfo->PartitionStyle = PARTITION_STYLE_MBR; pPartInfo->Mbr.Signature = GetCrc32((unsigned char*) &(Extension->UniqueVolumeId), 4); pDetectInfo->SizeOfDetectInfo = sizeof (DISK_DETECTION_INFO); Irp->IoStatus.Information = fullOutputSize; } else { if (irpSp->Parameters.DeviceIoControl.OutputBufferLength >= sizeof (DISK_GEOMETRY_EX)) Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_EX); else Irp->IoStatus.Information = minOutputSize; } Irp->IoStatus.Status = STATUS_SUCCESS; } } break; case IOCTL_STORAGE_GET_MEDIA_TYPES_EX: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_GET_MEDIA_TYPES_EX)\n"); if (ValidateIOBufferSize (Irp, sizeof (GET_MEDIA_TYPES), ValidateOutput)) { PGET_MEDIA_TYPES outputBuffer = (PGET_MEDIA_TYPES) Irp->AssociatedIrp.SystemBuffer; PDEVICE_MEDIA_INFO mediaInfo = &outputBuffer->MediaInfo[0]; outputBuffer->DeviceType = FILE_DEVICE_DISK; outputBuffer->MediaInfoCount = 1; if (Extension->bRemovable) { mediaInfo->DeviceSpecific.RemovableDiskInfo.NumberMediaSides = 1; if (Extension->bReadOnly) mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaCharacteristics = (MEDIA_CURRENTLY_MOUNTED | MEDIA_READ_ONLY | MEDIA_WRITE_PROTECTED); else mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaCharacteristics = (MEDIA_CURRENTLY_MOUNTED | MEDIA_READ_WRITE); mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaType = (STORAGE_MEDIA_TYPE) RemovableMedia; mediaInfo->DeviceSpecific.RemovableDiskInfo.Cylinders.QuadPart = Extension->NumberOfCylinders; mediaInfo->DeviceSpecific.RemovableDiskInfo.TracksPerCylinder = Extension->TracksPerCylinder; mediaInfo->DeviceSpecific.RemovableDiskInfo.SectorsPerTrack = Extension->SectorsPerTrack; mediaInfo->DeviceSpecific.RemovableDiskInfo.BytesPerSector = Extension->BytesPerSector; } else { mediaInfo->DeviceSpecific.DiskInfo.NumberMediaSides = 1; if (Extension->bReadOnly) mediaInfo->DeviceSpecific.DiskInfo.MediaCharacteristics = (MEDIA_CURRENTLY_MOUNTED | MEDIA_READ_ONLY | MEDIA_WRITE_PROTECTED); else mediaInfo->DeviceSpecific.DiskInfo.MediaCharacteristics = (MEDIA_CURRENTLY_MOUNTED | MEDIA_READ_WRITE); mediaInfo->DeviceSpecific.DiskInfo.MediaType = (STORAGE_MEDIA_TYPE) FixedMedia; mediaInfo->DeviceSpecific.DiskInfo.Cylinders.QuadPart = Extension->NumberOfCylinders; mediaInfo->DeviceSpecific.DiskInfo.TracksPerCylinder = Extension->TracksPerCylinder; mediaInfo->DeviceSpecific.DiskInfo.SectorsPerTrack = Extension->SectorsPerTrack; mediaInfo->DeviceSpecific.DiskInfo.BytesPerSector = Extension->BytesPerSector; } Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (GET_MEDIA_TYPES); } break; case IOCTL_STORAGE_QUERY_PROPERTY: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_QUERY_PROPERTY)\n"); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; if (EnableExtendedIoctlSupport || Extension->TrimEnabled) { if (ValidateIOBufferSize (Irp, sizeof (STORAGE_PROPERTY_QUERY), ValidateInput)) { PSTORAGE_PROPERTY_QUERY pStoragePropQuery = (PSTORAGE_PROPERTY_QUERY) Irp->AssociatedIrp.SystemBuffer; STORAGE_QUERY_TYPE type = pStoragePropQuery->QueryType; Dump ("IOCTL_STORAGE_QUERY_PROPERTY - PropertyId = %d, type = %d, InputBufferLength = %d, OutputBufferLength = %d\n", pStoragePropQuery->PropertyId, type, (int) irpSp->Parameters.DeviceIoControl.InputBufferLength, (int) irpSp->Parameters.DeviceIoControl.OutputBufferLength); if (Extension->bRawDevice && (pStoragePropQuery->PropertyId == (STORAGE_PROPERTY_ID) StorageDeviceLBProvisioningProperty) ) { IO_STATUS_BLOCK IoStatus; Dump ("ProcessVolumeDeviceControlIrp: sending IOCTL_STORAGE_QUERY_PROPERTY (%d) to device\n", (int) pStoragePropQuery->PropertyId); Irp->IoStatus.Status = ZwDeviceIoControlFile ( Extension->hDeviceFile, NULL, NULL, NULL, &IoStatus, IOCTL_STORAGE_QUERY_PROPERTY, Irp->AssociatedIrp.SystemBuffer, irpSp->Parameters.DeviceIoControl.InputBufferLength, Irp->AssociatedIrp.SystemBuffer, irpSp->Parameters.DeviceIoControl.OutputBufferLength); Dump ("ProcessVolumeDeviceControlIrp: ZwDeviceIoControlFile returned 0x%.8X\n", (DWORD) Irp->IoStatus.Status); if (Irp->IoStatus.Status == STATUS_SUCCESS) { Irp->IoStatus.Status = IoStatus.Status; Irp->IoStatus.Information = IoStatus.Information; } } else if ( (pStoragePropQuery->PropertyId == StorageAccessAlignmentProperty) || (pStoragePropQuery->PropertyId == StorageDeviceProperty) || (pStoragePropQuery->PropertyId == StorageAdapterProperty) || (pStoragePropQuery->PropertyId == StorageDeviceSeekPenaltyProperty) || (pStoragePropQuery->PropertyId == StorageDeviceTrimProperty) ) { if (type == PropertyExistsQuery) { Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; } else if (type == PropertyStandardQuery) { ULONG descriptorSize; switch (pStoragePropQuery->PropertyId) { case StorageDeviceProperty: { Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceProperty\n"); /* Add 0x00 for NULL terminating string used as ProductId, ProductRevision, SerialNumber, VendorId */ descriptorSize = sizeof (STORAGE_DEVICE_DESCRIPTOR) + 1; if (ValidateIOBufferSize (Irp, descriptorSize, ValidateOutput)) { PSTORAGE_DEVICE_DESCRIPTOR outputBuffer = (PSTORAGE_DEVICE_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; outputBuffer->Version = sizeof(STORAGE_DEVICE_DESCRIPTOR); outputBuffer->Size = descriptorSize; outputBuffer->DeviceType = FILE_DEVICE_DISK; outputBuffer->RemovableMedia = Extension->bRemovable? TRUE : FALSE; outputBuffer->ProductIdOffset = sizeof (STORAGE_DEVICE_DESCRIPTOR); outputBuffer->SerialNumberOffset = sizeof (STORAGE_DEVICE_DESCRIPTOR); outputBuffer->ProductRevisionOffset = sizeof (STORAGE_DEVICE_DESCRIPTOR); outputBuffer->VendorIdOffset = sizeof (STORAGE_DEVICE_DESCRIPTOR); outputBuffer->BusType = BusTypeVirtual; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = descriptorSize; } else if (irpSp->Parameters.DeviceIoControl.OutputBufferLength == sizeof (STORAGE_DESCRIPTOR_HEADER)) { PSTORAGE_DESCRIPTOR_HEADER outputBuffer = (PSTORAGE_DESCRIPTOR_HEADER) Irp->AssociatedIrp.SystemBuffer; outputBuffer->Version = sizeof(STORAGE_DEVICE_DESCRIPTOR); outputBuffer->Size = descriptorSize; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (STORAGE_DESCRIPTOR_HEADER); } } break; case StorageAdapterProperty: { Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageAdapterProperty\n"); descriptorSize = sizeof (STORAGE_ADAPTER_DESCRIPTOR); if (ValidateIOBufferSize (Irp, descriptorSize, ValidateOutput)) { PSTORAGE_ADAPTER_DESCRIPTOR outputBuffer = (PSTORAGE_ADAPTER_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; outputBuffer->Version = sizeof(STORAGE_ADAPTER_DESCRIPTOR); outputBuffer->Size = descriptorSize; outputBuffer->MaximumTransferLength = Extension->HostMaximumTransferLength; outputBuffer->MaximumPhysicalPages = Extension->HostMaximumPhysicalPages; outputBuffer->AlignmentMask = Extension->HostAlignmentMask; outputBuffer->BusType = BusTypeVirtual; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = descriptorSize; } else if (irpSp->Parameters.DeviceIoControl.OutputBufferLength == sizeof (STORAGE_DESCRIPTOR_HEADER)) { PSTORAGE_DESCRIPTOR_HEADER outputBuffer = (PSTORAGE_DESCRIPTOR_HEADER) Irp->AssociatedIrp.SystemBuffer; outputBuffer->Version = sizeof(STORAGE_ADAPTER_DESCRIPTOR); outputBuffer->Size = descriptorSize; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (STORAGE_DESCRIPTOR_HEADER); } } break; case StorageAccessAlignmentProperty: { Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageAccessAlignmentProperty\n"); if (ValidateIOBufferSize (Irp, sizeof (STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR), ValidateOutput)) { PSTORAGE_ACCESS_ALIGNMENT_DESCRIPTOR outputBuffer = (PSTORAGE_ACCESS_ALIGNMENT_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; outputBuffer->Version = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR); outputBuffer->Size = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR); outputBuffer->BytesPerLogicalSector = Extension->BytesPerSector; outputBuffer->BytesPerPhysicalSector = Extension->HostBytesPerPhysicalSector; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR); } else if (irpSp->Parameters.DeviceIoControl.OutputBufferLength == sizeof (STORAGE_DESCRIPTOR_HEADER)) { PSTORAGE_DESCRIPTOR_HEADER outputBuffer = (PSTORAGE_DESCRIPTOR_HEADER) Irp->AssociatedIrp.SystemBuffer; outputBuffer->Version = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR); outputBuffer->Size = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (STORAGE_DESCRIPTOR_HEADER); } } break; case StorageDeviceSeekPenaltyProperty: { Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceSeekPenaltyProperty\n"); if (ValidateIOBufferSize (Irp, sizeof (DEVICE_SEEK_PENALTY_DESCRIPTOR), ValidateOutput)) { PDEVICE_SEEK_PENALTY_DESCRIPTOR outputBuffer = (PDEVICE_SEEK_PENALTY_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceSeekPenaltyProperty: set IncursSeekPenalty to %s\n", Extension->IncursSeekPenalty? "TRUE" : "FALSE"); outputBuffer->Version = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR); outputBuffer->Size = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR); outputBuffer->IncursSeekPenalty = (BOOLEAN) Extension->IncursSeekPenalty; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (DEVICE_SEEK_PENALTY_DESCRIPTOR); } else if (irpSp->Parameters.DeviceIoControl.OutputBufferLength == sizeof (STORAGE_DESCRIPTOR_HEADER)) { PSTORAGE_DESCRIPTOR_HEADER outputBuffer = (PSTORAGE_DESCRIPTOR_HEADER) Irp->AssociatedIrp.SystemBuffer; outputBuffer->Version = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR); outputBuffer->Size = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (STORAGE_DESCRIPTOR_HEADER); } } break; case StorageDeviceTrimProperty: { Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceTrimProperty\n"); if (ValidateIOBufferSize (Irp, sizeof (DEVICE_TRIM_DESCRIPTOR), ValidateOutput)) { PDEVICE_TRIM_DESCRIPTOR outputBuffer = (PDEVICE_TRIM_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceTrimProperty: set TrimEnabled to %s\n", Extension->TrimEnabled? "TRUE" : "FALSE"); outputBuffer->Version = sizeof(DEVICE_TRIM_DESCRIPTOR); outputBuffer->Size = sizeof(DEVICE_TRIM_DESCRIPTOR); outputBuffer->TrimEnabled = (BOOLEAN) Extension->TrimEnabled; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (DEVICE_TRIM_DESCRIPTOR); } else if (irpSp->Parameters.DeviceIoControl.OutputBufferLength == sizeof (STORAGE_DESCRIPTOR_HEADER)) { PSTORAGE_DESCRIPTOR_HEADER outputBuffer = (PSTORAGE_DESCRIPTOR_HEADER) Irp->AssociatedIrp.SystemBuffer; outputBuffer->Version = sizeof(DEVICE_TRIM_DESCRIPTOR); outputBuffer->Size = sizeof(DEVICE_TRIM_DESCRIPTOR); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (STORAGE_DESCRIPTOR_HEADER); } } break; } } } } } break; case IOCTL_DISK_GET_PARTITION_INFO: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_PARTITION_INFO)\n"); if (ValidateIOBufferSize (Irp, sizeof (PARTITION_INFORMATION), ValidateOutput)) { PPARTITION_INFORMATION outputBuffer = (PPARTITION_INFORMATION) Irp->AssociatedIrp.SystemBuffer; outputBuffer->PartitionType = Extension->PartitionType; outputBuffer->BootIndicator = FALSE; outputBuffer->RecognizedPartition = TRUE; outputBuffer->RewritePartition = FALSE; outputBuffer->StartingOffset.QuadPart = Extension->BytesPerSector; outputBuffer->PartitionLength.QuadPart= Extension->DiskLength; outputBuffer->PartitionNumber = 1; outputBuffer->HiddenSectors = 0; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION); } break; case IOCTL_DISK_GET_PARTITION_INFO_EX: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_PARTITION_INFO_EX)\n"); if (ValidateIOBufferSize (Irp, sizeof (PARTITION_INFORMATION_EX), ValidateOutput)) { PPARTITION_INFORMATION_EX outputBuffer = (PPARTITION_INFORMATION_EX) Irp->AssociatedIrp.SystemBuffer; outputBuffer->PartitionStyle = PARTITION_STYLE_MBR; outputBuffer->RewritePartition = FALSE; outputBuffer->StartingOffset.QuadPart = Extension->BytesPerSector; outputBuffer->PartitionLength.QuadPart= Extension->DiskLength; outputBuffer->PartitionNumber = 1; outputBuffer->Mbr.PartitionType = Extension->PartitionType; outputBuffer->Mbr.BootIndicator = FALSE; outputBuffer->Mbr.RecognizedPartition = TRUE; outputBuffer->Mbr.HiddenSectors = 0; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION_EX); } break; case IOCTL_DISK_GET_DRIVE_LAYOUT: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_DRIVE_LAYOUT)\n"); if (ValidateIOBufferSize (Irp, sizeof (DRIVE_LAYOUT_INFORMATION), ValidateOutput)) { PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); BOOL bFullBuffer = (irpSp->Parameters.DeviceIoControl.OutputBufferLength >= (sizeof (DRIVE_LAYOUT_INFORMATION) + 3*sizeof(PARTITION_INFORMATION)))? TRUE : FALSE; PDRIVE_LAYOUT_INFORMATION outputBuffer = (PDRIVE_LAYOUT_INFORMATION) Irp->AssociatedIrp.SystemBuffer; outputBuffer->PartitionCount = bFullBuffer? 4 : 1; outputBuffer->Signature = GetCrc32((unsigned char*) &(Extension->UniqueVolumeId), 4); outputBuffer->PartitionEntry->PartitionType = Extension->PartitionType; outputBuffer->PartitionEntry->BootIndicator = FALSE; outputBuffer->PartitionEntry->RecognizedPartition = TRUE; outputBuffer->PartitionEntry->RewritePartition = FALSE; outputBuffer->PartitionEntry->StartingOffset.QuadPart = Extension->BytesPerSector; outputBuffer->PartitionEntry->PartitionLength.QuadPart = Extension->DiskLength; outputBuffer->PartitionEntry->PartitionNumber = 1; outputBuffer->PartitionEntry->HiddenSectors = 0; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (DRIVE_LAYOUT_INFORMATION); if (bFullBuffer) { Irp->IoStatus.Information += 3*sizeof(PARTITION_INFORMATION); memset (((BYTE*) Irp->AssociatedIrp.SystemBuffer) + sizeof (DRIVE_LAYOUT_INFORMATION), 0, 3*sizeof(PARTITION_INFORMATION)); } } break; case IOCTL_DISK_GET_DRIVE_LAYOUT_EX: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_DRIVE_LAYOUT_EX)\n"); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; if (EnableExtendedIoctlSupport) { if (ValidateIOBufferSize (Irp, sizeof (DRIVE_LAYOUT_INFORMATION_EX), ValidateOutput)) { PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); BOOL bFullBuffer = (irpSp->Parameters.DeviceIoControl.OutputBufferLength >= (sizeof (DRIVE_LAYOUT_INFORMATION_EX) + 3*sizeof(PARTITION_INFORMATION_EX)))? TRUE : FALSE; PDRIVE_LAYOUT_INFORMATION_EX outputBuffer = (PDRIVE_LAYOUT_INFORMATION_EX) Irp->AssociatedIrp.SystemBuffer; outputBuffer->PartitionCount = bFullBuffer? 4 : 1; outputBuffer->PartitionStyle = PARTITION_STYLE_MBR; outputBuffer->Mbr.Signature = GetCrc32((unsigned char*) &(Extension->UniqueVolumeId), 4); outputBuffer->PartitionEntry->PartitionStyle = PARTITION_STYLE_MBR; outputBuffer->PartitionEntry->Mbr.BootIndicator = FALSE; outputBuffer->PartitionEntry->Mbr.RecognizedPartition = TRUE; outputBuffer->PartitionEntry->RewritePartition = FALSE; outputBuffer->PartitionEntry->StartingOffset.QuadPart = Extension->BytesPerSector; outputBuffer->PartitionEntry->PartitionLength.QuadPart = Extension->DiskLength; outputBuffer->PartitionEntry->PartitionNumber = 1; outputBuffer->PartitionEntry->Mbr.HiddenSectors = 0; outputBuffer->PartitionEntry->Mbr.PartitionType = Extension->PartitionType; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (DRIVE_LAYOUT_INFORMATION_EX); if (bFullBuffer) { Irp->IoStatus.Information += 3*sizeof(PARTITION_INFORMATION_EX); } } } break; case IOCTL_DISK_GET_LENGTH_INFO: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_LENGTH_INFO)\n"); if (!ValidateIOBufferSize (Irp, sizeof (GET_LENGTH_INFORMATION), ValidateOutput)) { Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; Irp->IoStatus.Information = sizeof (GET_LENGTH_INFORMATION); } else { PGET_LENGTH_INFORMATION outputBuffer = (PGET_LENGTH_INFORMATION) Irp->AssociatedIrp.SystemBuffer; outputBuffer->Length.QuadPart = Extension->DiskLength; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (GET_LENGTH_INFORMATION); } break; case IOCTL_DISK_VERIFY: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_VERIFY)\n"); if (ValidateIOBufferSize (Irp, sizeof (VERIFY_INFORMATION), ValidateInput)) { HRESULT hResult; ULONGLONG ullStartingOffset, ullNewOffset, ullEndOffset; PVERIFY_INFORMATION pVerifyInformation; pVerifyInformation = (PVERIFY_INFORMATION) Irp->AssociatedIrp.SystemBuffer; ullStartingOffset = (ULONGLONG) pVerifyInformation->StartingOffset.QuadPart; hResult = ULongLongAdd(ullStartingOffset, (ULONGLONG) Extension->cryptoInfo->hiddenVolume ? Extension->cryptoInfo->hiddenVolumeOffset : Extension->cryptoInfo->volDataAreaOffset, &ullNewOffset); if (hResult != S_OK) Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; else if (S_OK != ULongLongAdd(ullStartingOffset, (ULONGLONG) pVerifyInformation->Length, &ullEndOffset)) Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; else if (ullEndOffset > (ULONGLONG) Extension->DiskLength) Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; else { IO_STATUS_BLOCK ioStatus; PVOID buffer = TCalloc (max (pVerifyInformation->Length, PAGE_SIZE)); if (!buffer) { Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; } else { LARGE_INTEGER offset = pVerifyInformation->StartingOffset; offset.QuadPart = ullNewOffset; Irp->IoStatus.Status = ZwReadFile (Extension->hDeviceFile, NULL, NULL, NULL, &ioStatus, buffer, pVerifyInformation->Length, &offset, NULL); TCfree (buffer); if (NT_SUCCESS (Irp->IoStatus.Status) && ioStatus.Information != pVerifyInformation->Length) Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; } } Irp->IoStatus.Information = 0; } break; case IOCTL_DISK_CHECK_VERIFY: case IOCTL_STORAGE_CHECK_VERIFY: case IOCTL_STORAGE_CHECK_VERIFY2: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_CHECK_VERIFY)\n"); { Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; if (irpSp->Parameters.DeviceIoControl.OutputBufferLength >= sizeof (ULONG)) { *((ULONG *) Irp->AssociatedIrp.SystemBuffer) = 0; Irp->IoStatus.Information = sizeof (ULONG); } } break; case IOCTL_DISK_IS_WRITABLE: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_IS_WRITABLE)\n"); { if (Extension->bReadOnly) Irp->IoStatus.Status = STATUS_MEDIA_WRITE_PROTECTED; else Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; } break; case IOCTL_VOLUME_ONLINE: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_VOLUME_ONLINE)\n"); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; break; case IOCTL_VOLUME_POST_ONLINE: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_VOLUME_POST_ONLINE)\n"); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; if (EnableExtendedIoctlSupport) { Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; } break; case IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS)\n"); // Vista's, Windows 8.1 and later filesystem defragmenter fails if IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS does not succeed. if (!(OsMajorVersion == 6 && OsMinorVersion == 0) && !(IsOSAtLeast (WIN_8_1) && AllowWindowsDefrag && Extension->bRawDevice) ) { Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; } else if (ValidateIOBufferSize (Irp, sizeof (VOLUME_DISK_EXTENTS), ValidateOutput)) { VOLUME_DISK_EXTENTS *extents = (VOLUME_DISK_EXTENTS *) Irp->AssociatedIrp.SystemBuffer; if (IsOSAtLeast (WIN_8_1)) { // Windows 10 filesystem defragmenter works only if we report an extent with a real disk number // So in the case of a VeraCrypt disk based volume, we use the disk number // of the underlaying physical disk and we report a single extent extents->NumberOfDiskExtents = 1; extents->Extents[0].DiskNumber = Extension->DeviceNumber; extents->Extents[0].StartingOffset.QuadPart = Extension->BytesPerSector; extents->Extents[0].ExtentLength.QuadPart = Extension->DiskLength; } else { // Vista: No extent data can be returned as this is not a physical drive. memset (extents, 0, sizeof (*extents)); extents->NumberOfDiskExtents = 0; } Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (*extents); } break; case IOCTL_STORAGE_READ_CAPACITY: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_READ_CAPACITY)\n"); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; if (EnableExtendedIoctlSupport) { if (ValidateIOBufferSize (Irp, sizeof (STORAGE_READ_CAPACITY), ValidateOutput)) { STORAGE_READ_CAPACITY *capacity = (STORAGE_READ_CAPACITY *) Irp->AssociatedIrp.SystemBuffer; capacity->Version = sizeof (STORAGE_READ_CAPACITY); capacity->Size = sizeof (STORAGE_READ_CAPACITY); capacity->BlockLength = Extension->BytesPerSector; capacity->NumberOfBlocks.QuadPart = (Extension->DiskLength / Extension->BytesPerSector) + 1; capacity->DiskLength.QuadPart = Extension->DiskLength + Extension->BytesPerSector; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (STORAGE_READ_CAPACITY); } } break; /*case IOCTL_STORAGE_GET_DEVICE_NUMBER: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_GET_DEVICE_NUMBER)\n"); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; if (EnableExtendedIoctlSupport) { if (ValidateIOBufferSize (Irp, sizeof (STORAGE_DEVICE_NUMBER), ValidateOutput)) { STORAGE_DEVICE_NUMBER *storage = (STORAGE_DEVICE_NUMBER *) Irp->AssociatedIrp.SystemBuffer; storage->DeviceType = FILE_DEVICE_DISK; storage->DeviceNumber = (ULONG) -1; storage->PartitionNumber = 1; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (STORAGE_DEVICE_NUMBER); } } break;*/ case IOCTL_STORAGE_GET_HOTPLUG_INFO: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_GET_HOTPLUG_INFO)\n"); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; if (EnableExtendedIoctlSupport) { if (ValidateIOBufferSize (Irp, sizeof (STORAGE_HOTPLUG_INFO), ValidateOutput)) { STORAGE_HOTPLUG_INFO *info = (STORAGE_HOTPLUG_INFO *) Irp->AssociatedIrp.SystemBuffer; info->Size = sizeof (STORAGE_HOTPLUG_INFO); info->MediaRemovable = Extension->bRemovable? TRUE : FALSE; info->MediaHotplug = FALSE; info->DeviceHotplug = FALSE; info->WriteCacheEnableOverride = FALSE; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (STORAGE_HOTPLUG_INFO); } } break; case IOCTL_VOLUME_IS_DYNAMIC: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_VOLUME_IS_DYNAMIC)\n"); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; if (EnableExtendedIoctlSupport) { if (ValidateIOBufferSize (Irp, sizeof (BOOLEAN), ValidateOutput)) { BOOLEAN *pbDynamic = (BOOLEAN*) Irp->AssociatedIrp.SystemBuffer; *pbDynamic = FALSE; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (BOOLEAN); } } break; case IOCTL_DISK_IS_CLUSTERED: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_IS_CLUSTERED)\n"); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; if (EnableExtendedIoctlSupport) { if (ValidateIOBufferSize (Irp, sizeof (BOOLEAN), ValidateOutput)) { BOOLEAN *pbIsClustered = (BOOLEAN*) Irp->AssociatedIrp.SystemBuffer; *pbIsClustered = FALSE; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (BOOLEAN); } } break; case IOCTL_VOLUME_GET_GPT_ATTRIBUTES: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_VOLUME_GET_GPT_ATTRIBUTES)\n"); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; if (EnableExtendedIoctlSupport) { if (ValidateIOBufferSize (Irp, sizeof (VOLUME_GET_GPT_ATTRIBUTES_INFORMATION), ValidateOutput)) { VOLUME_GET_GPT_ATTRIBUTES_INFORMATION *pGptAttr = (VOLUME_GET_GPT_ATTRIBUTES_INFORMATION*) Irp->AssociatedIrp.SystemBuffer; pGptAttr->GptAttributes = 0; // we are MBR not GPT Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (VOLUME_GET_GPT_ATTRIBUTES_INFORMATION); } } break; case IOCTL_UNKNOWN_WINDOWS10_EFS_ACCESS: // This undocumented IOCTL is sent when handling EFS data // We must return success otherwise EFS operations fail Dump ("ProcessVolumeDeviceControlIrp (unknown IOCTL 0x%.8X, OutputBufferLength = %d). Returning fake success\n", irpSp->Parameters.DeviceIoControl.IoControlCode, (int) irpSp->Parameters.DeviceIoControl.OutputBufferLength); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; break; case IOCTL_DISK_UPDATE_PROPERTIES: Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_SUCCESS for IOCTL_DISK_UPDATE_PROPERTIES\n"); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; break; case IOCTL_DISK_MEDIA_REMOVAL: case IOCTL_STORAGE_MEDIA_REMOVAL: Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_SUCCESS for %ls\n", TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode)); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; break; case IOCTL_DISK_GET_CLUSTER_INFO: Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_NOT_SUPPORTED for %ls\n", TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode)); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; if (EnableExtendedIoctlSupport) { Irp->IoStatus.Status = STATUS_NOT_SUPPORTED; Irp->IoStatus.Information = 0; } break; case IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES\n"); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; if (Extension->bRawDevice && Extension->TrimEnabled) { if (ValidateIOBufferSize (Irp, sizeof (DEVICE_MANAGE_DATA_SET_ATTRIBUTES), ValidateInput)) { PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); DWORD inputLength = irpSp->Parameters.DeviceIoControl.InputBufferLength; PDEVICE_MANAGE_DATA_SET_ATTRIBUTES pInputAttrs = (PDEVICE_MANAGE_DATA_SET_ATTRIBUTES) Irp->AssociatedIrp.SystemBuffer; DEVICE_DATA_MANAGEMENT_SET_ACTION action = pInputAttrs->Action; BOOL bEntireSet = pInputAttrs->Flags & DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE? TRUE : FALSE; ULONGLONG minSizedataSet = (ULONGLONG) pInputAttrs->DataSetRangesOffset + (ULONGLONG) pInputAttrs->DataSetRangesLength; ULONGLONG minSizeParameter = (ULONGLONG) pInputAttrs->ParameterBlockOffset + (ULONGLONG) pInputAttrs->ParameterBlockLength; ULONGLONG minSizeGeneric = sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES) + (ULONGLONG) pInputAttrs->ParameterBlockLength + (ULONGLONG) pInputAttrs->DataSetRangesLength; PDEVICE_MANAGE_DATA_SET_ATTRIBUTES pNewSetAttrs = NULL; ULONG ulNewInputLength = 0; BOOL bForwardIoctl = FALSE; if (inputLength >= minSizeGeneric && inputLength >= minSizedataSet && inputLength >= minSizeParameter) { if (bEntireSet) { if (minSizedataSet) { Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE set but data set range specified=> Error.\n"); Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; } else { DWORD dwDataSetOffset = ALIGN_VALUE (inputLength, sizeof(DEVICE_DATA_SET_RANGE)); DWORD dwDataSetLength = sizeof(DEVICE_DATA_SET_RANGE); Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE set. Setting data range to all volume.\n"); ulNewInputLength = dwDataSetOffset + dwDataSetLength; pNewSetAttrs = (PDEVICE_MANAGE_DATA_SET_ATTRIBUTES) TCalloc (ulNewInputLength); if (pNewSetAttrs) { PDEVICE_DATA_SET_RANGE pRange = (PDEVICE_DATA_SET_RANGE) (((unsigned char*) pNewSetAttrs) + dwDataSetOffset); memcpy (pNewSetAttrs, pInputAttrs, inputLength); pRange->StartingOffset = (ULONGLONG) Extension->cryptoInfo->hiddenVolume ? Extension->cryptoInfo->hiddenVolumeOffset : Extension->cryptoInfo->volDataAreaOffset; pRange->LengthInBytes = Extension->DiskLength; pNewSetAttrs->Size = sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES); pNewSetAttrs->Action = action; pNewSetAttrs->Flags = pInputAttrs->Flags & (~DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE); pNewSetAttrs->ParameterBlockOffset = pInputAttrs->ParameterBlockOffset; pNewSetAttrs->ParameterBlockLength = pInputAttrs->ParameterBlockLength; pNewSetAttrs->DataSetRangesOffset = dwDataSetOffset; pNewSetAttrs->DataSetRangesLength = dwDataSetLength; bForwardIoctl = TRUE; } else { Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - Failed to allocate memory.\n"); Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; Irp->IoStatus.Information = 0; } } } else { Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - creating new data set range from input range.\n"); ulNewInputLength = inputLength; pNewSetAttrs = (PDEVICE_MANAGE_DATA_SET_ATTRIBUTES) TCalloc (inputLength); if (pNewSetAttrs) { PDEVICE_DATA_SET_RANGE pNewRanges = (PDEVICE_DATA_SET_RANGE) (((unsigned char*) pNewSetAttrs) + pInputAttrs->DataSetRangesOffset); PDEVICE_DATA_SET_RANGE pInputRanges = (PDEVICE_DATA_SET_RANGE) (((unsigned char*) pInputAttrs) + pInputAttrs->DataSetRangesOffset); DWORD dwInputRangesCount = 0, dwNewRangesCount = 0, i; ULONGLONG ullStartingOffset, ullNewOffset, ullEndOffset; HRESULT hResult; memcpy (pNewSetAttrs, pInputAttrs, inputLength); dwInputRangesCount = pInputAttrs->DataSetRangesLength / sizeof(DEVICE_DATA_SET_RANGE); for (i = 0; i < dwInputRangesCount; i++) { ullStartingOffset = (ULONGLONG) pInputRanges[i].StartingOffset; hResult = ULongLongAdd(ullStartingOffset, (ULONGLONG) Extension->cryptoInfo->hiddenVolume ? Extension->cryptoInfo->hiddenVolumeOffset : Extension->cryptoInfo->volDataAreaOffset, &ullNewOffset); if (hResult != S_OK) continue; else if (S_OK != ULongLongAdd(ullStartingOffset, (ULONGLONG) pInputRanges[i].LengthInBytes, &ullEndOffset)) continue; else if (ullEndOffset > (ULONGLONG) Extension->DiskLength) continue; else if (ullNewOffset > 0) { pNewRanges[dwNewRangesCount].StartingOffset = (LONGLONG) ullNewOffset; pNewRanges[dwNewRangesCount].LengthInBytes = pInputRanges[i].LengthInBytes; dwNewRangesCount++; } } Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - %d valid range processed from %d range in input.\n", (int) dwNewRangesCount, (int) dwInputRangesCount); pNewSetAttrs->DataSetRangesLength = dwNewRangesCount * sizeof (DEVICE_DATA_SET_RANGE); bForwardIoctl = TRUE; } else { Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - Failed to allocate memory.\n"); Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; Irp->IoStatus.Information = 0; } } } else { Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - buffer containing DEVICE_MANAGE_DATA_SET_ATTRIBUTES has invalid length.\n"); Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; } if (bForwardIoctl) { if (action == DeviceDsmAction_Trim) { Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_Trim.\n"); if (Extension->cryptoInfo->hiddenVolume || !AllowTrimCommand) { Dump ("ProcessVolumeDeviceControlIrp: TRIM command filtered\n"); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; } else { IO_STATUS_BLOCK IoStatus; Dump ("ProcessVolumeDeviceControlIrp: sending TRIM to device\n"); Irp->IoStatus.Status = ZwDeviceIoControlFile ( Extension->hDeviceFile, NULL, NULL, NULL, &IoStatus, IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES, (PVOID) pNewSetAttrs, ulNewInputLength, NULL, 0); Dump ("ProcessVolumeDeviceControlIrp: ZwDeviceIoControlFile returned 0x%.8X\n", (DWORD) Irp->IoStatus.Status); if (Irp->IoStatus.Status == STATUS_SUCCESS) { Irp->IoStatus.Status = IoStatus.Status; Irp->IoStatus.Information = IoStatus.Information; } else Irp->IoStatus.Information = 0; } } else { switch (action) { case DeviceDsmAction_Notification: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_Notification\n"); break; case DeviceDsmAction_OffloadRead: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_OffloadRead\n"); break; case DeviceDsmAction_OffloadWrite: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_OffloadWrite\n"); break; case DeviceDsmAction_Allocation: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_Allocation\n"); break; case DeviceDsmAction_Scrub: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_Scrub\n"); break; case DeviceDsmAction_DrtQuery: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_DrtQuery\n"); break; case DeviceDsmAction_DrtClear: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_DrtClear\n"); break; case DeviceDsmAction_DrtDisable: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_DrtDisable\n"); break; default: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - unknown action %d\n", (int) action); break; } } } if (pNewSetAttrs) TCfree (pNewSetAttrs); } } #if defined (DEBUG) || defined (DEBUG_TRACE) else Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_INVALID_DEVICE_REQUEST for IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES\n"); #endif break; case IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT: case IOCTL_VOLUME_QUERY_ALLOCATION_HINT: case FT_BALANCED_READ_MODE: case IOCTL_STORAGE_GET_DEVICE_NUMBER: case IOCTL_MOUNTDEV_LINK_CREATED: Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_INVALID_DEVICE_REQUEST for %ls\n", TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode)); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; break; default: Dump ("ProcessVolumeDeviceControlIrp (unknown code 0x%.8X)\n", irpSp->Parameters.DeviceIoControl.IoControlCode); return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); } #if defined(DEBUG) || defined (DEBG_TRACE) if (!NT_SUCCESS (Irp->IoStatus.Status)) { Dump ("IOCTL error 0x%08x (0x%x %d)\n", Irp->IoStatus.Status, (int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16), (int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2)); } #endif return TCCompleteDiskIrp (Irp, Irp->IoStatus.Status, Irp->IoStatus.Information); } NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp) { PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); NTSTATUS ntStatus; switch (irpSp->Parameters.DeviceIoControl.IoControlCode) { case TC_IOCTL_GET_DRIVER_VERSION: case TC_IOCTL_LEGACY_GET_DRIVER_VERSION: if (ValidateIOBufferSize (Irp, sizeof (LONG), ValidateOutput)) { LONG tmp = VERSION_NUM; memcpy (Irp->AssociatedIrp.SystemBuffer, &tmp, 4); Irp->IoStatus.Information = sizeof (LONG); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_GET_DEVICE_REFCOUNT: if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) { *(int *) Irp->AssociatedIrp.SystemBuffer = DeviceObject->ReferenceCount; Irp->IoStatus.Information = sizeof (int); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED: if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) { LONG deviceObjectCount = 0; *(int *) Irp->AssociatedIrp.SystemBuffer = DriverUnloadDisabled; if (IoEnumerateDeviceObjectList (TCDriverObject, NULL, 0, &deviceObjectCount) == STATUS_BUFFER_TOO_SMALL && deviceObjectCount > 1) *(int *) Irp->AssociatedIrp.SystemBuffer = TRUE; Irp->IoStatus.Information = sizeof (int); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_IS_ANY_VOLUME_MOUNTED: if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) { int drive; *(int *) Irp->AssociatedIrp.SystemBuffer = 0; for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) { if (GetVirtualVolumeDeviceObject (drive)) { *(int *) Irp->AssociatedIrp.SystemBuffer = 1; break; } } if (IsBootDriveMounted()) *(int *) Irp->AssociatedIrp.SystemBuffer = 1; Irp->IoStatus.Information = sizeof (int); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_OPEN_TEST: { OPEN_TEST_STRUCT *opentest = (OPEN_TEST_STRUCT *) Irp->AssociatedIrp.SystemBuffer; OBJECT_ATTRIBUTES ObjectAttributes; HANDLE NtFileHandle; UNICODE_STRING FullFileName; IO_STATUS_BLOCK IoStatus; LARGE_INTEGER offset; ACCESS_MASK access = FILE_READ_ATTRIBUTES; if (!ValidateIOBufferSize (Irp, sizeof (OPEN_TEST_STRUCT), ValidateInputOutput)) break; EnsureNullTerminatedString (opentest->wszFileName, sizeof (opentest->wszFileName)); RtlInitUnicodeString (&FullFileName, opentest->wszFileName); InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bComputeVolumeIDs) access |= FILE_READ_DATA; ntStatus = ZwCreateFile (&NtFileHandle, SYNCHRONIZE | access, &ObjectAttributes, &IoStatus, NULL, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); if (NT_SUCCESS (ntStatus)) { opentest->TCBootLoaderDetected = FALSE; opentest->FilesystemDetected = FALSE; memset (opentest->VolumeIDComputed, 0, sizeof (opentest->VolumeIDComputed)); memset (opentest->volumeIDs, 0, sizeof (opentest->volumeIDs)); if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bComputeVolumeIDs) { byte *readBuffer = TCalloc (TC_MAX_VOLUME_SECTOR_SIZE); if (!readBuffer) { ntStatus = STATUS_INSUFFICIENT_RESOURCES; } else { if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem) { // Determine if the first sector contains a portion of the VeraCrypt Boot Loader offset.QuadPart = 0; ntStatus = ZwReadFile (NtFileHandle, NULL, NULL, NULL, &IoStatus, readBuffer, TC_MAX_VOLUME_SECTOR_SIZE, &offset, NULL); if (NT_SUCCESS (ntStatus)) { size_t i; if (opentest->bDetectTCBootLoader && IoStatus.Information >= TC_SECTOR_SIZE_BIOS) { // Search for the string "VeraCrypt" for (i = 0; i < TC_SECTOR_SIZE_BIOS - strlen (TC_APP_NAME); ++i) { if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0) { opentest->TCBootLoaderDetected = TRUE; break; } } } if (opentest->DetectFilesystem && IoStatus.Information >= sizeof (int64)) { switch (BE64 (*(uint64 *) readBuffer)) { case 0xEB52904E54465320ULL: // NTFS case 0xEB3C904D53444F53ULL: // FAT16/FAT32 case 0xEB58904D53444F53ULL: // FAT32 case 0xEB76904558464154ULL: // exFAT case 0x0000005265465300ULL: // ReFS case 0xEB58906D6B66732EULL: // FAT32 mkfs.fat case 0xEB58906D6B646F73ULL: // FAT32 mkfs.vfat/mkdosfs case 0xEB3C906D6B66732EULL: // FAT16/FAT12 mkfs.fat case 0xEB3C906D6B646F73ULL: // FAT16/FAT12 mkfs.vfat/mkdosfs opentest->FilesystemDetected = TRUE; break; case 0x0000000000000000ULL: // all 512 bytes are zeroes => unencrypted filesystem like Microsoft reserved partition if (IsAllZeroes (readBuffer + 8, TC_VOLUME_HEADER_EFFECTIVE_SIZE - 8)) opentest->FilesystemDetected = TRUE; break; } } } } if (opentest->bComputeVolumeIDs && (!opentest->DetectFilesystem || !opentest->FilesystemDetected)) { int volumeType; // Go through all volume types (e.g., normal, hidden) for (volumeType = TC_VOLUME_TYPE_NORMAL; volumeType < TC_VOLUME_TYPE_COUNT; volumeType++) { /* Read the volume header */ switch (volumeType) { case TC_VOLUME_TYPE_NORMAL: offset.QuadPart = TC_VOLUME_HEADER_OFFSET; break; case TC_VOLUME_TYPE_HIDDEN: offset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET; break; } ntStatus = ZwReadFile (NtFileHandle, NULL, NULL, NULL, &IoStatus, readBuffer, TC_MAX_VOLUME_SECTOR_SIZE, &offset, NULL); if (NT_SUCCESS (ntStatus)) { /* compute the ID of this volume: SHA-256 of the effective header */ sha256 (opentest->volumeIDs[volumeType], readBuffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE); opentest->VolumeIDComputed[volumeType] = TRUE; } } } TCfree (readBuffer); } } ZwClose (NtFileHandle); Dump ("Open test on file %ls success.\n", opentest->wszFileName); } else { #if 0 Dump ("Open test on file %ls failed NTSTATUS 0x%08x\n", opentest->wszFileName, ntStatus); #endif } Irp->IoStatus.Information = NT_SUCCESS (ntStatus) ? sizeof (OPEN_TEST_STRUCT) : 0; Irp->IoStatus.Status = ntStatus; } break; case TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG: { GetSystemDriveConfigurationRequest *request = (GetSystemDriveConfigurationRequest *) Irp->AssociatedIrp.SystemBuffer; OBJECT_ATTRIBUTES ObjectAttributes; HANDLE NtFileHandle; UNICODE_STRING FullFileName; IO_STATUS_BLOCK IoStatus; LARGE_INTEGER offset; byte readBuffer [TC_SECTOR_SIZE_BIOS]; if (!ValidateIOBufferSize (Irp, sizeof (GetSystemDriveConfigurationRequest), ValidateInputOutput)) break; EnsureNullTerminatedString (request->DevicePath, sizeof (request->DevicePath)); RtlInitUnicodeString (&FullFileName, request->DevicePath); InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); ntStatus = ZwCreateFile (&NtFileHandle, SYNCHRONIZE | GENERIC_READ, &ObjectAttributes, &IoStatus, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT | FILE_RANDOM_ACCESS, NULL, 0); if (NT_SUCCESS (ntStatus)) { // Determine if the first sector contains a portion of the VeraCrypt Boot Loader offset.QuadPart = 0; // MBR ntStatus = ZwReadFile (NtFileHandle, NULL, NULL, NULL, &IoStatus, readBuffer, sizeof(readBuffer), &offset, NULL); if (NT_SUCCESS (ntStatus)) { size_t i; // Check for dynamic drive request->DriveIsDynamic = FALSE; if (readBuffer[510] == 0x55 && readBuffer[511] == 0xaa) { int i; for (i = 0; i < 4; ++i) { if (readBuffer[446 + i * 16 + 4] == PARTITION_LDM) { request->DriveIsDynamic = TRUE; break; } } } request->BootLoaderVersion = 0; request->Configuration = 0; request->UserConfiguration = 0; request->CustomUserMessage[0] = 0; // Search for the string "VeraCrypt" for (i = 0; i < sizeof (readBuffer) - strlen (TC_APP_NAME); ++i) { if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0) { request->BootLoaderVersion = BE16 (*(uint16 *) (readBuffer + TC_BOOT_SECTOR_VERSION_OFFSET)); request->Configuration = readBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET]; if (request->BootLoaderVersion != 0 && request->BootLoaderVersion <= VERSION_NUM) { request->UserConfiguration = readBuffer[TC_BOOT_SECTOR_USER_CONFIG_OFFSET]; memcpy (request->CustomUserMessage, readBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); } break; } } Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (*request); } else { Irp->IoStatus.Status = ntStatus; Irp->IoStatus.Information = 0; } ZwClose (NtFileHandle); } else { Irp->IoStatus.Status = ntStatus; Irp->IoStatus.Information = 0; } } break; case TC_IOCTL_WIPE_PASSWORD_CACHE: WipeCache (); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: Irp->IoStatus.Status = cacheEmpty ? STATUS_PIPE_EMPTY : STATUS_SUCCESS; Irp->IoStatus.Information = 0; break; case TC_IOCTL_SET_PORTABLE_MODE_STATUS: if (!UserCanAccessDriveDevice()) { Irp->IoStatus.Status = STATUS_ACCESS_DENIED; Irp->IoStatus.Information = 0; } else { PortableMode = TRUE; Dump ("Setting portable mode\n"); } break; case TC_IOCTL_GET_PORTABLE_MODE_STATUS: Irp->IoStatus.Status = PortableMode ? STATUS_SUCCESS : STATUS_PIPE_EMPTY; Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_MOUNTED_VOLUMES: if (ValidateIOBufferSize (Irp, sizeof (MOUNT_LIST_STRUCT), ValidateOutput)) { MOUNT_LIST_STRUCT *list = (MOUNT_LIST_STRUCT *) Irp->AssociatedIrp.SystemBuffer; PDEVICE_OBJECT ListDevice; int drive; list->ulMountedDrives = 0; for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) { PEXTENSION ListExtension; ListDevice = GetVirtualVolumeDeviceObject (drive); if (!ListDevice) continue; ListExtension = (PEXTENSION) ListDevice->DeviceExtension; if (IsVolumeAccessibleByCurrentUser (ListExtension)) { list->ulMountedDrives |= (1 << ListExtension->nDosDriveNo); RtlStringCbCopyW (list->wszVolume[ListExtension->nDosDriveNo], sizeof(list->wszVolume[ListExtension->nDosDriveNo]),ListExtension->wszVolume); RtlStringCbCopyW (list->wszLabel[ListExtension->nDosDriveNo], sizeof(list->wszLabel[ListExtension->nDosDriveNo]),ListExtension->wszLabel); memcpy (list->volumeID[ListExtension->nDosDriveNo], ListExtension->volumeID, VOLUME_ID_SIZE); list->diskLength[ListExtension->nDosDriveNo] = ListExtension->DiskLength; list->ea[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->ea; if (ListExtension->cryptoInfo->hiddenVolume) list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_HIDDEN; // Hidden volume else if (ListExtension->cryptoInfo->bHiddenVolProtectionAction) list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED; // Normal/outer volume (hidden volume protected AND write already prevented) else if (ListExtension->cryptoInfo->bProtectHiddenVolume) list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER; // Normal/outer volume (hidden volume protected) else list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_NORMAL; // Normal volume list->truecryptMode[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->bTrueCryptMode; } } Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (MOUNT_LIST_STRUCT); } break; case TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES: if (ValidateIOBufferSize (Irp, sizeof (uint32), ValidateOutput)) { // Prevent the user from downgrading to versions lower than 5.0 by faking mounted volumes. // The user could render the system unbootable by downgrading when boot encryption // is active or being set up. memset (Irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength); *(uint32 *) Irp->AssociatedIrp.SystemBuffer = 0xffffFFFF; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = irpSp->Parameters.DeviceIoControl.OutputBufferLength; } break; case TC_IOCTL_GET_VOLUME_PROPERTIES: if (ValidateIOBufferSize (Irp, sizeof (VOLUME_PROPERTIES_STRUCT), ValidateInputOutput)) { VOLUME_PROPERTIES_STRUCT *prop = (VOLUME_PROPERTIES_STRUCT *) Irp->AssociatedIrp.SystemBuffer; PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (prop->driveNo); Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; if (ListDevice) { PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; if (IsVolumeAccessibleByCurrentUser (ListExtension)) { prop->uniqueId = ListExtension->UniqueVolumeId; RtlStringCbCopyW (prop->wszVolume, sizeof(prop->wszVolume),ListExtension->wszVolume); RtlStringCbCopyW (prop->wszLabel, sizeof(prop->wszLabel),ListExtension->wszLabel); memcpy (prop->volumeID, ListExtension->volumeID, VOLUME_ID_SIZE); prop->bDriverSetLabel = ListExtension->bDriverSetLabel; prop->diskLength = ListExtension->DiskLength; prop->ea = ListExtension->cryptoInfo->ea; prop->mode = ListExtension->cryptoInfo->mode; prop->pkcs5 = ListExtension->cryptoInfo->pkcs5; prop->pkcs5Iterations = ListExtension->cryptoInfo->noIterations; prop->volumePim = ListExtension->cryptoInfo->volumePim; #if 0 prop->volumeCreationTime = ListExtension->cryptoInfo->volume_creation_time; prop->headerCreationTime = ListExtension->cryptoInfo->header_creation_time; #endif prop->volumeHeaderFlags = ListExtension->cryptoInfo->HeaderFlags; prop->readOnly = ListExtension->bReadOnly; prop->removable = ListExtension->bRemovable; prop->partitionInInactiveSysEncScope = ListExtension->PartitionInInactiveSysEncScope; prop->hiddenVolume = ListExtension->cryptoInfo->hiddenVolume; if (ListExtension->cryptoInfo->bProtectHiddenVolume) prop->hiddenVolProtection = ListExtension->cryptoInfo->bHiddenVolProtectionAction ? HIDVOL_PROT_STATUS_ACTION_TAKEN : HIDVOL_PROT_STATUS_ACTIVE; else prop->hiddenVolProtection = HIDVOL_PROT_STATUS_NONE; prop->totalBytesRead = ListExtension->Queue.TotalBytesRead; prop->totalBytesWritten = ListExtension->Queue.TotalBytesWritten; prop->volFormatVersion = ListExtension->cryptoInfo->LegacyVolume ? TC_VOLUME_FORMAT_VERSION_PRE_6_0 : TC_VOLUME_FORMAT_VERSION; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (VOLUME_PROPERTIES_STRUCT); } } } break; case TC_IOCTL_GET_RESOLVED_SYMLINK: if (ValidateIOBufferSize (Irp, sizeof (RESOLVE_SYMLINK_STRUCT), ValidateInputOutput)) { RESOLVE_SYMLINK_STRUCT *resolve = (RESOLVE_SYMLINK_STRUCT *) Irp->AssociatedIrp.SystemBuffer; { NTSTATUS ntStatus; EnsureNullTerminatedString (resolve->symLinkName, sizeof (resolve->symLinkName)); ntStatus = SymbolicLinkToTarget (resolve->symLinkName, resolve->targetName, sizeof (resolve->targetName)); Irp->IoStatus.Information = sizeof (RESOLVE_SYMLINK_STRUCT); Irp->IoStatus.Status = ntStatus; } } break; case TC_IOCTL_GET_DRIVE_PARTITION_INFO: if (ValidateIOBufferSize (Irp, sizeof (DISK_PARTITION_INFO_STRUCT), ValidateInputOutput)) { DISK_PARTITION_INFO_STRUCT *info = (DISK_PARTITION_INFO_STRUCT *) Irp->AssociatedIrp.SystemBuffer; { PARTITION_INFORMATION_EX pi; NTSTATUS ntStatus; EnsureNullTerminatedString (info->deviceName, sizeof (info->deviceName)); ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &pi, sizeof (pi)); if (NT_SUCCESS(ntStatus)) { memset (&info->partInfo, 0, sizeof (info->partInfo)); info->partInfo.PartitionLength = pi.PartitionLength; info->partInfo.PartitionNumber = pi.PartitionNumber; info->partInfo.StartingOffset = pi.StartingOffset; if (pi.PartitionStyle == PARTITION_STYLE_MBR) { info->partInfo.PartitionType = pi.Mbr.PartitionType; info->partInfo.BootIndicator = pi.Mbr.BootIndicator; } info->IsGPT = pi.PartitionStyle == PARTITION_STYLE_GPT; } else { // Windows 2000 does not support IOCTL_DISK_GET_PARTITION_INFO_EX ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &info->partInfo, sizeof (info->partInfo)); info->IsGPT = FALSE; } if (!NT_SUCCESS (ntStatus)) { GET_LENGTH_INFORMATION lengthInfo; ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &lengthInfo, sizeof (lengthInfo)); if (NT_SUCCESS (ntStatus)) { memset (&info->partInfo, 0, sizeof (info->partInfo)); info->partInfo.PartitionLength = lengthInfo.Length; } } info->IsDynamic = FALSE; if (NT_SUCCESS (ntStatus) && OsMajorVersion >= 6) { # define IOCTL_VOLUME_IS_DYNAMIC CTL_CODE(IOCTL_VOLUME_BASE, 18, METHOD_BUFFERED, FILE_ANY_ACCESS) if (!NT_SUCCESS (TCDeviceIoControl (info->deviceName, IOCTL_VOLUME_IS_DYNAMIC, NULL, 0, &info->IsDynamic, sizeof (info->IsDynamic)))) info->IsDynamic = FALSE; } Irp->IoStatus.Information = sizeof (DISK_PARTITION_INFO_STRUCT); Irp->IoStatus.Status = ntStatus; } } break; case TC_IOCTL_GET_DRIVE_GEOMETRY: if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_STRUCT), ValidateInputOutput)) { DISK_GEOMETRY_STRUCT *g = (DISK_GEOMETRY_STRUCT *) Irp->AssociatedIrp.SystemBuffer; { NTSTATUS ntStatus; EnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName)); Dump ("Calling IOCTL_DISK_GET_DRIVE_GEOMETRY on %ls\n", g->deviceName); ntStatus = TCDeviceIoControl (g->deviceName, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &g->diskGeometry, sizeof (g->diskGeometry)); Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_STRUCT); Irp->IoStatus.Status = ntStatus; } } break; case VC_IOCTL_GET_DRIVE_GEOMETRY_EX: if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_EX_STRUCT), ValidateInputOutput)) { DISK_GEOMETRY_EX_STRUCT *g = (DISK_GEOMETRY_EX_STRUCT *) Irp->AssociatedIrp.SystemBuffer; { NTSTATUS ntStatus; PVOID buffer = TCalloc (256); // enough for DISK_GEOMETRY_EX and padded data if (buffer) { EnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName)); Dump ("Calling IOCTL_DISK_GET_DRIVE_GEOMETRY_EX on %ls\n", g->deviceName); ntStatus = TCDeviceIoControl (g->deviceName, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, buffer, 256); if (NT_SUCCESS(ntStatus)) { PDISK_GEOMETRY_EX pGeo = (PDISK_GEOMETRY_EX) buffer; memcpy (&g->diskGeometry, &pGeo->Geometry, sizeof (DISK_GEOMETRY)); g->DiskSize.QuadPart = pGeo->DiskSize.QuadPart; } else { DISK_GEOMETRY dg = {0}; Dump ("Failed. Calling IOCTL_DISK_GET_DRIVE_GEOMETRY on %ls\n", g->deviceName); ntStatus = TCDeviceIoControl (g->deviceName, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &dg, sizeof (dg)); if (NT_SUCCESS(ntStatus)) { memcpy (&g->diskGeometry, &dg, sizeof (DISK_GEOMETRY)); g->DiskSize.QuadPart = dg.Cylinders.QuadPart * dg.SectorsPerTrack * dg.TracksPerCylinder * dg.BytesPerSector; if (OsMajorVersion >= 6) { STORAGE_READ_CAPACITY storage = {0}; NTSTATUS lStatus; storage.Version = sizeof (STORAGE_READ_CAPACITY); Dump ("Calling IOCTL_STORAGE_READ_CAPACITY on %ls\n", g->deviceName); lStatus = TCDeviceIoControl (g->deviceName, IOCTL_STORAGE_READ_CAPACITY, NULL, 0, &storage, sizeof (STORAGE_READ_CAPACITY)); if ( NT_SUCCESS(lStatus) && (storage.Size == sizeof (STORAGE_READ_CAPACITY)) ) { g->DiskSize.QuadPart = storage.DiskLength.QuadPart; } } } } TCfree (buffer); Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_EX_STRUCT); Irp->IoStatus.Status = ntStatus; } else { Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; Irp->IoStatus.Information = 0; } } } break; case TC_IOCTL_PROBE_REAL_DRIVE_SIZE: if (ValidateIOBufferSize (Irp, sizeof (ProbeRealDriveSizeRequest), ValidateInputOutput)) { ProbeRealDriveSizeRequest *request = (ProbeRealDriveSizeRequest *) Irp->AssociatedIrp.SystemBuffer; NTSTATUS status; UNICODE_STRING name; PFILE_OBJECT fileObject; PDEVICE_OBJECT deviceObject; EnsureNullTerminatedString (request->DeviceName, sizeof (request->DeviceName)); RtlInitUnicodeString (&name, request->DeviceName); status = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject); if (!NT_SUCCESS (status)) { Irp->IoStatus.Information = 0; Irp->IoStatus.Status = status; break; } status = ProbeRealDriveSize (deviceObject, &request->RealDriveSize); ObDereferenceObject (fileObject); if (status == STATUS_TIMEOUT) { request->TimeOut = TRUE; Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest); Irp->IoStatus.Status = STATUS_SUCCESS; } else if (!NT_SUCCESS (status)) { Irp->IoStatus.Information = 0; Irp->IoStatus.Status = status; } else { request->TimeOut = FALSE; Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest); Irp->IoStatus.Status = status; } } break; case TC_IOCTL_MOUNT_VOLUME: if (ValidateIOBufferSize (Irp, sizeof (MOUNT_STRUCT), ValidateInputOutput)) { MOUNT_STRUCT *mount = (MOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; if (mount->VolumePassword.Length > MAX_PASSWORD || mount->ProtectedHidVolPassword.Length > MAX_PASSWORD || mount->pkcs5_prf < 0 || mount->pkcs5_prf > LAST_PRF_ID || mount->VolumePim < -1 || mount->VolumePim == INT_MAX || mount->ProtectedHidVolPkcs5Prf < 0 || mount->ProtectedHidVolPkcs5Prf > LAST_PRF_ID || (mount->bTrueCryptMode != FALSE && mount->bTrueCryptMode != TRUE) ) { Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; break; } EnsureNullTerminatedString (mount->wszVolume, sizeof (mount->wszVolume)); EnsureNullTerminatedString (mount->wszLabel, sizeof (mount->wszLabel)); Irp->IoStatus.Information = sizeof (MOUNT_STRUCT); Irp->IoStatus.Status = MountDevice (DeviceObject, mount); burn (&mount->VolumePassword, sizeof (mount->VolumePassword)); burn (&mount->ProtectedHidVolPassword, sizeof (mount->ProtectedHidVolPassword)); burn (&mount->pkcs5_prf, sizeof (mount->pkcs5_prf)); burn (&mount->VolumePim, sizeof (mount->VolumePim)); burn (&mount->bTrueCryptMode, sizeof (mount->bTrueCryptMode)); burn (&mount->ProtectedHidVolPkcs5Prf, sizeof (mount->ProtectedHidVolPkcs5Prf)); burn (&mount->ProtectedHidVolPim, sizeof (mount->ProtectedHidVolPim)); } break; case TC_IOCTL_DISMOUNT_VOLUME: if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput)) { UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (unmount->nDosDriveNo); unmount->nReturnCode = ERR_DRIVE_NOT_FOUND; if (ListDevice) { PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; if (IsVolumeAccessibleByCurrentUser (ListExtension)) unmount->nReturnCode = UnmountDevice (unmount, ListDevice, unmount->ignoreOpenFiles); } Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_DISMOUNT_ALL_VOLUMES: if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput)) { UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; unmount->nReturnCode = UnmountAllDevices (unmount, unmount->ignoreOpenFiles); Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_BOOT_ENCRYPTION_SETUP: Irp->IoStatus.Status = StartBootEncryptionSetup (DeviceObject, Irp, irpSp); Irp->IoStatus.Information = 0; break; case TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP: Irp->IoStatus.Status = AbortBootEncryptionSetup(); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: GetBootEncryptionStatus (Irp, irpSp); break; case TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT: Irp->IoStatus.Information = 0; Irp->IoStatus.Status = GetSetupResult(); break; case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: GetBootDriveVolumeProperties (Irp, irpSp); break; case TC_IOCTL_GET_BOOT_LOADER_VERSION: GetBootLoaderVersion (Irp, irpSp); break; case TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER: ReopenBootVolumeHeader (Irp, irpSp); break; case VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT: GetBootLoaderFingerprint (Irp, irpSp); break; case TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME: GetBootEncryptionAlgorithmName (Irp, irpSp); break; case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) { *(int *) Irp->AssociatedIrp.SystemBuffer = IsHiddenSystemRunning() ? 1 : 0; Irp->IoStatus.Information = sizeof (int); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_START_DECOY_SYSTEM_WIPE: Irp->IoStatus.Status = StartDecoySystemWipe (DeviceObject, Irp, irpSp); Irp->IoStatus.Information = 0; break; case TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE: Irp->IoStatus.Status = AbortDecoySystemWipe(); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT: Irp->IoStatus.Status = GetDecoySystemWipeResult(); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS: GetDecoySystemWipeStatus (Irp, irpSp); break; case TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR: Irp->IoStatus.Status = WriteBootDriveSector (Irp, irpSp); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_WARNING_FLAGS: if (ValidateIOBufferSize (Irp, sizeof (GetWarningFlagsRequest), ValidateOutput)) { GetWarningFlagsRequest *flags = (GetWarningFlagsRequest *) Irp->AssociatedIrp.SystemBuffer; flags->PagingFileCreationPrevented = PagingFileCreationPrevented; PagingFileCreationPrevented = FALSE; flags->SystemFavoriteVolumeDirty = SystemFavoriteVolumeDirty; SystemFavoriteVolumeDirty = FALSE; Irp->IoStatus.Information = sizeof (GetWarningFlagsRequest); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY: if (UserCanAccessDriveDevice()) { SystemFavoriteVolumeDirty = TRUE; Irp->IoStatus.Status = STATUS_SUCCESS; } else Irp->IoStatus.Status = STATUS_ACCESS_DENIED; Irp->IoStatus.Information = 0; break; case TC_IOCTL_REREAD_DRIVER_CONFIG: Irp->IoStatus.Status = ReadRegistryConfigFlags (FALSE); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG: if ( (ValidateIOBufferSize (Irp, sizeof (GetSystemDriveDumpConfigRequest), ValidateOutput)) && (Irp->RequestorMode == KernelMode) ) { GetSystemDriveDumpConfigRequest *request = (GetSystemDriveDumpConfigRequest *) Irp->AssociatedIrp.SystemBuffer; request->BootDriveFilterExtension = GetBootDriveFilterExtension(); if (IsBootDriveMounted() && request->BootDriveFilterExtension) { request->HwEncryptionEnabled = IsHwEncryptionEnabled(); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (*request); } else { Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; } } break; default: return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); } #if defined(DEBUG) || defined(DEBUG_TRACE) if (!NT_SUCCESS (Irp->IoStatus.Status)) { switch (irpSp->Parameters.DeviceIoControl.IoControlCode) { case TC_IOCTL_GET_MOUNTED_VOLUMES: case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: case TC_IOCTL_GET_PORTABLE_MODE_STATUS: case TC_IOCTL_SET_PORTABLE_MODE_STATUS: case TC_IOCTL_OPEN_TEST: case TC_IOCTL_GET_RESOLVED_SYMLINK: case TC_IOCTL_GET_DRIVE_PARTITION_INFO: case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: break; default: Dump ("IOCTL error 0x%08x\n", Irp->IoStatus.Status); } } #endif return TCCompleteIrp (Irp, Irp->IoStatus.Status, Irp->IoStatus.Information); } NTSTATUS TCStartThread (PKSTART_ROUTINE threadProc, PVOID threadArg, PKTHREAD *kThread) { return TCStartThreadInProcess (threadProc, threadArg, kThread, NULL); } NTSTATUS TCStartThreadInProcess (PKSTART_ROUTINE threadProc, PVOID threadArg, PKTHREAD *kThread, PEPROCESS process) { NTSTATUS status; HANDLE threadHandle; HANDLE processHandle = NULL; OBJECT_ATTRIBUTES threadObjAttributes; if (process) { status = ObOpenObjectByPointer (process, OBJ_KERNEL_HANDLE, NULL, 0, NULL, KernelMode, &processHandle); if (!NT_SUCCESS (status)) return status; } InitializeObjectAttributes (&threadObjAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); status = PsCreateSystemThread (&threadHandle, THREAD_ALL_ACCESS, &threadObjAttributes, processHandle, NULL, threadProc, threadArg); if (!NT_SUCCESS (status)) return status; status = ObReferenceObjectByHandle (threadHandle, THREAD_ALL_ACCESS, NULL, KernelMode, (PVOID *) kThread, NULL); if (!NT_SUCCESS (status)) { ZwClose (threadHandle); *kThread = NULL; return status; } if (processHandle) ZwClose (processHandle); ZwClose (threadHandle); return STATUS_SUCCESS; } void TCStopThread (PKTHREAD kThread, PKEVENT wakeUpEvent) { if (wakeUpEvent) KeSetEvent (wakeUpEvent, 0, FALSE); KeWaitForSingleObject (kThread, Executive, KernelMode, FALSE, NULL); ObDereferenceObject (kThread); } NTSTATUS TCStartVolumeThread (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, MOUNT_STRUCT * mount) { PTHREAD_BLOCK pThreadBlock = TCalloc (sizeof (THREAD_BLOCK)); HANDLE hThread; NTSTATUS ntStatus; OBJECT_ATTRIBUTES threadObjAttributes; SECURITY_QUALITY_OF_SERVICE qos; Dump ("Starting thread...\n"); if (pThreadBlock == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } else { pThreadBlock->DeviceObject = DeviceObject; pThreadBlock->mount = mount; } qos.Length = sizeof (qos); qos.ContextTrackingMode = SECURITY_STATIC_TRACKING; qos.EffectiveOnly = TRUE; qos.ImpersonationLevel = SecurityImpersonation; ntStatus = SeCreateClientSecurity (PsGetCurrentThread(), &qos, FALSE, &Extension->SecurityClientContext); if (!NT_SUCCESS (ntStatus)) goto ret; Extension->SecurityClientContextValid = TRUE; Extension->bThreadShouldQuit = FALSE; InitializeObjectAttributes (&threadObjAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); ntStatus = PsCreateSystemThread (&hThread, THREAD_ALL_ACCESS, &threadObjAttributes, NULL, NULL, VolumeThreadProc, pThreadBlock); if (!NT_SUCCESS (ntStatus)) { Dump ("PsCreateSystemThread Failed END\n"); goto ret; } ntStatus = ObReferenceObjectByHandle (hThread, THREAD_ALL_ACCESS, NULL, KernelMode, &Extension->peThread, NULL); ZwClose (hThread); if (!NT_SUCCESS (ntStatus)) goto ret; Dump ("Waiting for thread to initialize...\n"); KeWaitForSingleObject (&Extension->keCreateEvent, Executive, KernelMode, FALSE, NULL); Dump ("Waiting completed! Thread returns 0x%08x\n", pThreadBlock->ntCreateStatus); ntStatus = pThreadBlock->ntCreateStatus; ret: TCfree (pThreadBlock); return ntStatus; } void TCStopVolumeThread (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension) { NTSTATUS ntStatus; UNREFERENCED_PARAMETER (DeviceObject); /* Remove compiler warning */ Dump ("Signalling thread to quit...\n"); Extension->bThreadShouldQuit = TRUE; KeReleaseSemaphore (&Extension->RequestSemaphore, 0, 1, TRUE); ntStatus = KeWaitForSingleObject (Extension->peThread, Executive, KernelMode, FALSE, NULL); ASSERT (NT_SUCCESS (ntStatus)); ObDereferenceObject (Extension->peThread); Extension->peThread = NULL; Dump ("Thread exited\n"); } // Suspend current thread for a number of milliseconds void TCSleep (int milliSeconds) { PKTIMER timer = (PKTIMER) TCalloc (sizeof (KTIMER)); LARGE_INTEGER duetime; if (!timer) return; duetime.QuadPart = (__int64) milliSeconds * -10000; KeInitializeTimerEx(timer, NotificationTimer); KeSetTimerEx(timer, duetime, 0, NULL); KeWaitForSingleObject (timer, Executive, KernelMode, FALSE, NULL); TCfree (timer); } BOOL IsDeviceName(wchar_t wszVolume[TC_MAX_PATH]) { if ( (wszVolume[0] == '\\') && (wszVolume[1] == 'D' || wszVolume[1] == 'd') && (wszVolume[2] == 'E' || wszVolume[2] == 'e') && (wszVolume[3] == 'V' || wszVolume[3] == 'v') && (wszVolume[4] == 'I' || wszVolume[4] == 'i') && (wszVolume[5] == 'C' || wszVolume[5] == 'c') && (wszVolume[6] == 'E' || wszVolume[6] == 'e') ) { return TRUE; } else return FALSE; } /* VolumeThreadProc does all the work of processing IRP's, and dispatching them to either the ReadWrite function or the DeviceControl function */ VOID VolumeThreadProc (PVOID Context) { PTHREAD_BLOCK pThreadBlock = (PTHREAD_BLOCK) Context; PDEVICE_OBJECT DeviceObject = pThreadBlock->DeviceObject; PEXTENSION Extension = (PEXTENSION) DeviceObject->DeviceExtension; BOOL bDevice; /* Set thread priority to lowest realtime level. */ KeSetPriorityThread (KeGetCurrentThread (), LOW_REALTIME_PRIORITY); Dump ("Mount THREAD OPENING VOLUME BEGIN\n"); if ( !IsDeviceName (pThreadBlock->mount->wszVolume)) { RtlStringCbCopyW (pThreadBlock->wszMountVolume, sizeof(pThreadBlock->wszMountVolume),WIDE ("\\??\\")); RtlStringCbCatW (pThreadBlock->wszMountVolume, sizeof(pThreadBlock->wszMountVolume),pThreadBlock->mount->wszVolume); bDevice = FALSE; } else { pThreadBlock->wszMountVolume[0] = 0; RtlStringCbCatW (pThreadBlock->wszMountVolume, sizeof(pThreadBlock->wszMountVolume),pThreadBlock->mount->wszVolume); bDevice = TRUE; } Dump ("Mount THREAD request for File %ls DriveNumber %d Device = %d\n", pThreadBlock->wszMountVolume, pThreadBlock->mount->nDosDriveNo, bDevice); pThreadBlock->ntCreateStatus = TCOpenVolume (DeviceObject, Extension, pThreadBlock->mount, pThreadBlock->wszMountVolume, bDevice); if (!NT_SUCCESS (pThreadBlock->ntCreateStatus) || pThreadBlock->mount->nReturnCode != 0) { KeSetEvent (&Extension->keCreateEvent, 0, FALSE); PsTerminateSystemThread (STATUS_SUCCESS); } // Start IO queue Extension->Queue.IsFilterDevice = FALSE; Extension->Queue.DeviceObject = DeviceObject; Extension->Queue.CryptoInfo = Extension->cryptoInfo; Extension->Queue.HostFileHandle = Extension->hDeviceFile; Extension->Queue.VirtualDeviceLength = Extension->DiskLength; Extension->Queue.MaxReadAheadOffset.QuadPart = Extension->HostLength; if (Extension->SecurityClientContextValid) Extension->Queue.SecurityClientContext = &Extension->SecurityClientContext; else Extension->Queue.SecurityClientContext = NULL; pThreadBlock->ntCreateStatus = EncryptedIoQueueStart (&Extension->Queue); if (!NT_SUCCESS (pThreadBlock->ntCreateStatus)) { TCCloseVolume (DeviceObject, Extension); pThreadBlock->mount->nReturnCode = ERR_OS_ERROR; KeSetEvent (&Extension->keCreateEvent, 0, FALSE); PsTerminateSystemThread (STATUS_SUCCESS); } KeSetEvent (&Extension->keCreateEvent, 0, FALSE); /* From this point on pThreadBlock cannot be used as it will have been released! */ pThreadBlock = NULL; for (;;) { /* Wait for a request from the dispatch routines. */ KeWaitForSingleObject ((PVOID) & Extension->RequestSemaphore, Executive, KernelMode, FALSE, NULL); for (;;) { PIO_STACK_LOCATION irpSp; PLIST_ENTRY request; PIRP irp; request = ExInterlockedRemoveHeadList (&Extension->ListEntry, &Extension->ListSpinLock); if (request == NULL) break; irp = CONTAINING_RECORD (request, IRP, Tail.Overlay.ListEntry); irpSp = IoGetCurrentIrpStackLocation (irp); ASSERT (irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL); ProcessVolumeDeviceControlIrp (DeviceObject, Extension, irp); IoReleaseRemoveLock (&Extension->Queue.RemoveLock, irp); } if (Extension->bThreadShouldQuit) { Dump ("Closing volume\n"); EncryptedIoQueueStop (&Extension->Queue); TCCloseVolume (DeviceObject, Extension); PsTerminateSystemThread (STATUS_SUCCESS); } } } void TCGetNTNameFromNumber (LPWSTR ntname, int cbNtName, int nDriveNo) { WCHAR tmp[2] = {0, 0}; int j = nDriveNo + (WCHAR) 'A'; tmp[0] = (short) j; RtlStringCbCopyW (ntname, cbNtName,(LPWSTR) NT_MOUNT_PREFIX); RtlStringCbCatW (ntname, cbNtName, tmp); } void TCGetDosNameFromNumber (LPWSTR dosname,int cbDosName, int nDriveNo, DeviceNamespaceType namespaceType) { WCHAR tmp[3] = {0, ':', 0}; int j = nDriveNo + (WCHAR) 'A'; tmp[0] = (short) j; if (DeviceNamespaceGlobal == namespaceType) { RtlStringCbCopyW (dosname, cbDosName, (LPWSTR) DOS_MOUNT_PREFIX_GLOBAL); } else { RtlStringCbCopyW (dosname, cbDosName, (LPWSTR) DOS_MOUNT_PREFIX_DEFAULT); } RtlStringCbCatW (dosname, cbDosName, tmp); } #if defined(_DEBUG) || defined (_DEBUG_TRACE) LPWSTR TCTranslateCode (ULONG ulCode) { switch (ulCode) { #define TC_CASE_RET_NAME(CODE) case CODE : return L###CODE TC_CASE_RET_NAME (TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP); TC_CASE_RET_NAME (TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE); TC_CASE_RET_NAME (TC_IOCTL_BOOT_ENCRYPTION_SETUP); TC_CASE_RET_NAME (TC_IOCTL_DISMOUNT_ALL_VOLUMES); TC_CASE_RET_NAME (TC_IOCTL_DISMOUNT_VOLUME); TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES); TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME); TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT); TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS); TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_LOADER_VERSION); TC_CASE_RET_NAME (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT); TC_CASE_RET_NAME (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS); TC_CASE_RET_NAME (TC_IOCTL_GET_DEVICE_REFCOUNT); TC_CASE_RET_NAME (TC_IOCTL_GET_DRIVE_GEOMETRY); TC_CASE_RET_NAME (TC_IOCTL_GET_DRIVE_PARTITION_INFO); TC_CASE_RET_NAME (TC_IOCTL_GET_DRIVER_VERSION); TC_CASE_RET_NAME (TC_IOCTL_GET_MOUNTED_VOLUMES); TC_CASE_RET_NAME (TC_IOCTL_GET_PASSWORD_CACHE_STATUS); TC_CASE_RET_NAME (TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG); TC_CASE_RET_NAME (TC_IOCTL_GET_PORTABLE_MODE_STATUS); TC_CASE_RET_NAME (TC_IOCTL_SET_PORTABLE_MODE_STATUS); TC_CASE_RET_NAME (TC_IOCTL_GET_RESOLVED_SYMLINK); TC_CASE_RET_NAME (TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG); TC_CASE_RET_NAME (TC_IOCTL_GET_VOLUME_PROPERTIES); TC_CASE_RET_NAME (TC_IOCTL_GET_WARNING_FLAGS); TC_CASE_RET_NAME (TC_IOCTL_DISK_IS_WRITABLE); TC_CASE_RET_NAME (TC_IOCTL_IS_ANY_VOLUME_MOUNTED); TC_CASE_RET_NAME (TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED); TC_CASE_RET_NAME (TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING); TC_CASE_RET_NAME (TC_IOCTL_MOUNT_VOLUME); TC_CASE_RET_NAME (TC_IOCTL_OPEN_TEST); TC_CASE_RET_NAME (TC_IOCTL_PROBE_REAL_DRIVE_SIZE); TC_CASE_RET_NAME (TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER); TC_CASE_RET_NAME (TC_IOCTL_REREAD_DRIVER_CONFIG); TC_CASE_RET_NAME (TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY); TC_CASE_RET_NAME (TC_IOCTL_START_DECOY_SYSTEM_WIPE); TC_CASE_RET_NAME (TC_IOCTL_WIPE_PASSWORD_CACHE); TC_CASE_RET_NAME (TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR); TC_CASE_RET_NAME (VC_IOCTL_GET_DRIVE_GEOMETRY_EX); TC_CASE_RET_NAME (IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS); #undef TC_CASE_RET_NAME } if (ulCode == IOCTL_DISK_GET_DRIVE_GEOMETRY) return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_GEOMETRY"); else if (ulCode == IOCTL_DISK_GET_DRIVE_GEOMETRY_EX) return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_GEOMETRY_EX"); else if (ulCode == IOCTL_MOUNTDEV_QUERY_DEVICE_NAME) return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_DEVICE_NAME"); else if (ulCode == IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME) return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME"); else if (ulCode == IOCTL_MOUNTDEV_QUERY_UNIQUE_ID) return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_UNIQUE_ID"); else if (ulCode == IOCTL_VOLUME_ONLINE) return (LPWSTR) _T ("IOCTL_VOLUME_ONLINE"); else if (ulCode == IOCTL_MOUNTDEV_LINK_CREATED) return (LPWSTR) _T ("IOCTL_MOUNTDEV_LINK_CREATED"); else if (ulCode == IOCTL_MOUNTDEV_LINK_DELETED) return (LPWSTR) _T ("IOCTL_MOUNTDEV_LINK_DELETED"); else if (ulCode == IOCTL_MOUNTMGR_QUERY_POINTS) return (LPWSTR) _T ("IOCTL_MOUNTMGR_QUERY_POINTS"); else if (ulCode == IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_CREATED) return (LPWSTR) _T ("IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_CREATED"); else if (ulCode == IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_DELETED) return (LPWSTR) _T ("IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_DELETED"); else if (ulCode == IOCTL_DISK_GET_LENGTH_INFO) return (LPWSTR) _T ("IOCTL_DISK_GET_LENGTH_INFO"); else if (ulCode == IOCTL_STORAGE_GET_DEVICE_NUMBER) return (LPWSTR) _T ("IOCTL_STORAGE_GET_DEVICE_NUMBER"); else if (ulCode == IOCTL_DISK_GET_PARTITION_INFO) return (LPWSTR) _T ("IOCTL_DISK_GET_PARTITION_INFO"); else if (ulCode == IOCTL_DISK_GET_PARTITION_INFO_EX) return (LPWSTR) _T ("IOCTL_DISK_GET_PARTITION_INFO_EX"); else if (ulCode == IOCTL_DISK_SET_PARTITION_INFO) return (LPWSTR) _T ("IOCTL_DISK_SET_PARTITION_INFO"); else if (ulCode == IOCTL_DISK_GET_DRIVE_LAYOUT) return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_LAYOUT"); else if (ulCode == IOCTL_DISK_GET_DRIVE_LAYOUT_EX) return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_LAYOUT_EX"); else if (ulCode == IOCTL_DISK_SET_DRIVE_LAYOUT_EX) return (LPWSTR) _T ("IOCTL_DISK_SET_DRIVE_LAYOUT_EX"); else if (ulCode == IOCTL_DISK_VERIFY) return (LPWSTR) _T ("IOCTL_DISK_VERIFY"); else if (ulCode == IOCTL_DISK_FORMAT_TRACKS) return (LPWSTR) _T ("IOCTL_DISK_FORMAT_TRACKS"); else if (ulCode == IOCTL_DISK_REASSIGN_BLOCKS) return (LPWSTR) _T ("IOCTL_DISK_REASSIGN_BLOCKS"); else if (ulCode == IOCTL_DISK_PERFORMANCE) return (LPWSTR) _T ("IOCTL_DISK_PERFORMANCE"); else if (ulCode == IOCTL_DISK_IS_WRITABLE) return (LPWSTR) _T ("IOCTL_DISK_IS_WRITABLE"); else if (ulCode == IOCTL_DISK_LOGGING) return (LPWSTR) _T ("IOCTL_DISK_LOGGING"); else if (ulCode == IOCTL_DISK_FORMAT_TRACKS_EX) return (LPWSTR) _T ("IOCTL_DISK_FORMAT_TRACKS_EX"); else if (ulCode == IOCTL_DISK_HISTOGRAM_STRUCTURE) return (LPWSTR) _T ("IOCTL_DISK_HISTOGRAM_STRUCTURE"); else if (ulCode == IOCTL_DISK_HISTOGRAM_DATA) return (LPWSTR) _T ("IOCTL_DISK_HISTOGRAM_DATA"); else if (ulCode == IOCTL_DISK_HISTOGRAM_RESET) return (LPWSTR) _T ("IOCTL_DISK_HISTOGRAM_RESET"); else if (ulCode == IOCTL_DISK_REQUEST_STRUCTURE) return (LPWSTR) _T ("IOCTL_DISK_REQUEST_STRUCTURE"); else if (ulCode == IOCTL_DISK_REQUEST_DATA) return (LPWSTR) _T ("IOCTL_DISK_REQUEST_DATA"); else if (ulCode == IOCTL_DISK_CONTROLLER_NUMBER) return (LPWSTR) _T ("IOCTL_DISK_CONTROLLER_NUMBER"); else if (ulCode == SMART_GET_VERSION) return (LPWSTR) _T ("SMART_GET_VERSION"); else if (ulCode == SMART_SEND_DRIVE_COMMAND) return (LPWSTR) _T ("SMART_SEND_DRIVE_COMMAND"); else if (ulCode == SMART_RCV_DRIVE_DATA) return (LPWSTR) _T ("SMART_RCV_DRIVE_DATA"); else if (ulCode == IOCTL_DISK_INTERNAL_SET_VERIFY) return (LPWSTR) _T ("IOCTL_DISK_INTERNAL_SET_VERIFY"); else if (ulCode == IOCTL_DISK_INTERNAL_CLEAR_VERIFY) return (LPWSTR) _T ("IOCTL_DISK_INTERNAL_CLEAR_VERIFY"); else if (ulCode == IOCTL_DISK_CHECK_VERIFY) return (LPWSTR) _T ("IOCTL_DISK_CHECK_VERIFY"); else if (ulCode == IOCTL_DISK_MEDIA_REMOVAL) return (LPWSTR) _T ("IOCTL_DISK_MEDIA_REMOVAL"); else if (ulCode == IOCTL_DISK_EJECT_MEDIA) return (LPWSTR) _T ("IOCTL_DISK_EJECT_MEDIA"); else if (ulCode == IOCTL_DISK_LOAD_MEDIA) return (LPWSTR) _T ("IOCTL_DISK_LOAD_MEDIA"); else if (ulCode == IOCTL_DISK_RESERVE) return (LPWSTR) _T ("IOCTL_DISK_RESERVE"); else if (ulCode == IOCTL_DISK_RELEASE) return (LPWSTR) _T ("IOCTL_DISK_RELEASE"); else if (ulCode == IOCTL_DISK_FIND_NEW_DEVICES) return (LPWSTR) _T ("IOCTL_DISK_FIND_NEW_DEVICES"); else if (ulCode == IOCTL_DISK_GET_MEDIA_TYPES) return (LPWSTR) _T ("IOCTL_DISK_GET_MEDIA_TYPES"); else if (ulCode == IOCTL_DISK_IS_CLUSTERED) return (LPWSTR) _T ("IOCTL_DISK_IS_CLUSTERED"); else if (ulCode == IOCTL_DISK_UPDATE_DRIVE_SIZE) return (LPWSTR) _T ("IOCTL_DISK_UPDATE_DRIVE_SIZE"); else if (ulCode == IOCTL_STORAGE_GET_MEDIA_TYPES) return (LPWSTR) _T ("IOCTL_STORAGE_GET_MEDIA_TYPES"); else if (ulCode == IOCTL_STORAGE_GET_HOTPLUG_INFO) return (LPWSTR) _T ("IOCTL_STORAGE_GET_HOTPLUG_INFO"); else if (ulCode == IOCTL_STORAGE_SET_HOTPLUG_INFO) return (LPWSTR) _T ("IOCTL_STORAGE_SET_HOTPLUG_INFO"); else if (ulCode == IOCTL_STORAGE_QUERY_PROPERTY) return (LPWSTR) _T ("IOCTL_STORAGE_QUERY_PROPERTY"); else if (ulCode == IOCTL_VOLUME_GET_GPT_ATTRIBUTES) return (LPWSTR) _T ("IOCTL_VOLUME_GET_GPT_ATTRIBUTES"); else if (ulCode == FT_BALANCED_READ_MODE) return (LPWSTR) _T ("FT_BALANCED_READ_MODE"); else if (ulCode == IOCTL_VOLUME_QUERY_ALLOCATION_HINT) return (LPWSTR) _T ("IOCTL_VOLUME_QUERY_ALLOCATION_HINT"); else if (ulCode == IOCTL_DISK_GET_CLUSTER_INFO) return (LPWSTR) _T ("IOCTL_DISK_GET_CLUSTER_INFO"); else if (ulCode == IOCTL_DISK_ARE_VOLUMES_READY) return (LPWSTR) _T ("IOCTL_DISK_ARE_VOLUMES_READY"); else if (ulCode == IOCTL_VOLUME_IS_DYNAMIC) return (LPWSTR) _T ("IOCTL_VOLUME_IS_DYNAMIC"); else if (ulCode == IOCTL_MOUNTDEV_QUERY_STABLE_GUID) return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_STABLE_GUID"); else if (ulCode == IOCTL_VOLUME_POST_ONLINE) return (LPWSTR) _T ("IOCTL_VOLUME_POST_ONLINE"); else if (ulCode == IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT) return (LPWSTR) _T ("IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT"); else if (ulCode == IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES) return (LPWSTR) _T ("IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES"); else if (ulCode == IRP_MJ_READ) return (LPWSTR) _T ("IRP_MJ_READ"); else if (ulCode == IRP_MJ_WRITE) return (LPWSTR) _T ("IRP_MJ_WRITE"); else if (ulCode == IRP_MJ_CREATE) return (LPWSTR) _T ("IRP_MJ_CREATE"); else if (ulCode == IRP_MJ_CLOSE) return (LPWSTR) _T ("IRP_MJ_CLOSE"); else if (ulCode == IRP_MJ_CLEANUP) return (LPWSTR) _T ("IRP_MJ_CLEANUP"); else if (ulCode == IRP_MJ_FLUSH_BUFFERS) return (LPWSTR) _T ("IRP_MJ_FLUSH_BUFFERS"); else if (ulCode == IRP_MJ_SHUTDOWN) return (LPWSTR) _T ("IRP_MJ_SHUTDOWN"); else if (ulCode == IRP_MJ_DEVICE_CONTROL) return (LPWSTR) _T ("IRP_MJ_DEVICE_CONTROL"); else { return (LPWSTR) _T ("IOCTL"); } } #endif void TCDeleteDeviceObject (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension) { UNICODE_STRING Win32NameString; NTSTATUS ntStatus; Dump ("TCDeleteDeviceObject BEGIN\n"); if (Extension->bRootDevice) { RtlInitUnicodeString (&Win32NameString, (LPWSTR) DOS_ROOT_PREFIX); ntStatus = IoDeleteSymbolicLink (&Win32NameString); if (!NT_SUCCESS (ntStatus)) Dump ("IoDeleteSymbolicLink failed ntStatus = 0x%08x\n", ntStatus); RootDeviceObject = NULL; } else { if (Extension->peThread != NULL) TCStopVolumeThread (DeviceObject, Extension); if (Extension->UserSid) TCfree (Extension->UserSid); if (Extension->SecurityClientContextValid) { if (OsMajorVersion == 5 && OsMinorVersion == 0) { ObDereferenceObject (Extension->SecurityClientContext.ClientToken); } else { // Windows 2000 does not support PsDereferenceImpersonationToken() used by SeDeleteClientSecurity(). // TODO: Use only SeDeleteClientSecurity() once support for Windows 2000 is dropped. VOID (*PsDereferenceImpersonationTokenD) (PACCESS_TOKEN ImpersonationToken); UNICODE_STRING name; RtlInitUnicodeString (&name, L"PsDereferenceImpersonationToken"); PsDereferenceImpersonationTokenD = MmGetSystemRoutineAddress (&name); if (!PsDereferenceImpersonationTokenD) TC_BUG_CHECK (STATUS_NOT_IMPLEMENTED); # define PsDereferencePrimaryToken # define PsDereferenceImpersonationToken PsDereferenceImpersonationTokenD SeDeleteClientSecurity (&Extension->SecurityClientContext); # undef PsDereferencePrimaryToken # undef PsDereferenceImpersonationToken } } VirtualVolumeDeviceObjects[Extension->nDosDriveNo] = NULL; } IoDeleteDevice (DeviceObject); Dump ("TCDeleteDeviceObject END\n"); } VOID TCUnloadDriver (PDRIVER_OBJECT DriverObject) { Dump ("TCUnloadDriver BEGIN\n"); OnShutdownPending(); if (IsBootDriveMounted()) TC_BUG_CHECK (STATUS_INVALID_DEVICE_STATE); EncryptionThreadPoolStop(); TCDeleteDeviceObject (RootDeviceObject, (PEXTENSION) RootDeviceObject->DeviceExtension); Dump ("TCUnloadDriver END\n"); } void OnShutdownPending () { UNMOUNT_STRUCT unmount; memset (&unmount, 0, sizeof (unmount)); unmount.ignoreOpenFiles = TRUE; while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_DISMOUNT_ALL_VOLUMES, &unmount, sizeof (unmount), &unmount, sizeof (unmount)) == STATUS_INSUFFICIENT_RESOURCES || unmount.HiddenVolumeProtectionTriggered) unmount.HiddenVolumeProtectionTriggered = FALSE; while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES); } NTSTATUS TCDeviceIoControl (PWSTR deviceName, ULONG IoControlCode, void *InputBuffer, ULONG InputBufferSize, void *OutputBuffer, ULONG OutputBufferSize) { IO_STATUS_BLOCK ioStatusBlock; NTSTATUS ntStatus; PIRP irp; PFILE_OBJECT fileObject; PDEVICE_OBJECT deviceObject; KEVENT event; UNICODE_STRING name; RtlInitUnicodeString(&name, deviceName); ntStatus = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject); if (!NT_SUCCESS (ntStatus)) return ntStatus; KeInitializeEvent(&event, NotificationEvent, FALSE); irp = IoBuildDeviceIoControlRequest (IoControlCode, deviceObject, InputBuffer, InputBufferSize, OutputBuffer, OutputBufferSize, FALSE, &event, &ioStatusBlock); if (irp == NULL) { Dump ("IRP allocation failed\n"); ntStatus = STATUS_INSUFFICIENT_RESOURCES; goto ret; } IoGetNextIrpStackLocation (irp)->FileObject = fileObject; ntStatus = IoCallDriver (deviceObject, irp); if (ntStatus == STATUS_PENDING) { KeWaitForSingleObject (&event, Executive, KernelMode, FALSE, NULL); ntStatus = ioStatusBlock.Status; } ret: ObDereferenceObject (fileObject); return ntStatus; } typedef struct { PDEVICE_OBJECT deviceObject; ULONG ioControlCode; void *inputBuffer; int inputBufferSize; void *outputBuffer; int outputBufferSize; NTSTATUS Status; KEVENT WorkItemCompletedEvent; } SendDeviceIoControlRequestWorkItemArgs; static VOID SendDeviceIoControlRequestWorkItemRoutine (PDEVICE_OBJECT rootDeviceObject, SendDeviceIoControlRequestWorkItemArgs *arg) { arg->Status = SendDeviceIoControlRequest (arg->deviceObject, arg->ioControlCode, arg->inputBuffer, arg->inputBufferSize, arg->outputBuffer, arg->outputBufferSize); KeSetEvent (&arg->WorkItemCompletedEvent, IO_NO_INCREMENT, FALSE); } NTSTATUS SendDeviceIoControlRequest (PDEVICE_OBJECT deviceObject, ULONG ioControlCode, void *inputBuffer, int inputBufferSize, void *outputBuffer, int outputBufferSize) { IO_STATUS_BLOCK ioStatusBlock; NTSTATUS status; PIRP irp; KEVENT event; if (KeGetCurrentIrql() > APC_LEVEL) { SendDeviceIoControlRequestWorkItemArgs args; PIO_WORKITEM workItem = IoAllocateWorkItem (RootDeviceObject); if (!workItem) return STATUS_INSUFFICIENT_RESOURCES; args.deviceObject = deviceObject; args.ioControlCode = ioControlCode; args.inputBuffer = inputBuffer; args.inputBufferSize = inputBufferSize; args.outputBuffer = outputBuffer; args.outputBufferSize = outputBufferSize; KeInitializeEvent (&args.WorkItemCompletedEvent, SynchronizationEvent, FALSE); IoQueueWorkItem (workItem, SendDeviceIoControlRequestWorkItemRoutine, DelayedWorkQueue, &args); KeWaitForSingleObject (&args.WorkItemCompletedEvent, Executive, KernelMode, FALSE, NULL); IoFreeWorkItem (workItem); return args.Status; } KeInitializeEvent (&event, NotificationEvent, FALSE); irp = IoBuildDeviceIoControlRequest (ioControlCode, deviceObject, inputBuffer, inputBufferSize, outputBuffer, outputBufferSize, FALSE, &event, &ioStatusBlock); if (!irp) return STATUS_INSUFFICIENT_RESOURCES; ObReferenceObject (deviceObject); status = IoCallDriver (deviceObject, irp); if (status == STATUS_PENDING) { KeWaitForSingleObject (&event, Executive, KernelMode, FALSE, NULL); status = ioStatusBlock.Status; } ObDereferenceObject (deviceObject); return status; } NTSTATUS ProbeRealDriveSize (PDEVICE_OBJECT driveDeviceObject, LARGE_INTEGER *driveSize) { NTSTATUS status; LARGE_INTEGER sysLength; LARGE_INTEGER offset; byte *sectorBuffer; ULONGLONG startTime; if (!UserCanAccessDriveDevice()) return STATUS_ACCESS_DENIED; sectorBuffer = TCalloc (TC_SECTOR_SIZE_BIOS); if (!sectorBuffer) return STATUS_INSUFFICIENT_RESOURCES; status = SendDeviceIoControlRequest (driveDeviceObject, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &sysLength, sizeof (sysLength)); if (!NT_SUCCESS (status)) { Dump ("Failed to get drive size - error %x\n", status); TCfree (sectorBuffer); return status; } startTime = KeQueryInterruptTime (); for (offset.QuadPart = sysLength.QuadPart; ; offset.QuadPart += TC_SECTOR_SIZE_BIOS) { status = TCReadDevice (driveDeviceObject, sectorBuffer, offset, TC_SECTOR_SIZE_BIOS); if (NT_SUCCESS (status)) status = TCWriteDevice (driveDeviceObject, sectorBuffer, offset, TC_SECTOR_SIZE_BIOS); if (!NT_SUCCESS (status)) { driveSize->QuadPart = offset.QuadPart; Dump ("Real drive size = %I64d bytes (%I64d hidden)\n", driveSize->QuadPart, driveSize->QuadPart - sysLength.QuadPart); TCfree (sectorBuffer); return STATUS_SUCCESS; } if (KeQueryInterruptTime() - startTime > 3ULL * 60 * 1000 * 1000 * 10) { // Abort if probing for more than 3 minutes driveSize->QuadPart = sysLength.QuadPart; TCfree (sectorBuffer); return STATUS_TIMEOUT; } } } NTSTATUS TCOpenFsVolume (PEXTENSION Extension, PHANDLE volumeHandle, PFILE_OBJECT * fileObject) { NTSTATUS ntStatus; OBJECT_ATTRIBUTES objectAttributes; UNICODE_STRING fullFileName; IO_STATUS_BLOCK ioStatus; WCHAR volumeName[TC_MAX_PATH]; TCGetNTNameFromNumber (volumeName, sizeof(volumeName),Extension->nDosDriveNo); RtlInitUnicodeString (&fullFileName, volumeName); InitializeObjectAttributes (&objectAttributes, &fullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); ntStatus = ZwCreateFile (volumeHandle, SYNCHRONIZE | GENERIC_READ, &objectAttributes, &ioStatus, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); Dump ("Volume %ls open NTSTATUS 0x%08x\n", volumeName, ntStatus); if (!NT_SUCCESS (ntStatus)) return ntStatus; ntStatus = ObReferenceObjectByHandle (*volumeHandle, FILE_READ_DATA, NULL, KernelMode, fileObject, NULL); if (!NT_SUCCESS (ntStatus)) ZwClose (*volumeHandle); return ntStatus; } void TCCloseFsVolume (HANDLE volumeHandle, PFILE_OBJECT fileObject) { ObDereferenceObject (fileObject); ZwClose (volumeHandle); } static NTSTATUS TCReadWriteDevice (BOOL write, PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length) { NTSTATUS status; IO_STATUS_BLOCK ioStatusBlock; PIRP irp; KEVENT completionEvent; ASSERT (KeGetCurrentIrql() <= APC_LEVEL); KeInitializeEvent (&completionEvent, NotificationEvent, FALSE); irp = IoBuildSynchronousFsdRequest (write ? IRP_MJ_WRITE : IRP_MJ_READ, deviceObject, buffer, length, &offset, &completionEvent, &ioStatusBlock); if (!irp) return STATUS_INSUFFICIENT_RESOURCES; ObReferenceObject (deviceObject); status = IoCallDriver (deviceObject, irp); if (status == STATUS_PENDING) { status = KeWaitForSingleObject (&completionEvent, Executive, KernelMode, FALSE, NULL); if (NT_SUCCESS (status)) status = ioStatusBlock.Status; } ObDereferenceObject (deviceObject); return status; } NTSTATUS TCReadDevice (PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length) { return TCReadWriteDevice (FALSE, deviceObject, buffer, offset, length); } NTSTATUS TCWriteDevice (PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length) { return TCReadWriteDevice (TRUE, deviceObject, buffer, offset, length); } NTSTATUS TCFsctlCall (PFILE_OBJECT fileObject, LONG IoControlCode, void *InputBuffer, int InputBufferSize, void *OutputBuffer, int OutputBufferSize) { IO_STATUS_BLOCK ioStatusBlock; NTSTATUS ntStatus; PIRP irp; KEVENT event; PIO_STACK_LOCATION stack; PDEVICE_OBJECT deviceObject = IoGetRelatedDeviceObject (fileObject); KeInitializeEvent(&event, NotificationEvent, FALSE); irp = IoBuildDeviceIoControlRequest (IoControlCode, deviceObject, InputBuffer, InputBufferSize, OutputBuffer, OutputBufferSize, FALSE, &event, &ioStatusBlock); if (irp == NULL) return STATUS_INSUFFICIENT_RESOURCES; stack = IoGetNextIrpStackLocation(irp); stack->MajorFunction = IRP_MJ_FILE_SYSTEM_CONTROL; stack->MinorFunction = IRP_MN_USER_FS_REQUEST; stack->FileObject = fileObject; ntStatus = IoCallDriver (deviceObject, irp); if (ntStatus == STATUS_PENDING) { KeWaitForSingleObject (&event, Executive, KernelMode, FALSE, NULL); ntStatus = ioStatusBlock.Status; } return ntStatus; } NTSTATUS CreateDriveLink (int nDosDriveNo) { WCHAR dev[128], link[128]; UNICODE_STRING deviceName, symLink; NTSTATUS ntStatus; TCGetNTNameFromNumber (dev, sizeof(dev),nDosDriveNo); TCGetDosNameFromNumber (link, sizeof(link),nDosDriveNo, DeviceNamespaceDefault); RtlInitUnicodeString (&deviceName, dev); RtlInitUnicodeString (&symLink, link); ntStatus = IoCreateSymbolicLink (&symLink, &deviceName); Dump ("IoCreateSymbolicLink returned %X\n", ntStatus); return ntStatus; } NTSTATUS RemoveDriveLink (int nDosDriveNo) { WCHAR link[256]; UNICODE_STRING symLink; NTSTATUS ntStatus; TCGetDosNameFromNumber (link, sizeof(link),nDosDriveNo, DeviceNamespaceDefault); RtlInitUnicodeString (&symLink, link); ntStatus = IoDeleteSymbolicLink (&symLink); Dump ("IoDeleteSymbolicLink returned %X\n", ntStatus); return ntStatus; } NTSTATUS MountManagerMount (MOUNT_STRUCT *mount) { NTSTATUS ntStatus; WCHAR arrVolume[256]; char buf[200]; PMOUNTMGR_TARGET_NAME in = (PMOUNTMGR_TARGET_NAME) buf; PMOUNTMGR_CREATE_POINT_INPUT point = (PMOUNTMGR_CREATE_POINT_INPUT) buf; TCGetNTNameFromNumber (arrVolume, sizeof(arrVolume),mount->nDosDriveNo); in->DeviceNameLength = (USHORT) wcslen (arrVolume) * 2; RtlStringCbCopyW(in->DeviceName, sizeof(buf) - sizeof(in->DeviceNameLength),arrVolume); ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION, in, (ULONG) (sizeof (in->DeviceNameLength) + wcslen (arrVolume) * 2), 0, 0); memset (buf, 0, sizeof buf); TCGetDosNameFromNumber ((PWSTR) &point[1], sizeof(buf) - sizeof(MOUNTMGR_CREATE_POINT_INPUT),mount->nDosDriveNo, DeviceNamespaceDefault); point->SymbolicLinkNameOffset = sizeof (MOUNTMGR_CREATE_POINT_INPUT); point->SymbolicLinkNameLength = (USHORT) wcslen ((PWSTR) &point[1]) * 2; point->DeviceNameOffset = point->SymbolicLinkNameOffset + point->SymbolicLinkNameLength; TCGetNTNameFromNumber ((PWSTR) (buf + point->DeviceNameOffset), sizeof(buf) - point->DeviceNameOffset,mount->nDosDriveNo); point->DeviceNameLength = (USHORT) wcslen ((PWSTR) (buf + point->DeviceNameOffset)) * 2; ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_CREATE_POINT, point, point->DeviceNameOffset + point->DeviceNameLength, 0, 0); return ntStatus; } NTSTATUS MountManagerUnmount (int nDosDriveNo) { NTSTATUS ntStatus; char buf[256], out[300]; PMOUNTMGR_MOUNT_POINT in = (PMOUNTMGR_MOUNT_POINT) buf; memset (buf, 0, sizeof buf); TCGetDosNameFromNumber ((PWSTR) &in[1], sizeof(buf) - sizeof(MOUNTMGR_MOUNT_POINT),nDosDriveNo, DeviceNamespaceDefault); // Only symbolic link can be deleted with IOCTL_MOUNTMGR_DELETE_POINTS. If any other entry is specified, the mount manager will ignore subsequent IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION for the same volume ID. in->SymbolicLinkNameOffset = sizeof (MOUNTMGR_MOUNT_POINT); in->SymbolicLinkNameLength = (USHORT) wcslen ((PWCHAR) &in[1]) * 2; ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_DELETE_POINTS, in, sizeof(MOUNTMGR_MOUNT_POINT) + in->SymbolicLinkNameLength, out, sizeof out); Dump ("IOCTL_MOUNTMGR_DELETE_POINTS returned 0x%08x\n", ntStatus); return ntStatus; } NTSTATUS MountDevice (PDEVICE_OBJECT DeviceObject, MOUNT_STRUCT *mount) { PDEVICE_OBJECT NewDeviceObject; NTSTATUS ntStatus; // Make sure the user is asking for a reasonable nDosDriveNo if (mount->nDosDriveNo >= 0 && mount->nDosDriveNo <= 25 && IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceDefault) // drive letter must not exist both locally and globally && IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceGlobal) ) { Dump ("Mount request looks valid\n"); } else { Dump ("WARNING: MOUNT DRIVE LETTER INVALID\n"); mount->nReturnCode = ERR_DRIVE_NOT_FOUND; return ERR_DRIVE_NOT_FOUND; } if (!SelfTestsPassed) { Dump ("Failure of built-in automatic self-tests! Mounting not allowed.\n"); mount->nReturnCode = ERR_SELF_TESTS_FAILED; return ERR_SELF_TESTS_FAILED; } ntStatus = TCCreateDeviceObject (DeviceObject->DriverObject, &NewDeviceObject, mount); if (!NT_SUCCESS (ntStatus)) { Dump ("Mount CREATE DEVICE ERROR, ntStatus = 0x%08x\n", ntStatus); return ntStatus; } else { PEXTENSION NewExtension = (PEXTENSION) NewDeviceObject->DeviceExtension; SECURITY_SUBJECT_CONTEXT subContext; PACCESS_TOKEN accessToken; SeCaptureSubjectContext (&subContext); SeLockSubjectContext(&subContext); if (subContext.ClientToken && subContext.ImpersonationLevel >= SecurityImpersonation) accessToken = subContext.ClientToken; else accessToken = subContext.PrimaryToken; if (!accessToken) { ntStatus = STATUS_INVALID_PARAMETER; } else { PTOKEN_USER tokenUser; ntStatus = SeQueryInformationToken (accessToken, TokenUser, &tokenUser); if (NT_SUCCESS (ntStatus)) { ULONG sidLength = RtlLengthSid (tokenUser->User.Sid); NewExtension->UserSid = TCalloc (sidLength); if (!NewExtension->UserSid) ntStatus = STATUS_INSUFFICIENT_RESOURCES; else ntStatus = RtlCopySid (sidLength, NewExtension->UserSid, tokenUser->User.Sid); ExFreePool (tokenUser); // Documented in newer versions of WDK } } SeUnlockSubjectContext(&subContext); SeReleaseSubjectContext (&subContext); if (NT_SUCCESS (ntStatus)) ntStatus = TCStartVolumeThread (NewDeviceObject, NewExtension, mount); if (!NT_SUCCESS (ntStatus)) { Dump ("Mount FAILURE NT ERROR, ntStatus = 0x%08x\n", ntStatus); TCDeleteDeviceObject (NewDeviceObject, NewExtension); return ntStatus; } else { if (mount->nReturnCode == 0) { HANDLE volumeHandle; PFILE_OBJECT volumeFileObject; ULONG labelLen = (ULONG) wcslen (mount->wszLabel); BOOL bIsNTFS = FALSE; ULONG labelMaxLen, labelEffectiveLen; Dump ("Mount SUCCESS TC code = 0x%08x READ-ONLY = %d\n", mount->nReturnCode, NewExtension->bReadOnly); if (NewExtension->bReadOnly) NewDeviceObject->Characteristics |= FILE_READ_ONLY_DEVICE; NewDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; NewExtension->UniqueVolumeId = LastUniqueVolumeId++; // check again that the drive letter is available globally and locally if ( !IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceDefault) || !IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceGlobal) ) { TCDeleteDeviceObject (NewDeviceObject, NewExtension); mount->nReturnCode = ERR_DRIVE_NOT_FOUND; return ERR_DRIVE_NOT_FOUND; } if (mount->bMountManager) MountManagerMount (mount); NewExtension->bMountManager = mount->bMountManager; // We create symbolic link even if mount manager is notified of // arriving volume as it apparently sometimes fails to create the link CreateDriveLink (mount->nDosDriveNo); mount->FilesystemDirty = FALSE; if (NT_SUCCESS (TCOpenFsVolume (NewExtension, &volumeHandle, &volumeFileObject))) { __try { ULONG fsStatus; if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_IS_VOLUME_DIRTY, NULL, 0, &fsStatus, sizeof (fsStatus))) && (fsStatus & VOLUME_IS_DIRTY)) { mount->FilesystemDirty = TRUE; } } __except (EXCEPTION_EXECUTE_HANDLER) { mount->FilesystemDirty = TRUE; } // detect if the filesystem is NTFS or FAT __try { NTFS_VOLUME_DATA_BUFFER ntfsData; if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsData, sizeof (ntfsData)))) { bIsNTFS = TRUE; } } __except (EXCEPTION_EXECUTE_HANDLER) { bIsNTFS = FALSE; } NewExtension->bIsNTFS = bIsNTFS; mount->bIsNTFS = bIsNTFS; if (labelLen > 0) { if (bIsNTFS) labelMaxLen = 32; // NTFS maximum label length else labelMaxLen = 11; // FAT maximum label length // calculate label effective length labelEffectiveLen = labelLen > labelMaxLen? labelMaxLen : labelLen; // correct the label in the device memset (&NewExtension->wszLabel[labelEffectiveLen], 0, 33 - labelEffectiveLen); memcpy (mount->wszLabel, NewExtension->wszLabel, 33); // set the volume label __try { IO_STATUS_BLOCK ioblock; ULONG labelInfoSize = sizeof(FILE_FS_LABEL_INFORMATION) + (labelEffectiveLen * sizeof(WCHAR)); FILE_FS_LABEL_INFORMATION* labelInfo = (FILE_FS_LABEL_INFORMATION*) TCalloc (labelInfoSize); if (labelInfo) { labelInfo->VolumeLabelLength = labelEffectiveLen * sizeof(WCHAR); memcpy (labelInfo->VolumeLabel, mount->wszLabel, labelInfo->VolumeLabelLength); if (STATUS_SUCCESS == ZwSetVolumeInformationFile (volumeHandle, &ioblock, labelInfo, labelInfoSize, FileFsLabelInformation)) { mount->bDriverSetLabel = TRUE; NewExtension->bDriverSetLabel = TRUE; } TCfree(labelInfo); } } __except (EXCEPTION_EXECUTE_HANDLER) { } } TCCloseFsVolume (volumeHandle, volumeFileObject); } } else { Dump ("Mount FAILURE TC code = 0x%08x\n", mount->nReturnCode); TCDeleteDeviceObject (NewDeviceObject, NewExtension); } return STATUS_SUCCESS; } } } NTSTATUS UnmountDevice (UNMOUNT_STRUCT *unmountRequest, PDEVICE_OBJECT deviceObject, BOOL ignoreOpenFiles) { PEXTENSION extension = deviceObject->DeviceExtension; NTSTATUS ntStatus; HANDLE volumeHandle; PFILE_OBJECT volumeFileObject; Dump ("UnmountDevice %d\n", extension->nDosDriveNo); ntStatus = TCOpenFsVolume (extension, &volumeHandle, &volumeFileObject); if (NT_SUCCESS (ntStatus)) { int dismountRetry; // Dismounting a writable NTFS filesystem prevents the driver from being unloaded on Windows 7 if (IsOSAtLeast (WIN_7) && !extension->bReadOnly) { NTFS_VOLUME_DATA_BUFFER ntfsData; if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsData, sizeof (ntfsData)))) DriverUnloadDisabled = TRUE; } // Lock volume ntStatus = TCFsctlCall (volumeFileObject, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0); Dump ("FSCTL_LOCK_VOLUME returned %X\n", ntStatus); if (!NT_SUCCESS (ntStatus) && !ignoreOpenFiles) { TCCloseFsVolume (volumeHandle, volumeFileObject); return ERR_FILES_OPEN; } // Dismount volume for (dismountRetry = 0; dismountRetry < 200; ++dismountRetry) { ntStatus = TCFsctlCall (volumeFileObject, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0); Dump ("FSCTL_DISMOUNT_VOLUME returned %X\n", ntStatus); if (NT_SUCCESS (ntStatus) || ntStatus == STATUS_VOLUME_DISMOUNTED) break; if (!ignoreOpenFiles) { TCCloseFsVolume (volumeHandle, volumeFileObject); return ERR_FILES_OPEN; } TCSleep (100); } } else { // Volume cannot be opened => force dismount if allowed if (!ignoreOpenFiles) return ERR_FILES_OPEN; else volumeHandle = NULL; } if (extension->bMountManager) MountManagerUnmount (extension->nDosDriveNo); // We always remove symbolic link as mount manager might fail to do so RemoveDriveLink (extension->nDosDriveNo); extension->bShuttingDown = TRUE; ntStatus = IoAcquireRemoveLock (&extension->Queue.RemoveLock, NULL); ASSERT (NT_SUCCESS (ntStatus)); IoReleaseRemoveLockAndWait (&extension->Queue.RemoveLock, NULL); if (volumeHandle != NULL) TCCloseFsVolume (volumeHandle, volumeFileObject); if (unmountRequest) { PCRYPTO_INFO cryptoInfo = ((PEXTENSION) deviceObject->DeviceExtension)->cryptoInfo; unmountRequest->HiddenVolumeProtectionTriggered = (cryptoInfo->bProtectHiddenVolume && cryptoInfo->bHiddenVolProtectionAction); } TCDeleteDeviceObject (deviceObject, (PEXTENSION) deviceObject->DeviceExtension); return 0; } static PDEVICE_OBJECT FindVolumeWithHighestUniqueId (int maxUniqueId) { PDEVICE_OBJECT highestIdDevice = NULL; int highestId = -1; int drive; for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) { PDEVICE_OBJECT device = GetVirtualVolumeDeviceObject (drive); if (device) { PEXTENSION extension = (PEXTENSION) device->DeviceExtension; if (extension->UniqueVolumeId > highestId && extension->UniqueVolumeId <= maxUniqueId) { highestId = extension->UniqueVolumeId; highestIdDevice = device; } } } return highestIdDevice; } NTSTATUS UnmountAllDevices (UNMOUNT_STRUCT *unmountRequest, BOOL ignoreOpenFiles) { NTSTATUS status = 0; PDEVICE_OBJECT ListDevice; int maxUniqueId = LastUniqueVolumeId; Dump ("Unmounting all volumes\n"); if (unmountRequest) unmountRequest->HiddenVolumeProtectionTriggered = FALSE; // Dismount volumes in the reverse order they were mounted to properly dismount nested volumes while ((ListDevice = FindVolumeWithHighestUniqueId (maxUniqueId)) != NULL) { PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; maxUniqueId = ListExtension->UniqueVolumeId - 1; if (IsVolumeAccessibleByCurrentUser (ListExtension)) { NTSTATUS ntStatus; if (unmountRequest) unmountRequest->nDosDriveNo = ListExtension->nDosDriveNo; ntStatus = UnmountDevice (unmountRequest, ListDevice, ignoreOpenFiles); status = ntStatus == 0 ? status : ntStatus; if (unmountRequest && unmountRequest->HiddenVolumeProtectionTriggered) break; } } return status; } // Resolves symbolic link name to its target name NTSTATUS SymbolicLinkToTarget (PWSTR symlinkName, PWSTR targetName, USHORT maxTargetNameLength) { NTSTATUS ntStatus; OBJECT_ATTRIBUTES objectAttributes; UNICODE_STRING fullFileName; HANDLE handle; RtlInitUnicodeString (&fullFileName, symlinkName); InitializeObjectAttributes (&objectAttributes, &fullFileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); ntStatus = ZwOpenSymbolicLinkObject (&handle, GENERIC_READ, &objectAttributes); if (NT_SUCCESS (ntStatus)) { UNICODE_STRING target; target.Buffer = targetName; target.Length = 0; target.MaximumLength = maxTargetNameLength; memset (targetName, 0, maxTargetNameLength); ntStatus = ZwQuerySymbolicLinkObject (handle, &target, NULL); ZwClose (handle); } return ntStatus; } // Checks if two regions overlap (borders are parts of regions) BOOL RegionsOverlap (unsigned __int64 start1, unsigned __int64 end1, unsigned __int64 start2, unsigned __int64 end2) { return (start1 < start2) ? (end1 >= start2) : (start1 <= end2); } void GetIntersection (uint64 start1, uint32 length1, uint64 start2, uint64 end2, uint64 *intersectStart, uint32 *intersectLength) { uint64 end1 = start1 + length1 - 1; uint64 intersectEnd = (end1 <= end2) ? end1 : end2; *intersectStart = (start1 >= start2) ? start1 : start2; *intersectLength = (uint32) ((*intersectStart > intersectEnd) ? 0 : intersectEnd + 1 - *intersectStart); if (*intersectLength == 0) *intersectStart = start1; } BOOL IsAccessibleByUser (PUNICODE_STRING objectFileName, BOOL readOnly) { OBJECT_ATTRIBUTES fileObjAttributes; IO_STATUS_BLOCK ioStatusBlock; HANDLE fileHandle; NTSTATUS status; ASSERT (!IoIsSystemThread (PsGetCurrentThread())); InitializeObjectAttributes (&fileObjAttributes, objectFileName, OBJ_CASE_INSENSITIVE | OBJ_FORCE_ACCESS_CHECK | OBJ_KERNEL_HANDLE, NULL, NULL); status = ZwCreateFile (&fileHandle, readOnly ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE, &fileObjAttributes, &ioStatusBlock, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); if (NT_SUCCESS (status)) { ZwClose (fileHandle); return TRUE; } return FALSE; } BOOL UserCanAccessDriveDevice () { UNICODE_STRING name; RtlInitUnicodeString (&name, L"\\Device\\MountPointManager"); return IsAccessibleByUser (&name, FALSE); } BOOL IsDriveLetterAvailable (int nDosDriveNo, DeviceNamespaceType namespaceType) { OBJECT_ATTRIBUTES objectAttributes; UNICODE_STRING objectName; WCHAR link[128]; HANDLE handle; NTSTATUS ntStatus; TCGetDosNameFromNumber (link, sizeof(link),nDosDriveNo, namespaceType); RtlInitUnicodeString (&objectName, link); InitializeObjectAttributes (&objectAttributes, &objectName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); if (NT_SUCCESS (ntStatus = ZwOpenSymbolicLinkObject (&handle, GENERIC_READ, &objectAttributes))) { ZwClose (handle); return FALSE; } return (ntStatus == STATUS_OBJECT_NAME_NOT_FOUND)? TRUE : FALSE; } NTSTATUS TCCompleteIrp (PIRP irp, NTSTATUS status, ULONG_PTR information) { irp->IoStatus.Status = status; irp->IoStatus.Information = information; IoCompleteRequest (irp, IO_NO_INCREMENT); return status; } NTSTATUS TCCompleteDiskIrp (PIRP irp, NTSTATUS status, ULONG_PTR information) { irp->IoStatus.Status = status; irp->IoStatus.Information = information; IoCompleteRequest (irp, NT_SUCCESS (status) ? IO_DISK_INCREMENT : IO_NO_INCREMENT); return status; } size_t GetCpuCount () { KAFFINITY activeCpuMap = KeQueryActiveProcessors(); size_t mapSize = sizeof (activeCpuMap) * 8; size_t cpuCount = 0; while (mapSize--) { if (activeCpuMap & 1) ++cpuCount; activeCpuMap >>= 1; } if (cpuCount == 0) return 1; return cpuCount; } void EnsureNullTerminatedString (wchar_t *str, size_t maxSizeInBytes) { ASSERT ((maxSizeInBytes & 1) == 0); str[maxSizeInBytes / sizeof (wchar_t) - 1] = 0; } void *AllocateMemoryWithTimeout (size_t size, int retryDelay, int timeout) { LARGE_INTEGER waitInterval; waitInterval.QuadPart = retryDelay * -10000; ASSERT (KeGetCurrentIrql() <= APC_LEVEL); ASSERT (retryDelay > 0 && retryDelay <= timeout); while (TRUE) { void *memory = TCalloc (size); if (memory) return memory; timeout -= retryDelay; if (timeout <= 0) break; KeDelayExecutionThread (KernelMode, FALSE, &waitInterval); } return NULL; } NTSTATUS TCReadRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, PKEY_VALUE_PARTIAL_INFORMATION *keyData) { OBJECT_ATTRIBUTES regObjAttribs; HANDLE regKeyHandle; NTSTATUS status; UNICODE_STRING valName; ULONG size = 0; ULONG resultSize; InitializeObjectAttributes (&regObjAttribs, keyPath, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); status = ZwOpenKey (&regKeyHandle, KEY_READ, &regObjAttribs); if (!NT_SUCCESS (status)) return status; RtlInitUnicodeString (&valName, keyValueName); status = ZwQueryValueKey (regKeyHandle, &valName, KeyValuePartialInformation, NULL, 0, &size); if (!NT_SUCCESS (status) && status != STATUS_BUFFER_OVERFLOW && status != STATUS_BUFFER_TOO_SMALL) { ZwClose (regKeyHandle); return status; } if (size == 0) { ZwClose (regKeyHandle); return STATUS_NO_DATA_DETECTED; } *keyData = (PKEY_VALUE_PARTIAL_INFORMATION) TCalloc (size); if (!*keyData) { ZwClose (regKeyHandle); return STATUS_INSUFFICIENT_RESOURCES; } status = ZwQueryValueKey (regKeyHandle, &valName, KeyValuePartialInformation, *keyData, size, &resultSize); ZwClose (regKeyHandle); return status; } NTSTATUS TCWriteRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, ULONG keyValueType, void *valueData, ULONG valueSize) { OBJECT_ATTRIBUTES regObjAttribs; HANDLE regKeyHandle; NTSTATUS status; UNICODE_STRING valName; InitializeObjectAttributes (&regObjAttribs, keyPath, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); status = ZwOpenKey (&regKeyHandle, KEY_READ | KEY_WRITE, &regObjAttribs); if (!NT_SUCCESS (status)) return status; RtlInitUnicodeString (&valName, keyValueName); status = ZwSetValueKey (regKeyHandle, &valName, 0, keyValueType, valueData, valueSize); ZwClose (regKeyHandle); return status; } BOOL IsVolumeClassFilterRegistered () { UNICODE_STRING name; NTSTATUS status; BOOL registered = FALSE; PKEY_VALUE_PARTIAL_INFORMATION data; RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{71A27CDD-812A-11D0-BEC7-08002BE2092F}"); status = TCReadRegistryKey (&name, L"UpperFilters", &data); if (NT_SUCCESS (status)) { if (data->Type == REG_MULTI_SZ && data->DataLength >= 9 * sizeof (wchar_t)) { // Search for the string "veracrypt" ULONG i; for (i = 0; i <= data->DataLength - 9 * sizeof (wchar_t); ++i) { if (memcmp (data->Data + i, L"veracrypt", 9 * sizeof (wchar_t)) == 0) { Dump ("Volume class filter active\n"); registered = TRUE; break; } } } TCfree (data); } return registered; } NTSTATUS ReadRegistryConfigFlags (BOOL driverEntry) { PKEY_VALUE_PARTIAL_INFORMATION data; UNICODE_STRING name; NTSTATUS status; uint32 flags = 0; RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\veracrypt"); status = TCReadRegistryKey (&name, TC_DRIVER_CONFIG_REG_VALUE_NAME, &data); if (NT_SUCCESS (status)) { if (data->Type == REG_DWORD) { flags = *(uint32 *) data->Data; Dump ("Configuration flags = 0x%x\n", flags); if (driverEntry) { if (flags & (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD | TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES)) CacheBootPassword = TRUE; if (flags & TC_DRIVER_CONFIG_DISABLE_NONADMIN_SYS_FAVORITES_ACCESS) NonAdminSystemFavoritesAccessDisabled = TRUE; if (flags & TC_DRIVER_CONFIG_CACHE_BOOT_PIM) CacheBootPim = TRUE; if (flags & VC_DRIVER_CONFIG_BLOCK_SYS_TRIM) BlockSystemTrimCommand = TRUE; } EnableHwEncryption ((flags & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? FALSE : TRUE); EnableExtendedIoctlSupport = (flags & TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL)? TRUE : FALSE; AllowTrimCommand = (flags & VC_DRIVER_CONFIG_ALLOW_NONSYS_TRIM)? TRUE : FALSE; AllowWindowsDefrag = (flags & VC_DRIVER_CONFIG_ALLOW_WINDOWS_DEFRAG)? TRUE : FALSE; } else status = STATUS_INVALID_PARAMETER; TCfree (data); } if (driverEntry && NT_SUCCESS (TCReadRegistryKey (&name, TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME, &data))) { if (data->Type == REG_DWORD) EncryptionThreadPoolFreeCpuCountLimit = *(uint32 *) data->Data; TCfree (data); } return status; } NTSTATUS WriteRegistryConfigFlags (uint32 flags) { UNICODE_STRING name; RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\veracrypt"); return TCWriteRegistryKey (&name, TC_DRIVER_CONFIG_REG_VALUE_NAME, REG_DWORD, &flags, sizeof (flags)); } NTSTATUS GetDeviceSectorSize (PDEVICE_OBJECT deviceObject, ULONG *bytesPerSector) { NTSTATUS status; DISK_GEOMETRY geometry; status = SendDeviceIoControlRequest (deviceObject, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &geometry, sizeof (geometry)); if (!NT_SUCCESS (status)) return status; *bytesPerSector = geometry.BytesPerSector; return STATUS_SUCCESS; } NTSTATUS ZeroUnreadableSectors (PDEVICE_OBJECT deviceObject, LARGE_INTEGER startOffset, ULONG size, uint64 *zeroedSectorCount) { NTSTATUS status; ULONG sectorSize; ULONG sectorCount; byte *sectorBuffer = NULL; *zeroedSectorCount = 0; status = GetDeviceSectorSize (deviceObject, &sectorSize); if (!NT_SUCCESS (status)) return status; sectorBuffer = TCalloc (sectorSize); if (!sectorBuffer) return STATUS_INSUFFICIENT_RESOURCES; for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount, startOffset.QuadPart += sectorSize) { status = TCReadDevice (deviceObject, sectorBuffer, startOffset, sectorSize); if (!NT_SUCCESS (status)) { Dump ("Zeroing sector at %I64d\n", startOffset.QuadPart); memset (sectorBuffer, 0, sectorSize); status = TCWriteDevice (deviceObject, sectorBuffer, startOffset, sectorSize); if (!NT_SUCCESS (status)) goto err; ++(*zeroedSectorCount); } } status = STATUS_SUCCESS; err: if (sectorBuffer) TCfree (sectorBuffer); return status; } NTSTATUS ReadDeviceSkipUnreadableSectors (PDEVICE_OBJECT deviceObject, byte *buffer, LARGE_INTEGER startOffset, ULONG size, uint64 *badSectorCount) { NTSTATUS status; ULONG sectorSize; ULONG sectorCount; *badSectorCount = 0; status = GetDeviceSectorSize (deviceObject, &sectorSize); if (!NT_SUCCESS (status)) return status; for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount, startOffset.QuadPart += sectorSize, buffer += sectorSize) { status = TCReadDevice (deviceObject, buffer, startOffset, sectorSize); if (!NT_SUCCESS (status)) { Dump ("Skipping bad sector at %I64d\n", startOffset.QuadPart); memset (buffer, 0, sectorSize); ++(*badSectorCount); } } return STATUS_SUCCESS; } BOOL IsVolumeAccessibleByCurrentUser (PEXTENSION volumeDeviceExtension) { SECURITY_SUBJECT_CONTEXT subContext; PACCESS_TOKEN accessToken; PTOKEN_USER tokenUser; BOOL result = FALSE; if (IoIsSystemThread (PsGetCurrentThread()) || UserCanAccessDriveDevice() || !volumeDeviceExtension->UserSid || (volumeDeviceExtension->SystemFavorite && !NonAdminSystemFavoritesAccessDisabled)) { return TRUE; } SeCaptureSubjectContext (&subContext); SeLockSubjectContext(&subContext); if (subContext.ClientToken && subContext.ImpersonationLevel >= SecurityImpersonation) accessToken = subContext.ClientToken; else accessToken = subContext.PrimaryToken; if (!accessToken) goto ret; if (SeTokenIsAdmin (accessToken)) { result = TRUE; goto ret; } if (!NT_SUCCESS (SeQueryInformationToken (accessToken, TokenUser, &tokenUser))) goto ret; result = RtlEqualSid (volumeDeviceExtension->UserSid, tokenUser->User.Sid); ExFreePool (tokenUser); // Documented in newer versions of WDK ret: SeUnlockSubjectContext(&subContext); SeReleaseSubjectContext (&subContext); return result; } void GetElapsedTimeInit (LARGE_INTEGER *lastPerfCounter) { *lastPerfCounter = KeQueryPerformanceCounter (NULL); } // Returns elapsed time in microseconds since last call int64 GetElapsedTime (LARGE_INTEGER *lastPerfCounter) { LARGE_INTEGER freq; LARGE_INTEGER counter = KeQueryPerformanceCounter (&freq); int64 elapsed = (counter.QuadPart - lastPerfCounter->QuadPart) * 1000000LL / freq.QuadPart; *lastPerfCounter = counter; return elapsed; } BOOL IsOSAtLeast (OSVersionEnum reqMinOS) { /* When updating this function, update IsOSVersionAtLeast() in Dlgcode.c too. */ ULONG major = 0, minor = 0; ASSERT (OsMajorVersion != 0); switch (reqMinOS) { case WIN_2000: major = 5; minor = 0; break; case WIN_XP: major = 5; minor = 1; break; case WIN_SERVER_2003: major = 5; minor = 2; break; case WIN_VISTA: major = 6; minor = 0; break; case WIN_7: major = 6; minor = 1; break; case WIN_8: major = 6; minor = 2; break; case WIN_8_1: major = 6; minor = 3; break; case WIN_10: major = 10; minor = 0; break; default: TC_THROW_FATAL_EXCEPTION; break; } return ((OsMajorVersion << 16 | OsMinorVersion << 8) >= (major << 16 | minor << 8)); } NTSTATUS NTAPI KeSaveExtendedProcessorState ( __in ULONG64 Mask, PXSTATE_SAVE XStateSave ) { if (KeSaveExtendedProcessorStatePtr) { return (KeSaveExtendedProcessorStatePtr) (Mask, XStateSave); } else { return STATUS_SUCCESS; } } VOID NTAPI KeRestoreExtendedProcessorState ( PXSTATE_SAVE XStateSave ) { if (KeRestoreExtendedProcessorStatePtr) { (KeRestoreExtendedProcessorStatePtr) (XStateSave); } }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_715_0
crossvul-cpp_data_good_4767_0
/* $OpenBSD: monitor.c,v 1.166 2016/09/28 16:33:06 djm Exp $ */ /* * Copyright 2002 Niels Provos <provos@citi.umich.edu> * Copyright 2002 Markus Friedl <markus@openbsd.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/types.h> #include <sys/wait.h> #include <sys/socket.h> #include <sys/tree.h> #include <sys/queue.h> #ifdef WITH_OPENSSL #include <openssl/dh.h> #endif #include <errno.h> #include <fcntl.h> #include <limits.h> #include <paths.h> #include <poll.h> #include <pwd.h> #include <signal.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "atomicio.h" #include "xmalloc.h" #include "ssh.h" #include "key.h" #include "buffer.h" #include "hostfile.h" #include "auth.h" #include "cipher.h" #include "kex.h" #include "dh.h" #include <zlib.h> #include "packet.h" #include "auth-options.h" #include "sshpty.h" #include "channels.h" #include "session.h" #include "sshlogin.h" #include "canohost.h" #include "log.h" #include "misc.h" #include "servconf.h" #include "monitor.h" #ifdef GSSAPI #include "ssh-gss.h" #endif #include "monitor_wrap.h" #include "monitor_fdpass.h" #include "compat.h" #include "ssh2.h" #include "authfd.h" #include "match.h" #include "ssherr.h" #ifdef GSSAPI static Gssctxt *gsscontext = NULL; #endif /* Imports */ extern ServerOptions options; extern u_int utmp_len; extern u_char session_id[]; extern Buffer auth_debug; extern int auth_debug_init; extern Buffer loginmsg; /* State exported from the child */ static struct sshbuf *child_state; /* Functions on the monitor that answer unprivileged requests */ int mm_answer_moduli(int, Buffer *); int mm_answer_sign(int, Buffer *); int mm_answer_pwnamallow(int, Buffer *); int mm_answer_auth2_read_banner(int, Buffer *); int mm_answer_authserv(int, Buffer *); int mm_answer_authpassword(int, Buffer *); int mm_answer_bsdauthquery(int, Buffer *); int mm_answer_bsdauthrespond(int, Buffer *); int mm_answer_skeyquery(int, Buffer *); int mm_answer_skeyrespond(int, Buffer *); int mm_answer_keyallowed(int, Buffer *); int mm_answer_keyverify(int, Buffer *); int mm_answer_pty(int, Buffer *); int mm_answer_pty_cleanup(int, Buffer *); int mm_answer_term(int, Buffer *); int mm_answer_rsa_keyallowed(int, Buffer *); int mm_answer_rsa_challenge(int, Buffer *); int mm_answer_rsa_response(int, Buffer *); int mm_answer_sesskey(int, Buffer *); int mm_answer_sessid(int, Buffer *); #ifdef GSSAPI int mm_answer_gss_setup_ctx(int, Buffer *); int mm_answer_gss_accept_ctx(int, Buffer *); int mm_answer_gss_userok(int, Buffer *); int mm_answer_gss_checkmic(int, Buffer *); #endif static int monitor_read_log(struct monitor *); static Authctxt *authctxt; /* local state for key verify */ static u_char *key_blob = NULL; static u_int key_bloblen = 0; static int key_blobtype = MM_NOKEY; static char *hostbased_cuser = NULL; static char *hostbased_chost = NULL; static char *auth_method = "unknown"; static char *auth_submethod = NULL; static u_int session_id2_len = 0; static u_char *session_id2 = NULL; static pid_t monitor_child_pid; struct mon_table { enum monitor_reqtype type; int flags; int (*f)(int, Buffer *); }; #define MON_ISAUTH 0x0004 /* Required for Authentication */ #define MON_AUTHDECIDE 0x0008 /* Decides Authentication */ #define MON_ONCE 0x0010 /* Disable after calling */ #define MON_ALOG 0x0020 /* Log auth attempt without authenticating */ #define MON_AUTH (MON_ISAUTH|MON_AUTHDECIDE) #define MON_PERMIT 0x1000 /* Request is permitted */ struct mon_table mon_dispatch_proto20[] = { #ifdef WITH_OPENSSL {MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli}, #endif {MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign}, {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow}, {MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv}, {MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner}, {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword}, {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery}, {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond}, {MONITOR_REQ_KEYALLOWED, MON_ISAUTH, mm_answer_keyallowed}, {MONITOR_REQ_KEYVERIFY, MON_AUTH, mm_answer_keyverify}, #ifdef GSSAPI {MONITOR_REQ_GSSSETUP, MON_ISAUTH, mm_answer_gss_setup_ctx}, {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx}, {MONITOR_REQ_GSSUSEROK, MON_ONCE|MON_AUTHDECIDE, mm_answer_gss_userok}, {MONITOR_REQ_GSSCHECKMIC, MON_ONCE, mm_answer_gss_checkmic}, #endif {0, 0, NULL} }; struct mon_table mon_dispatch_postauth20[] = { #ifdef WITH_OPENSSL {MONITOR_REQ_MODULI, 0, mm_answer_moduli}, #endif {MONITOR_REQ_SIGN, 0, mm_answer_sign}, {MONITOR_REQ_PTY, 0, mm_answer_pty}, {MONITOR_REQ_PTYCLEANUP, 0, mm_answer_pty_cleanup}, {MONITOR_REQ_TERM, 0, mm_answer_term}, {0, 0, NULL} }; struct mon_table *mon_dispatch; /* Specifies if a certain message is allowed at the moment */ static void monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit) { while (ent->f != NULL) { if (ent->type == type) { ent->flags &= ~MON_PERMIT; ent->flags |= permit ? MON_PERMIT : 0; return; } ent++; } } static void monitor_permit_authentications(int permit) { struct mon_table *ent = mon_dispatch; while (ent->f != NULL) { if (ent->flags & MON_AUTH) { ent->flags &= ~MON_PERMIT; ent->flags |= permit ? MON_PERMIT : 0; } ent++; } } void monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor) { struct mon_table *ent; int authenticated = 0, partial = 0; debug3("preauth child monitor started"); close(pmonitor->m_recvfd); close(pmonitor->m_log_sendfd); pmonitor->m_log_sendfd = pmonitor->m_recvfd = -1; authctxt = _authctxt; memset(authctxt, 0, sizeof(*authctxt)); mon_dispatch = mon_dispatch_proto20; /* Permit requests for moduli and signatures */ monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1); monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1); /* The first few requests do not require asynchronous access */ while (!authenticated) { partial = 0; auth_method = "unknown"; auth_submethod = NULL; authenticated = (monitor_read(pmonitor, mon_dispatch, &ent) == 1); /* Special handling for multiple required authentications */ if (options.num_auth_methods != 0) { if (authenticated && !auth2_update_methods_lists(authctxt, auth_method, auth_submethod)) { debug3("%s: method %s: partial", __func__, auth_method); authenticated = 0; partial = 1; } } if (authenticated) { if (!(ent->flags & MON_AUTHDECIDE)) fatal("%s: unexpected authentication from %d", __func__, ent->type); if (authctxt->pw->pw_uid == 0 && !auth_root_allowed(auth_method)) authenticated = 0; } if (ent->flags & (MON_AUTHDECIDE|MON_ALOG)) { auth_log(authctxt, authenticated, partial, auth_method, auth_submethod); if (!partial && !authenticated) authctxt->failures++; } } if (!authctxt->valid) fatal("%s: authenticated invalid user", __func__); if (strcmp(auth_method, "unknown") == 0) fatal("%s: authentication method name unknown", __func__); debug("%s: %s has been authenticated by privileged process", __func__, authctxt->user); mm_get_keystate(pmonitor); /* Drain any buffered messages from the child */ while (pmonitor->m_log_recvfd != -1 && monitor_read_log(pmonitor) == 0) ; close(pmonitor->m_sendfd); close(pmonitor->m_log_recvfd); pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1; } static void monitor_set_child_handler(pid_t pid) { monitor_child_pid = pid; } static void monitor_child_handler(int sig) { kill(monitor_child_pid, sig); } void monitor_child_postauth(struct monitor *pmonitor) { close(pmonitor->m_recvfd); pmonitor->m_recvfd = -1; monitor_set_child_handler(pmonitor->m_pid); signal(SIGHUP, &monitor_child_handler); signal(SIGTERM, &monitor_child_handler); signal(SIGINT, &monitor_child_handler); mon_dispatch = mon_dispatch_postauth20; /* Permit requests for moduli and signatures */ monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1); monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1); monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1); if (!no_pty_flag) { monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1); monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1); } for (;;) monitor_read(pmonitor, mon_dispatch, NULL); } static int monitor_read_log(struct monitor *pmonitor) { Buffer logmsg; u_int len, level; char *msg; buffer_init(&logmsg); /* Read length */ buffer_append_space(&logmsg, 4); if (atomicio(read, pmonitor->m_log_recvfd, buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg)) { if (errno == EPIPE) { buffer_free(&logmsg); debug("%s: child log fd closed", __func__); close(pmonitor->m_log_recvfd); pmonitor->m_log_recvfd = -1; return -1; } fatal("%s: log fd read: %s", __func__, strerror(errno)); } len = buffer_get_int(&logmsg); if (len <= 4 || len > 8192) fatal("%s: invalid log message length %u", __func__, len); /* Read severity, message */ buffer_clear(&logmsg); buffer_append_space(&logmsg, len); if (atomicio(read, pmonitor->m_log_recvfd, buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg)) fatal("%s: log fd read: %s", __func__, strerror(errno)); /* Log it */ level = buffer_get_int(&logmsg); msg = buffer_get_string(&logmsg, NULL); if (log_level_name(level) == NULL) fatal("%s: invalid log level %u (corrupted message?)", __func__, level); do_log2(level, "%s [preauth]", msg); buffer_free(&logmsg); free(msg); return 0; } int monitor_read(struct monitor *pmonitor, struct mon_table *ent, struct mon_table **pent) { Buffer m; int ret; u_char type; struct pollfd pfd[2]; for (;;) { memset(&pfd, 0, sizeof(pfd)); pfd[0].fd = pmonitor->m_sendfd; pfd[0].events = POLLIN; pfd[1].fd = pmonitor->m_log_recvfd; pfd[1].events = pfd[1].fd == -1 ? 0 : POLLIN; if (poll(pfd, pfd[1].fd == -1 ? 1 : 2, -1) == -1) { if (errno == EINTR || errno == EAGAIN) continue; fatal("%s: poll: %s", __func__, strerror(errno)); } if (pfd[1].revents) { /* * Drain all log messages before processing next * monitor request. */ monitor_read_log(pmonitor); continue; } if (pfd[0].revents) break; /* Continues below */ } buffer_init(&m); mm_request_receive(pmonitor->m_sendfd, &m); type = buffer_get_char(&m); debug3("%s: checking request %d", __func__, type); while (ent->f != NULL) { if (ent->type == type) break; ent++; } if (ent->f != NULL) { if (!(ent->flags & MON_PERMIT)) fatal("%s: unpermitted request %d", __func__, type); ret = (*ent->f)(pmonitor->m_sendfd, &m); buffer_free(&m); /* The child may use this request only once, disable it */ if (ent->flags & MON_ONCE) { debug2("%s: %d used once, disabling now", __func__, type); ent->flags &= ~MON_PERMIT; } if (pent != NULL) *pent = ent; return ret; } fatal("%s: unsupported request: %d", __func__, type); /* NOTREACHED */ return (-1); } /* allowed key state */ static int monitor_allowed_key(u_char *blob, u_int bloblen) { /* make sure key is allowed */ if (key_blob == NULL || key_bloblen != bloblen || timingsafe_bcmp(key_blob, blob, key_bloblen)) return (0); return (1); } static void monitor_reset_key_state(void) { /* reset state */ free(key_blob); free(hostbased_cuser); free(hostbased_chost); key_blob = NULL; key_bloblen = 0; key_blobtype = MM_NOKEY; hostbased_cuser = NULL; hostbased_chost = NULL; } #ifdef WITH_OPENSSL int mm_answer_moduli(int sock, Buffer *m) { DH *dh; int min, want, max; min = buffer_get_int(m); want = buffer_get_int(m); max = buffer_get_int(m); debug3("%s: got parameters: %d %d %d", __func__, min, want, max); /* We need to check here, too, in case the child got corrupted */ if (max < min || want < min || max < want) fatal("%s: bad parameters: %d %d %d", __func__, min, want, max); buffer_clear(m); dh = choose_dh(min, want, max); if (dh == NULL) { buffer_put_char(m, 0); return (0); } else { /* Send first bignum */ buffer_put_char(m, 1); buffer_put_bignum2(m, dh->p); buffer_put_bignum2(m, dh->g); DH_free(dh); } mm_request_send(sock, MONITOR_ANS_MODULI, m); return (0); } #endif int mm_answer_sign(int sock, Buffer *m) { struct ssh *ssh = active_state; /* XXX */ extern int auth_sock; /* XXX move to state struct? */ struct sshkey *key; struct sshbuf *sigbuf = NULL; u_char *p = NULL, *signature = NULL; char *alg = NULL; size_t datlen, siglen, alglen; int r, is_proof = 0; u_int keyid; const char proof_req[] = "hostkeys-prove-00@openssh.com"; debug3("%s", __func__); if ((r = sshbuf_get_u32(m, &keyid)) != 0 || (r = sshbuf_get_string(m, &p, &datlen)) != 0 || (r = sshbuf_get_cstring(m, &alg, &alglen)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); if (keyid > INT_MAX) fatal("%s: invalid key ID", __func__); /* * Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes), * SHA384 (48 bytes) and SHA512 (64 bytes). * * Otherwise, verify the signature request is for a hostkey * proof. * * XXX perform similar check for KEX signature requests too? * it's not trivial, since what is signed is the hash, rather * than the full kex structure... */ if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64) { /* * Construct expected hostkey proof and compare it to what * the client sent us. */ if (session_id2_len == 0) /* hostkeys is never first */ fatal("%s: bad data length: %zu", __func__, datlen); if ((key = get_hostkey_public_by_index(keyid, ssh)) == NULL) fatal("%s: no hostkey for index %d", __func__, keyid); if ((sigbuf = sshbuf_new()) == NULL) fatal("%s: sshbuf_new", __func__); if ((r = sshbuf_put_cstring(sigbuf, proof_req)) != 0 || (r = sshbuf_put_string(sigbuf, session_id2, session_id2_len)) != 0 || (r = sshkey_puts(key, sigbuf)) != 0) fatal("%s: couldn't prepare private key " "proof buffer: %s", __func__, ssh_err(r)); if (datlen != sshbuf_len(sigbuf) || memcmp(p, sshbuf_ptr(sigbuf), sshbuf_len(sigbuf)) != 0) fatal("%s: bad data length: %zu, hostkey proof len %zu", __func__, datlen, sshbuf_len(sigbuf)); sshbuf_free(sigbuf); is_proof = 1; } /* save session id, it will be passed on the first call */ if (session_id2_len == 0) { session_id2_len = datlen; session_id2 = xmalloc(session_id2_len); memcpy(session_id2, p, session_id2_len); } if ((key = get_hostkey_by_index(keyid)) != NULL) { if ((r = sshkey_sign(key, &signature, &siglen, p, datlen, alg, datafellows)) != 0) fatal("%s: sshkey_sign failed: %s", __func__, ssh_err(r)); } else if ((key = get_hostkey_public_by_index(keyid, ssh)) != NULL && auth_sock > 0) { if ((r = ssh_agent_sign(auth_sock, key, &signature, &siglen, p, datlen, alg, datafellows)) != 0) { fatal("%s: ssh_agent_sign failed: %s", __func__, ssh_err(r)); } } else fatal("%s: no hostkey from index %d", __func__, keyid); debug3("%s: %s signature %p(%zu)", __func__, is_proof ? "KEX" : "hostkey proof", signature, siglen); sshbuf_reset(m); if ((r = sshbuf_put_string(m, signature, siglen)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); free(alg); free(p); free(signature); mm_request_send(sock, MONITOR_ANS_SIGN, m); /* Turn on permissions for getpwnam */ monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1); return (0); } /* Retrieves the password entry and also checks if the user is permitted */ int mm_answer_pwnamallow(int sock, Buffer *m) { char *username; struct passwd *pwent; int allowed = 0; u_int i; debug3("%s", __func__); if (authctxt->attempt++ != 0) fatal("%s: multiple attempts for getpwnam", __func__); username = buffer_get_string(m, NULL); pwent = getpwnamallow(username); authctxt->user = xstrdup(username); setproctitle("%s [priv]", pwent ? username : "unknown"); free(username); buffer_clear(m); if (pwent == NULL) { buffer_put_char(m, 0); authctxt->pw = fakepw(); goto out; } allowed = 1; authctxt->pw = pwent; authctxt->valid = 1; buffer_put_char(m, 1); buffer_put_string(m, pwent, sizeof(struct passwd)); buffer_put_cstring(m, pwent->pw_name); buffer_put_cstring(m, "*"); buffer_put_cstring(m, pwent->pw_gecos); buffer_put_cstring(m, pwent->pw_class); buffer_put_cstring(m, pwent->pw_dir); buffer_put_cstring(m, pwent->pw_shell); out: buffer_put_string(m, &options, sizeof(options)); #define M_CP_STROPT(x) do { \ if (options.x != NULL) \ buffer_put_cstring(m, options.x); \ } while (0) #define M_CP_STRARRAYOPT(x, nx) do { \ for (i = 0; i < options.nx; i++) \ buffer_put_cstring(m, options.x[i]); \ } while (0) /* See comment in servconf.h */ COPY_MATCH_STRING_OPTS(); #undef M_CP_STROPT #undef M_CP_STRARRAYOPT /* Create valid auth method lists */ if (auth2_setup_methods_lists(authctxt) != 0) { /* * The monitor will continue long enough to let the child * run to it's packet_disconnect(), but it must not allow any * authentication to succeed. */ debug("%s: no valid authentication method lists", __func__); } debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed); mm_request_send(sock, MONITOR_ANS_PWNAM, m); /* Allow service/style information on the auth context */ monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1); monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1); return (0); } int mm_answer_auth2_read_banner(int sock, Buffer *m) { char *banner; buffer_clear(m); banner = auth2_read_banner(); buffer_put_cstring(m, banner != NULL ? banner : ""); mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m); free(banner); return (0); } int mm_answer_authserv(int sock, Buffer *m) { monitor_permit_authentications(1); authctxt->service = buffer_get_string(m, NULL); authctxt->style = buffer_get_string(m, NULL); debug3("%s: service=%s, style=%s", __func__, authctxt->service, authctxt->style); if (strlen(authctxt->style) == 0) { free(authctxt->style); authctxt->style = NULL; } return (0); } int mm_answer_authpassword(int sock, Buffer *m) { static int call_count; char *passwd; int authenticated; u_int plen; if (!options.password_authentication) fatal("%s: password authentication not enabled", __func__); passwd = buffer_get_string(m, &plen); /* Only authenticate if the context is valid */ authenticated = options.password_authentication && auth_password(authctxt, passwd); explicit_bzero(passwd, strlen(passwd)); free(passwd); buffer_clear(m); buffer_put_int(m, authenticated); debug3("%s: sending result %d", __func__, authenticated); mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m); call_count++; if (plen == 0 && call_count == 1) auth_method = "none"; else auth_method = "password"; /* Causes monitor loop to terminate if authenticated */ return (authenticated); } int mm_answer_bsdauthquery(int sock, Buffer *m) { char *name, *infotxt; u_int numprompts; u_int *echo_on; char **prompts; u_int success; if (!options.kbd_interactive_authentication) fatal("%s: kbd-int authentication not enabled", __func__); success = bsdauth_query(authctxt, &name, &infotxt, &numprompts, &prompts, &echo_on) < 0 ? 0 : 1; buffer_clear(m); buffer_put_int(m, success); if (success) buffer_put_cstring(m, prompts[0]); debug3("%s: sending challenge success: %u", __func__, success); mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m); if (success) { free(name); free(infotxt); free(prompts); free(echo_on); } return (0); } int mm_answer_bsdauthrespond(int sock, Buffer *m) { char *response; int authok; if (!options.kbd_interactive_authentication) fatal("%s: kbd-int authentication not enabled", __func__); if (authctxt->as == NULL) fatal("%s: no bsd auth session", __func__); response = buffer_get_string(m, NULL); authok = options.challenge_response_authentication && auth_userresponse(authctxt->as, response, 0); authctxt->as = NULL; debug3("%s: <%s> = <%d>", __func__, response, authok); free(response); buffer_clear(m); buffer_put_int(m, authok); debug3("%s: sending authenticated: %d", __func__, authok); mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m); auth_method = "keyboard-interactive"; auth_submethod = "bsdauth"; return (authok != 0); } int mm_answer_keyallowed(int sock, Buffer *m) { Key *key; char *cuser, *chost; u_char *blob; u_int bloblen, pubkey_auth_attempt; enum mm_keytype type = 0; int allowed = 0; debug3("%s entering", __func__); type = buffer_get_int(m); cuser = buffer_get_string(m, NULL); chost = buffer_get_string(m, NULL); blob = buffer_get_string(m, &bloblen); pubkey_auth_attempt = buffer_get_int(m); key = key_from_blob(blob, bloblen); debug3("%s: key_from_blob: %p", __func__, key); if (key != NULL && authctxt->valid) { /* These should not make it past the privsep child */ if (key_type_plain(key->type) == KEY_RSA && (datafellows & SSH_BUG_RSASIGMD5) != 0) fatal("%s: passed a SSH_BUG_RSASIGMD5 key", __func__); switch (type) { case MM_USERKEY: allowed = options.pubkey_authentication && !auth2_userkey_already_used(authctxt, key) && match_pattern_list(sshkey_ssh_name(key), options.pubkey_key_types, 0) == 1 && user_key_allowed(authctxt->pw, key, pubkey_auth_attempt); pubkey_auth_info(authctxt, key, NULL); auth_method = "publickey"; if (options.pubkey_authentication && (!pubkey_auth_attempt || allowed != 1)) auth_clear_options(); break; case MM_HOSTKEY: allowed = options.hostbased_authentication && match_pattern_list(sshkey_ssh_name(key), options.hostbased_key_types, 0) == 1 && hostbased_key_allowed(authctxt->pw, cuser, chost, key); pubkey_auth_info(authctxt, key, "client user \"%.100s\", client host \"%.100s\"", cuser, chost); auth_method = "hostbased"; break; default: fatal("%s: unknown key type %d", __func__, type); break; } } debug3("%s: key %p is %s", __func__, key, allowed ? "allowed" : "not allowed"); if (key != NULL) key_free(key); /* clear temporarily storage (used by verify) */ monitor_reset_key_state(); if (allowed) { /* Save temporarily for comparison in verify */ key_blob = blob; key_bloblen = bloblen; key_blobtype = type; hostbased_cuser = cuser; hostbased_chost = chost; } else { /* Log failed attempt */ auth_log(authctxt, 0, 0, auth_method, NULL); free(blob); free(cuser); free(chost); } buffer_clear(m); buffer_put_int(m, allowed); buffer_put_int(m, forced_command != NULL); mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m); return (0); } static int monitor_valid_userblob(u_char *data, u_int datalen) { Buffer b; u_char *p; char *userstyle, *cp; u_int len; int fail = 0; buffer_init(&b); buffer_append(&b, data, datalen); if (datafellows & SSH_OLD_SESSIONID) { p = buffer_ptr(&b); len = buffer_len(&b); if ((session_id2 == NULL) || (len < session_id2_len) || (timingsafe_bcmp(p, session_id2, session_id2_len) != 0)) fail++; buffer_consume(&b, session_id2_len); } else { p = buffer_get_string(&b, &len); if ((session_id2 == NULL) || (len != session_id2_len) || (timingsafe_bcmp(p, session_id2, session_id2_len) != 0)) fail++; free(p); } if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST) fail++; cp = buffer_get_cstring(&b, NULL); xasprintf(&userstyle, "%s%s%s", authctxt->user, authctxt->style ? ":" : "", authctxt->style ? authctxt->style : ""); if (strcmp(userstyle, cp) != 0) { logit("wrong user name passed to monitor: " "expected %s != %.100s", userstyle, cp); fail++; } free(userstyle); free(cp); buffer_skip_string(&b); if (datafellows & SSH_BUG_PKAUTH) { if (!buffer_get_char(&b)) fail++; } else { cp = buffer_get_cstring(&b, NULL); if (strcmp("publickey", cp) != 0) fail++; free(cp); if (!buffer_get_char(&b)) fail++; buffer_skip_string(&b); } buffer_skip_string(&b); if (buffer_len(&b) != 0) fail++; buffer_free(&b); return (fail == 0); } static int monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser, char *chost) { Buffer b; char *p, *userstyle; u_int len; int fail = 0; buffer_init(&b); buffer_append(&b, data, datalen); p = buffer_get_string(&b, &len); if ((session_id2 == NULL) || (len != session_id2_len) || (timingsafe_bcmp(p, session_id2, session_id2_len) != 0)) fail++; free(p); if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST) fail++; p = buffer_get_cstring(&b, NULL); xasprintf(&userstyle, "%s%s%s", authctxt->user, authctxt->style ? ":" : "", authctxt->style ? authctxt->style : ""); if (strcmp(userstyle, p) != 0) { logit("wrong user name passed to monitor: expected %s != %.100s", userstyle, p); fail++; } free(userstyle); free(p); buffer_skip_string(&b); /* service */ p = buffer_get_cstring(&b, NULL); if (strcmp(p, "hostbased") != 0) fail++; free(p); buffer_skip_string(&b); /* pkalg */ buffer_skip_string(&b); /* pkblob */ /* verify client host, strip trailing dot if necessary */ p = buffer_get_string(&b, NULL); if (((len = strlen(p)) > 0) && p[len - 1] == '.') p[len - 1] = '\0'; if (strcmp(p, chost) != 0) fail++; free(p); /* verify client user */ p = buffer_get_string(&b, NULL); if (strcmp(p, cuser) != 0) fail++; free(p); if (buffer_len(&b) != 0) fail++; buffer_free(&b); return (fail == 0); } int mm_answer_keyverify(int sock, Buffer *m) { Key *key; u_char *signature, *data, *blob; u_int signaturelen, datalen, bloblen; int verified = 0; int valid_data = 0; blob = buffer_get_string(m, &bloblen); signature = buffer_get_string(m, &signaturelen); data = buffer_get_string(m, &datalen); if (hostbased_cuser == NULL || hostbased_chost == NULL || !monitor_allowed_key(blob, bloblen)) fatal("%s: bad key, not previously allowed", __func__); key = key_from_blob(blob, bloblen); if (key == NULL) fatal("%s: bad public key blob", __func__); switch (key_blobtype) { case MM_USERKEY: valid_data = monitor_valid_userblob(data, datalen); break; case MM_HOSTKEY: valid_data = monitor_valid_hostbasedblob(data, datalen, hostbased_cuser, hostbased_chost); break; default: valid_data = 0; break; } if (!valid_data) fatal("%s: bad signature data blob", __func__); verified = key_verify(key, signature, signaturelen, data, datalen); debug3("%s: key %p signature %s", __func__, key, (verified == 1) ? "verified" : "unverified"); /* If auth was successful then record key to ensure it isn't reused */ if (verified == 1 && key_blobtype == MM_USERKEY) auth2_record_userkey(authctxt, key); else key_free(key); free(blob); free(signature); free(data); auth_method = key_blobtype == MM_USERKEY ? "publickey" : "hostbased"; monitor_reset_key_state(); buffer_clear(m); buffer_put_int(m, verified); mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m); return (verified == 1); } static void mm_record_login(Session *s, struct passwd *pw) { struct ssh *ssh = active_state; /* XXX */ socklen_t fromlen; struct sockaddr_storage from; /* * Get IP address of client. If the connection is not a socket, let * the address be 0.0.0.0. */ memset(&from, 0, sizeof(from)); fromlen = sizeof(from); if (packet_connection_is_on_socket()) { if (getpeername(packet_get_connection_in(), (struct sockaddr *)&from, &fromlen) < 0) { debug("getpeername: %.100s", strerror(errno)); cleanup_exit(255); } } /* Record that there was a login on that tty from the remote host. */ record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid, session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns), (struct sockaddr *)&from, fromlen); } static void mm_session_close(Session *s) { debug3("%s: session %d pid %ld", __func__, s->self, (long)s->pid); if (s->ttyfd != -1) { debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ptyfd); session_pty_cleanup2(s); } session_unused(s->self); } int mm_answer_pty(int sock, Buffer *m) { extern struct monitor *pmonitor; Session *s; int res, fd0; debug3("%s entering", __func__); buffer_clear(m); s = session_new(); if (s == NULL) goto error; s->authctxt = authctxt; s->pw = authctxt->pw; s->pid = pmonitor->m_pid; res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)); if (res == 0) goto error; pty_setowner(authctxt->pw, s->tty); buffer_put_int(m, 1); buffer_put_cstring(m, s->tty); /* We need to trick ttyslot */ if (dup2(s->ttyfd, 0) == -1) fatal("%s: dup2", __func__); mm_record_login(s, authctxt->pw); /* Now we can close the file descriptor again */ close(0); /* send messages generated by record_login */ buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg)); buffer_clear(&loginmsg); mm_request_send(sock, MONITOR_ANS_PTY, m); if (mm_send_fd(sock, s->ptyfd) == -1 || mm_send_fd(sock, s->ttyfd) == -1) fatal("%s: send fds failed", __func__); /* make sure nothing uses fd 0 */ if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0) fatal("%s: open(/dev/null): %s", __func__, strerror(errno)); if (fd0 != 0) error("%s: fd0 %d != 0", __func__, fd0); /* slave is not needed */ close(s->ttyfd); s->ttyfd = s->ptyfd; /* no need to dup() because nobody closes ptyfd */ s->ptymaster = s->ptyfd; debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd); return (0); error: if (s != NULL) mm_session_close(s); buffer_put_int(m, 0); mm_request_send(sock, MONITOR_ANS_PTY, m); return (0); } int mm_answer_pty_cleanup(int sock, Buffer *m) { Session *s; char *tty; debug3("%s entering", __func__); tty = buffer_get_string(m, NULL); if ((s = session_by_tty(tty)) != NULL) mm_session_close(s); buffer_clear(m); free(tty); return (0); } int mm_answer_term(int sock, Buffer *req) { extern struct monitor *pmonitor; int res, status; debug3("%s: tearing down sessions", __func__); /* The child is terminating */ session_destroy_all(&mm_session_close); while (waitpid(pmonitor->m_pid, &status, 0) == -1) if (errno != EINTR) exit(1); res = WIFEXITED(status) ? WEXITSTATUS(status) : 1; /* Terminate process */ exit(res); } void monitor_apply_keystate(struct monitor *pmonitor) { struct ssh *ssh = active_state; /* XXX */ struct kex *kex; int r; debug3("%s: packet_set_state", __func__); if ((r = ssh_packet_set_state(ssh, child_state)) != 0) fatal("%s: packet_set_state: %s", __func__, ssh_err(r)); sshbuf_free(child_state); child_state = NULL; if ((kex = ssh->kex) != NULL) { /* XXX set callbacks */ #ifdef WITH_OPENSSL kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server; kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server; kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server; kex->kex[KEX_DH_GEX_SHA1] = kexgex_server; kex->kex[KEX_DH_GEX_SHA256] = kexgex_server; kex->kex[KEX_ECDH_SHA2] = kexecdh_server; #endif kex->kex[KEX_C25519_SHA256] = kexc25519_server; kex->load_host_public_key=&get_hostkey_public_by_type; kex->load_host_private_key=&get_hostkey_private_by_type; kex->host_key_index=&get_hostkey_index; kex->sign = sshd_hostkey_sign; } } /* This function requries careful sanity checking */ void mm_get_keystate(struct monitor *pmonitor) { debug3("%s: Waiting for new keys", __func__); if ((child_state = sshbuf_new()) == NULL) fatal("%s: sshbuf_new failed", __func__); mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT, child_state); debug3("%s: GOT new keys", __func__); } /* XXX */ #define FD_CLOSEONEXEC(x) do { \ if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \ fatal("fcntl(%d, F_SETFD)", x); \ } while (0) static void monitor_openfds(struct monitor *mon, int do_logfds) { int pair[2]; if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) fatal("%s: socketpair: %s", __func__, strerror(errno)); FD_CLOSEONEXEC(pair[0]); FD_CLOSEONEXEC(pair[1]); mon->m_recvfd = pair[0]; mon->m_sendfd = pair[1]; if (do_logfds) { if (pipe(pair) == -1) fatal("%s: pipe: %s", __func__, strerror(errno)); FD_CLOSEONEXEC(pair[0]); FD_CLOSEONEXEC(pair[1]); mon->m_log_recvfd = pair[0]; mon->m_log_sendfd = pair[1]; } else mon->m_log_recvfd = mon->m_log_sendfd = -1; } #define MM_MEMSIZE 65536 struct monitor * monitor_init(void) { struct monitor *mon; mon = xcalloc(1, sizeof(*mon)); monitor_openfds(mon, 1); return mon; } void monitor_reinit(struct monitor *mon) { monitor_openfds(mon, 0); } #ifdef GSSAPI int mm_answer_gss_setup_ctx(int sock, Buffer *m) { gss_OID_desc goid; OM_uint32 major; u_int len; if (!options.gss_authentication) fatal("%s: GSSAPI authentication not enabled", __func__); goid.elements = buffer_get_string(m, &len); goid.length = len; major = ssh_gssapi_server_ctx(&gsscontext, &goid); free(goid.elements); buffer_clear(m); buffer_put_int(m, major); mm_request_send(sock, MONITOR_ANS_GSSSETUP, m); /* Now we have a context, enable the step */ monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1); return (0); } int mm_answer_gss_accept_ctx(int sock, Buffer *m) { gss_buffer_desc in; gss_buffer_desc out = GSS_C_EMPTY_BUFFER; OM_uint32 major, minor; OM_uint32 flags = 0; /* GSI needs this */ u_int len; if (!options.gss_authentication) fatal("%s: GSSAPI authentication not enabled", __func__); in.value = buffer_get_string(m, &len); in.length = len; major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags); free(in.value); buffer_clear(m); buffer_put_int(m, major); buffer_put_string(m, out.value, out.length); buffer_put_int(m, flags); mm_request_send(sock, MONITOR_ANS_GSSSTEP, m); gss_release_buffer(&minor, &out); if (major == GSS_S_COMPLETE) { monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0); monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1); monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1); } return (0); } int mm_answer_gss_checkmic(int sock, Buffer *m) { gss_buffer_desc gssbuf, mic; OM_uint32 ret; u_int len; if (!options.gss_authentication) fatal("%s: GSSAPI authentication not enabled", __func__); gssbuf.value = buffer_get_string(m, &len); gssbuf.length = len; mic.value = buffer_get_string(m, &len); mic.length = len; ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic); free(gssbuf.value); free(mic.value); buffer_clear(m); buffer_put_int(m, ret); mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m); if (!GSS_ERROR(ret)) monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1); return (0); } int mm_answer_gss_userok(int sock, Buffer *m) { int authenticated; if (!options.gss_authentication) fatal("%s: GSSAPI authentication not enabled", __func__); authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user); buffer_clear(m); buffer_put_int(m, authenticated); debug3("%s: sending result %d", __func__, authenticated); mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m); auth_method = "gssapi-with-mic"; /* Monitor loop will terminate if authenticated */ return (authenticated); } #endif /* GSSAPI */
./CrossVul/dataset_final_sorted/CWE-119/c/good_4767_0
crossvul-cpp_data_bad_344_1
/* * Support for ePass2003 smart cards * * Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com> * Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #ifdef ENABLE_SM /* empty file without SM enabled */ #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table epass2003_atrs[] = { /* This is a FIPS certified card using SCP01 security messaging. */ {"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e", "FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00", "FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL }, {NULL, NULL, NULL, 0, 0, NULL} }; static struct sc_card_operations *iso_ops = NULL; static struct sc_card_operations epass2003_ops; static struct sc_card_driver epass2003_drv = { "epass2003", "epass2003", &epass2003_ops, NULL, 0, NULL }; #define KEY_TYPE_AES 0x01 /* FIPS mode */ #define KEY_TYPE_DES 0x02 /* Non-FIPS mode */ #define KEY_LEN_AES 16 #define KEY_LEN_DES 8 #define KEY_LEN_DES3 24 #define HASH_LEN 24 static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID }; /*0x00:plain; 0x01:scp01 sm*/ #define SM_PLAIN 0x00 #define SM_SCP01 0x01 static unsigned char g_init_key_enc[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_init_key_mac[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_random[8] = { 0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40 }; typedef struct epass2003_exdata_st { unsigned char sm; /* SM_PLAIN or SM_SCP01 */ unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */ unsigned char sk_enc[16]; /* encrypt session key */ unsigned char sk_mac[16]; /* mac session key */ unsigned char icv_mac[16]; /* instruction counter vector(for sm) */ unsigned char currAlg; /* current Alg */ unsigned int ecAlgFlags; /* Ec Alg mechanism type*/ } epass2003_exdata; #define REVERSE_ORDER4(x) ( \ ((unsigned long)x & 0xFF000000)>> 24 | \ ((unsigned long)x & 0x00FF0000)>> 8 | \ ((unsigned long)x & 0x0000FF00)<< 8 | \ ((unsigned long)x & 0x000000FF)<< 24) static const struct sc_card_error epass2003_errors[] = { { 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" }, { 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" }, { 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" }, { 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" }, { 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" }, { 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"}, { 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"}, { 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" }, { 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" }, { 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" }, { 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" }, { 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" }, { 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" }, { 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" }, { 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" }, { 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" }, { 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" }, { 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" }, { 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" }, { 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" }, { 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" }, { 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" }, { 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" }, { 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" }, { 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" }, { 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" }, { 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" }, { 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" }, { 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" }, { 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" }, { 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" }, { 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"}, { 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"}, { 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" }, { 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" }, { 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" }, { 0x9000,SC_SUCCESS, NULL } }; static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu); static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out); int epass2003_refresh(struct sc_card *card); static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType); static int epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]); int i; /* Handle special cases here */ if (sw1 == 0x6C) { sc_log(card->ctx, "Wrong length; correct length is %d", sw2); return SC_ERROR_WRONG_LENGTH; } for (i = 0; i < err_count; i++) { if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) { sc_log(card->ctx, "%s", epass2003_errors[i].errorstr); return epass2003_errors[i].errorno; } } sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2); return SC_ERROR_CARD_CMD_FAILED; } static int sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu) { int r = sc_transmit_apdu(card, apdu); if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2))) { epass2003_refresh(card); r = sc_transmit_apdu(card, apdu); } return r; } static int openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_EncryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_DecryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int aes128_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, size_t length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output); } static int aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output); } static int aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output); } static int des3_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, int length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output); } static int des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_des_cbc(), key, iv, input, length, output); } static int des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_des_cbc(), key, iv, input, length, output); } static int openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length, unsigned char *output) { int r = 0; EVP_MD_CTX *ctx = NULL; unsigned outl = 0; ctx = EVP_MD_CTX_create(); if (ctx == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } EVP_MD_CTX_init(ctx); EVP_DigestInit_ex(ctx, digest, NULL); if (!EVP_DigestUpdate(ctx, input, length)) { r = SC_ERROR_INTERNAL; goto err; } if (!EVP_DigestFinal_ex(ctx, output, &outl)) { r = SC_ERROR_INTERNAL; goto err; } r = SC_SUCCESS; err: if (ctx) EVP_MD_CTX_destroy(ctx); return r; } static int sha1_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha1(), input, length, output); } static int sha256_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha256(), input, length, output); } static int gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac, unsigned char *result, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned char data[256] = { 0 }; unsigned char tmp_sm; unsigned long blocksize = 0; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = sizeof(g_random); apdu.data = g_random; /* host random */ apdu.le = apdu.resplen = 28; apdu.resp = result; /* card random is result[12~19] */ tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "gen_init_key failed"); /* Step 1 - Generate Derivation data */ memcpy(data, &result[16], 4); memcpy(&data[4], g_random, 4); memcpy(&data[8], &result[12], 4); memcpy(&data[12], &g_random[4], 4); /* Step 2,3 - Create S-ENC/S-MAC Session Key */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } else { des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } memcpy(data, g_random, 8); memcpy(&data[8], &result[12], 8); data[16] = 0x80; blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); memset(&data[17], 0x00, blocksize - 1); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); /* verify card cryptogram */ if (0 != memcmp(&cryptogram[16], &result[20], 8)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); unsigned char data[256] = { 0 }; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; unsigned char mac[256] = { 0 }; unsigned long i; unsigned char tmp_sm; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); memcpy(data, ran_key, 8); memcpy(&data[8], g_random, 8); data[16] = 0x80; memset(&data[17], 0x00, blocksize - 1); memset(iv, 0, 16); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } else { des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } memset(data, 0, sizeof(data)); memcpy(data, "\x84\x82\x03\x00\x10", 5); memcpy(&data[5], &cryptogram[16], 8); memcpy(&data[13], "\x80\x00\x00", 3); /* calculate mac icv */ memset(iv, 0x00, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 0; } else { des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 8; } /* save mac icv */ memset(exdata->icv_mac, 0x00, 16); memcpy(exdata->icv_mac, &mac[i], 8); /* verify host cryptogram */ memcpy(data, &cryptogram[16], 8); memcpy(&data[8], &mac[i], 8); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00); apdu.cla = 0x84; apdu.lc = apdu.datalen = 16; apdu.data = data; tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU verify_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "verify_init_key failed"); return r; } static int mutual_auth(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac) { struct sc_context *ctx = card->ctx; int r; unsigned char result[256] = { 0 }; unsigned char ran_key[8] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(ctx); r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype); LOG_TEST_RET(ctx, r, "gen_init_key failed"); memcpy(ran_key, &result[12], 8); r = verify_init_key(card, ran_key, exdata->smtype); LOG_TEST_RET(ctx, r, "verify_init_key failed"); LOG_FUNC_RETURN(ctx, r); } int epass2003_refresh(struct sc_card *card) { int r = SC_SUCCESS; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (exdata->sm) { card->sm_ctx.sm_mode = 0; r = mutual_auth(card, g_init_key_enc, g_init_key_mac); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; LOG_TEST_RET(card->ctx, r, "mutual_auth failed"); } return r; } /* Data(TLV)=0x87|L|0x01+Cipher */ static int construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf, unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char pad[4096] = { 0 }; size_t pad_len; size_t tlv_more; /* increased tlv length */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* padding */ apdu_buf[block_size] = 0x87; memcpy(pad, apdu->data, apdu->lc); pad[apdu->lc] = 0x80; if ((apdu->lc + 1) % block_size) pad_len = ((apdu->lc + 1) / block_size + 1) * block_size; else pad_len = apdu->lc + 1; /* encode Lc' */ if (pad_len > 0x7E) { /* Lc' > 0x7E, use extended APDU */ apdu_buf[block_size + 1] = 0x82; apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100); apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100); apdu_buf[block_size + 4] = 0x01; tlv_more = 5; } else { apdu_buf[block_size + 1] = (unsigned char)pad_len + 1; apdu_buf[block_size + 2] = 0x01; tlv_more = 3; } memcpy(data_tlv, &apdu_buf[block_size], tlv_more); /* encrypt Data */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len); *data_tlv_len = tlv_more + pad_len; return 0; } /* Le(TLV)=0x97|L|Le */ static int construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len, unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); *(apdu_buf + block_size + data_tlv_len) = 0x97; if (apdu->le > 0x7F) { /* Le' > 0x7E, use extended APDU */ *(apdu_buf + block_size + data_tlv_len + 1) = 2; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100); *(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100); memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4); *le_tlv_len = 4; } else { *(apdu_buf + block_size + data_tlv_len + 1) = 1; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le; memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3); *le_tlv_len = 3; } return 0; } /* MAC(TLV)=0x8e|0x08|MAC */ static int construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, sizeof iv); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; } /* According to GlobalPlatform Card Specification's SCP01 * encode APDU from * CLA INS P1 P2 [Lc] Data [Le] * to * CLA INS P1 P2 Lc' Data' [Le] * where * Data'=Data(TLV)+Le(TLV)+MAC(TLV) */ static int encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm, unsigned char *apdu_buf, size_t * apdu_buf_len) { size_t block_size = 0; unsigned char dataTLV[4096] = { 0 }; size_t data_tlv_len = 0; unsigned char le_tlv[256] = { 0 }; size_t le_tlv_len = 0; size_t mac_tlv_len = 10; size_t tmp_lc = 0; size_t tmp_le = 0; unsigned char mac_tlv[256] = { 0 }; epass2003_exdata *exdata = NULL; mac_tlv[0] = 0x8E; mac_tlv[1] = 8; /* size_t plain_le = 0; */ if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata*)card->drv_data; block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8); sm->cse = SC_APDU_CASE_4_SHORT; apdu_buf[0] = (unsigned char)plain->cla; apdu_buf[1] = (unsigned char)plain->ins; apdu_buf[2] = (unsigned char)plain->p1; apdu_buf[3] = (unsigned char)plain->p2; /* plain_le = plain->le; */ /* padding */ apdu_buf[4] = 0x80; memset(&apdu_buf[5], 0x00, block_size - 5); /* Data -> Data' */ if (plain->lc != 0) if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype)) return -1; if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0)) if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv, &le_tlv_len, exdata->smtype)) return -1; if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype)) return -1; memset(apdu_buf + 4, 0, *apdu_buf_len - 4); sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len; if (sm->lc > 0xFF) { sm->cse = SC_APDU_CASE_4_EXT; apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000); apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100); apdu_buf[6] = (unsigned char)((sm->lc) % 0x100); tmp_lc = 3; } else { apdu_buf[4] = (unsigned char)sm->lc; tmp_lc = 1; } memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len); memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen); *apdu_buf_len = 0; if (4 == le_tlv_len) { sm->cse = SC_APDU_CASE_4_EXT; *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100); *(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100); tmp_le = 2; } else if (3 == le_tlv_len) { *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le; tmp_le = 1; } *apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le; /* sm->le = calc_le(plain_le); */ return 0; } static int epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm) { unsigned char buf[4096] = { 0 }; /* APDU buffer */ size_t buf_len = sizeof(buf); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); if (exdata->sm) plain->cla |= 0x0C; sm->cse = plain->cse; sm->cla = plain->cla; sm->ins = plain->ins; sm->p1 = plain->p1; sm->p2 = plain->p2; sm->lc = plain->lc; sm->le = plain->le; sm->control = plain->control; sm->flags = plain->flags; switch (sm->cla & 0x0C) { case 0x00: case 0x04: sm->datalen = plain->datalen; memcpy((void *)sm->data, plain->data, plain->datalen); sm->resplen = plain->resplen; memcpy(sm->resp, plain->resp, plain->resplen); break; case 0x0C: memset(buf, 0, sizeof(buf)); if (0 != encode_apdu(card, plain, sm, buf, &buf_len)) return SC_ERROR_CARD_CMD_FAILED; break; default: return SC_ERROR_INCORRECT_PARAMETERS; } return SC_SUCCESS; } /* According to GlobalPlatform Card Specification's SCP01 * decrypt APDU response from * ResponseData' SW1 SW2 * to * ResponseData SW1 SW2 * where * ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV) * where * Data(TLV)=0x87|L|Cipher * SW12(TLV)=0x99|0x02|SW1+SW2 * MAC(TLV)=0x8e|0x08|MAC */ static int decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } static int epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); if (!sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); if (!(*sm_apdu)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (plain) rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain); if ((*sm_apdu)->data) { unsigned char * p = (unsigned char *)((*sm_apdu)->data); free(p); } if ((*sm_apdu)->resp) { free((*sm_apdu)->resp); } free(*sm_apdu); *sm_apdu = NULL; LOG_FUNC_RETURN(ctx, rv); } static int epass2003_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; struct sc_apdu *apdu = NULL; int rv; LOG_FUNC_CALLED(ctx); if (!plain || !sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); *sm_apdu = NULL; //construct new SM apdu from original apdu apdu = calloc(1, sizeof(struct sc_apdu)); if (!apdu) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->resp) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE; apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE; rv = epass2003_sm_wrap_apdu(card, plain, apdu); if (rv) { rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu); if (rv < 0) goto err; } *sm_apdu = apdu; apdu = NULL; err: if (apdu) { free((unsigned char *) apdu->data); free(apdu->resp); free(apdu); apdu = NULL; } LOG_FUNC_RETURN(ctx, rv); } static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu) { int r; LOG_FUNC_CALLED(card->ctx); r = sc_transmit_apdu_t(card, apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return r; } static int get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t resplen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type); apdu.resp = resp; apdu.le = 0; apdu.resplen = resplen; if (0x86 == type) { /* No SM temporarily */ unsigned char tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = sc_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; } else { r = sc_transmit_apdu_t(card, &apdu); } LOG_TEST_RET(card->ctx, r, "APDU get_data failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get_data failed"); memcpy(data, resp, datalen); return r; } /* card driver functions */ static int epass2003_match_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); r = _sc_match_atr(card, epass2003_atrs, &card->type); if (r < 0) return 0; return 1; } static int epass2003_init(struct sc_card *card) { unsigned int flags; unsigned int ext_flags; unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t datalen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); card->name = "epass2003"; card->cla = 0x00; exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata)); if (!exdata) return SC_ERROR_OUT_OF_MEMORY; card->drv_data = exdata; exdata->sm = SM_SCP01; /* decide FIPS/Non-FIPS mode */ if (SC_SUCCESS != get_data(card, 0x86, data, datalen)) return SC_ERROR_INVALID_CARD; if (0x01 == data[2]) exdata->smtype = KEY_TYPE_AES; else exdata->smtype = KEY_TYPE_DES; if (0x84 == data[14]) { if (0x00 == data[16]) { exdata->sm = SM_PLAIN; } } /* mutual authentication */ card->max_recv_size = 0xD8; card->max_send_size = 0xE8; card->sm_ctx.ops.open = epass2003_refresh; card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu; card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu; /* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */ epass2003_refresh(card); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); //set EC Alg Flags flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW; ext_flags = 0; _sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL); card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_finish(sc_card_t *card) { epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data; if (exdata) free(exdata); return SC_SUCCESS; } /* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the * same DF, so use hook functions to increase/decrease FID by 0x20 */ static int epass2003_hook_path(struct sc_path *path, int inc) { u8 fid_h = path->value[path->len - 2]; u8 fid_l = path->value[path->len - 1]; switch (fid_h) { case 0x29: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: if (inc) fid_l = fid_l * FID_STEP; else fid_l = fid_l / FID_STEP; path->value[path->len - 1] = fid_l; return 1; default: break; } return 0; } static void epass2003_hook_file(struct sc_file *file, int inc) { int fidl = file->id & 0xff; int fidh = file->id & 0xff00; if (epass2003_hook_path(&file->path, inc)) { if (inc) file->id = fidh + fidl * FID_STEP; else file->id = fidh + fidl / FID_STEP; } } static int epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out) { struct sc_apdu apdu; u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen; sc_file_t *file = NULL; epass2003_hook_path(in_path, 1); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: apdu.p1 = 0; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.p2 = 0; /* first record, return FCI */ apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 0; } else { apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */ /* Not allowed to select private key file, so fake fci. */ /* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */ apdu.resplen = 0x18; memcpy(apdu.resp, "\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff", apdu.resplen); apdu.resp[9] = path[1]; apdu.sw1 = 0x90; apdu.sw2 = 0x00; } else { r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); } if (file_out == NULL) { if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(card->ctx, 0); LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(card->ctx, r); if (apdu.resplen < 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); switch (apdu.resp[0]) { case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; if (card->ops->process_fci == NULL) { sc_file_free(file); LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } if ((size_t) apdu.resp[1] + 2 <= apdu.resplen) card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]); epass2003_hook_file(file, 0); *file_out = file; break; case 0x00: /* proprietary coding */ LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } return 0; } static int epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo, sc_file_t ** file_out) { int r; sc_file_t *file = 0; sc_path_t path; memset(&path, 0, sizeof(path)); path.type = SC_PATH_TYPE_FILE_ID; path.value[0] = id_hi; path.value[1] = id_lo; path.len = 2; r = epass2003_select_fid_(card, &path, &file); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ if (file && file->type == SC_FILE_TYPE_DF) { card->cache.current_path.type = SC_PATH_TYPE_PATH; card->cache.current_path.value[0] = 0x3f; card->cache.current_path.value[1] = 0x00; if (id_hi == 0x3f && id_lo == 0x00) { card->cache.current_path.len = 2; } else { card->cache.current_path.len = 4; card->cache.current_path.value[2] = id_hi; card->cache.current_path.value[3] = id_lo; } } if (file_out) *file_out = file; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r = 0; if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_DF_NAME && card->cache.current_path.len == in_path->len && memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) { if (file_out) { *file_out = sc_file_new(); if (!file_out) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } } else { r = iso_ops->select_file(card, in_path, file_out); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ card->cache.current_path.type = SC_PATH_TYPE_DF_NAME; card->cache.current_path.len = in_path->len; memcpy(card->cache.current_path.value, in_path->value, in_path->len); } if (file_out) { sc_file_t *file = *file_out; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->path.len = 0; file->size = 0; /* AID */ memcpy(file->name, in_path->value, in_path->len); file->namelen = in_path->len; file->id = 0x0000; } LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len, sc_file_t ** file_out) { u8 n_pathbuf[SC_MAX_PATH_SIZE]; const u8 *path = pathbuf; size_t pathlen = len; int bMatch = -1; unsigned int i; int r; if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* if pathlen == 6 then the first FID must be MF (== 3F00) */ if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* unify path (the first FID should be MF) */ if (path[0] != 0x3f || path[1] != 0x00) { n_pathbuf[0] = 0x3f; n_pathbuf[1] = 0x00; for (i = 0; i < pathlen; i++) n_pathbuf[i + 2] = pathbuf[i]; path = n_pathbuf; pathlen += 2; } /* check current working directory */ if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_PATH && card->cache.current_path.len >= 2 && card->cache.current_path.len <= pathlen) { bMatch = 0; for (i = 0; i < card->cache.current_path.len; i += 2) if (card->cache.current_path.value[i] == path[i] && card->cache.current_path.value[i + 1] == path[i + 1]) bMatch += 2; } if (card->cache.valid && bMatch > 2) { if (pathlen - bMatch == 2) { /* we are in the right directory */ return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out); } else if (pathlen - bMatch > 2) { /* two more steps to go */ sc_path_t new_path; /* first step: change directory */ r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); new_path.type = SC_PATH_TYPE_PATH; new_path.len = pathlen - bMatch - 2; memcpy(new_path.value, &(path[bMatch + 2]), new_path.len); /* final step: select file */ return epass2003_select_file(card, &new_path, file_out); } else { /* if (bMatch - pathlen == 0) */ /* done: we are already in the * requested directory */ sc_log(card->ctx, "cache hit\n"); /* copy file info (if necessary) */ if (file_out) { sc_file_t *file = sc_file_new(); if (!file) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->id = (path[pathlen - 2] << 8) + path[pathlen - 1]; file->path = card->cache.current_path; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->size = 0; file->namelen = 0; file->magic = SC_FILE_MAGIC; *file_out = file; } /* nothing left to do */ return SC_SUCCESS; } } else { /* no usable cache */ for (i = 0; i < pathlen - 2; i += 2) { r = epass2003_select_fid(card, path[i], path[i + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); } return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out); } } static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r; char pbuf[SC_MAX_PATH_STRING_SIZE]; LOG_FUNC_CALLED(card->ctx); r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path); if (r != SC_SUCCESS) pbuf[0] = '\0'; sc_log(card->ctx, "current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n", card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ? "aid" : "path", card->cache.valid ? "valid" : "invalid", pbuf, card->cache.current_path.len); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (in_path->len != 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out); case SC_PATH_TYPE_DF_NAME: return epass2003_select_aid(card, in_path, file_out); case SC_PATH_TYPE_PATH: return epass2003_select_path(card, in_path->value, in_path->len, file_out); default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } } static int epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num) { struct sc_apdu apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 *p; unsigned short fid = 0; int r, locked = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0); p = sbuf; *p++ = 0x80; /* algorithm reference */ *p++ = 0x01; *p++ = 0x84; *p++ = 0x81; *p++ = 0x02; fid = 0x2900; fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff)); *p++ = fid >> 8; *p++ = fid & 0xff; r = p - sbuf; apdu.lc = r; apdu.datalen = r; apdu.data = sbuf; if (env->algorithm == SC_ALGORITHM_EC) { apdu.p2 = 0xB6; exdata->currAlg = SC_ALGORITHM_EC; if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1) { sbuf[2] = 0x91; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1; } else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256) { sbuf[2] = 0x92; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256; } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags); goto err; } } else if(env->algorithm == SC_ALGORITHM_RSA) { exdata->currAlg = SC_ALGORITHM_RSA; apdu.p2 = 0xB8; sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags); } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm); } if (se_num > 0) { r = sc_lock(card); LOG_TEST_RET(card->ctx, r, "sc_lock() failed"); locked = 1; } if (apdu.datalen != 0) { r = sc_transmit_apdu_t(card, &apdu); if (r) { sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r)); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) { sc_log(card->ctx, "%s: Card returned error", sc_strerror(r)); goto err; } } if (se_num <= 0) return 0; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num); r = sc_transmit_apdu_t(card, &apdu); sc_unlock(card); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); err: if (locked) sc_unlock(card); return r; } static int epass2003_restore_security_env(struct sc_card *card, int se_num) { LOG_FUNC_CALLED(card->ctx); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if(exdata->currAlg == SC_ALGORITHM_EC) { if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x14; apdu.datalen = 0x14; } else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x20; apdu.datalen = 0x20; } else { return SC_ERROR_NOT_SUPPORTED; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } else if(exdata->currAlg == SC_ALGORITHM_RSA) { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } else { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e) { if (e == NULL) return SC_ERROR_OBJECT_NOT_FOUND; switch (e->method) { case SC_AC_NONE: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE); case SC_AC_NEVER: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE); default: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); } static int epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen) { sc_context_t *ctx = card->ctx; size_t taglen, len = buflen; const u8 *tag = NULL, *p = buf; sc_log(ctx, "processing FCI bytes"); tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen); if (tag != NULL && taglen == 2) { file->id = (tag[0] << 8) | tag[1]; sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]); } tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen); if (tag != NULL && taglen > 0 && taglen < 3) { file->size = tag[0]; if (taglen == 2) file->size = (file->size << 8) + tag[1]; sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u", file->size); } if (tag == NULL) { tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen); if (tag != NULL && taglen >= 2) { int bytes = (tag[0] << 8) + tag[1]; sc_log(ctx, " bytes in file: %d", bytes); file->size = bytes; } } tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen); if (tag != NULL) { if (taglen > 0) { unsigned char byte = tag[0]; const char *type; if (byte == 0x38) { type = "DF"; file->type = SC_FILE_TYPE_DF; } else if (0x01 <= byte && byte <= 0x07) { type = "working EF"; file->type = SC_FILE_TYPE_WORKING_EF; switch (byte) { case 0x01: file->ef_structure = SC_FILE_EF_TRANSPARENT; break; case 0x02: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x04: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x03: case 0x05: case 0x06: case 0x07: break; default: break; } } else if (0x10 == byte) { type = "BSO"; file->type = SC_FILE_TYPE_BSO; } else if (0x11 <= byte) { type = "internal EF"; file->type = SC_FILE_TYPE_INTERNAL_EF; switch (byte) { case 0x11: break; case 0x12: break; default: break; } } else { type = "unknown"; file->type = SC_FILE_TYPE_INTERNAL_EF; } sc_log(ctx, "type %s, EF structure %d", type, byte); } } tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen); if (tag != NULL && taglen > 0 && taglen <= 16) { memcpy(file->name, tag, taglen); file->namelen = taglen; sc_log_hex(ctx, "File name", file->name, file->namelen); if (!file->type) file->type = SC_FILE_TYPE_DF; } tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); else file->prop_attr_len = 0; tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen); if (tag != NULL && taglen) sc_file_set_sec_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen); if (tag != NULL && taglen == 1) { if (tag[0] == 0x01) file->status = SC_FILE_STATUS_CREATION; else if (tag[0] == 0x07 || tag[0] == 0x05) file->status = SC_FILE_STATUS_ACTIVATED; else if (tag[0] == 0x06 || tag[0] == 0x04) file->status = SC_FILE_STATUS_INVALIDATED; } file->magic = SC_FILE_MAGIC; return 0; } static int epass2003_construct_fci(struct sc_card *card, const sc_file_t * file, u8 * out, size_t * outlen) { u8 *p = out; u8 buf[64]; unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; int rv; unsigned ii; if (*outlen < 2) return SC_ERROR_BUFFER_TOO_SMALL; *p++ = 0x62; p++; if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p); } } if (file->type == SC_FILE_TYPE_DF) { buf[0] = 0x38; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_WORKING_EF) { buf[0] = file->ef_structure & 7; if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { buf[1] = 0x00; buf[2] = 0x00; buf[3] = 0x40; /* record length */ buf[4] = 0x00; /* record count */ sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p); } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { buf[0] = 0x11; buf[1] = 0x00; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = 0x12; buf[1] = 0x00; } else { return SC_ERROR_NOT_SUPPORTED; } sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = 0x10; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p); if (file->type == SC_FILE_TYPE_DF) { if (file->namelen != 0) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p); } else { return SC_ERROR_INVALID_ARGUMENTS; } } if (file->type == SC_FILE_TYPE_DF) { unsigned char data[2] = {0x00, 0x7F}; /* 127 files at most */ sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = file->size & 0xff; sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p); } } if (file->sec_attr_len) { memcpy(buf, file->sec_attr, file->sec_attr_len); sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p); } else { sc_log(card->ctx, "SC_FILE_ACL"); if (file->type == SC_FILE_TYPE_DF) { ops[0] = SC_AC_OP_LIST_FILES; ops[1] = SC_AC_OP_CREATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_WRITE; ops[3] = SC_AC_OP_DELETE; } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_BSO) { ops[0] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } } else { return SC_ERROR_NOT_SUPPORTED; } for (ii = 0; ii < sizeof(ops); ii++) { const struct sc_acl_entry *entry; buf[ii] = 0xFF; if (ops[ii] == 0xFF) continue; entry = sc_file_get_acl_entry(file, ops[ii]); rv = acl_to_ac_byte(card, entry); LOG_TEST_RET(card->ctx, rv, "Invalid ACL"); buf[ii] = rv; } sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x13; } } /* VT ??? */ if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { unsigned char data[2] = {0x00, 0x66}; sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x14; } } out[1] = p - out - 2; *outlen = p - out; return 0; } static int epass2003_create_file(struct sc_card *card, sc_file_t * file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; struct sc_apdu apdu; len = SC_MAX_APDU_BUFFER_SIZE; epass2003_hook_file(file, 1); if (card->ops->construct_fci == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); r = epass2003_construct_fci(card, file, sbuf, &len); LOG_TEST_RET(card->ctx, r, "construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong"); epass2003_hook_file(file, 0); return r; } static int epass2003_delete_file(struct sc_card *card, const sc_path_t * path) { int r; u8 sbuf[2]; struct sc_apdu apdu; LOG_FUNC_CALLED(card->ctx); r = sc_select_file(card, path, NULL); epass2003_hook_path((struct sc_path *)path, 1); if (r == SC_SUCCESS) { sbuf[0] = path->value[path->len - 2]; sbuf[1] = path->value[path->len - 1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Delete file failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen) { struct sc_apdu apdu; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00); apdu.cla = 0x80; apdu.le = 0; apdu.resplen = sizeof(rbuf); apdu.resp = rbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Card returned error"); if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0) LOG_FUNC_RETURN(card->ctx, 0); buflen = buflen < apdu.resplen ? buflen : apdu.resplen; memcpy(buf, rbuf, buflen); LOG_FUNC_RETURN(card->ctx, buflen); } static int internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor, sc_pkcs15_bignum_t data) { int r; struct sc_apdu apdu; u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); sbuff[0] = ((fid & 0xff00) >> 8); sbuff[1] = (fid & 0x00ff); memcpy(&sbuff[2], data.data, data.len); // sc_mem_reverse(&sbuff[2], data.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 2 + data.len; apdu.data = sbuff; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa) { int r; LOG_FUNC_CALLED(card->ctx); r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus); LOG_TEST_RET(card->ctx, r, "write n failed"); r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d); LOG_TEST_RET(card->ctx, r, "write d failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType) { if ((NULL == data) || (NULL == hash)) return SC_ERROR_INVALID_ARGUMENTS; if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1) { unsigned char data_hash[24] = { 0 }; size_t len = 0; sha1_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[20], &len, 4); memcpy(hash, data_hash, 24); } else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256) { unsigned char data_hash[36] = { 0 }; size_t len = 0; sha256_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[32], &len, 4); memcpy(hash, data_hash, 36); } else { return SC_ERROR_NOT_SUPPORTED; } return SC_SUCCESS; } static int install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, unsigned char useac, unsigned char modifyac, unsigned char EC, unsigned char *data, unsigned long dataLen) { int r; struct sc_apdu apdu; unsigned char isapp = 0x00; /* appendable */ unsigned char tmp_data[256] = { 0 }; tmp_data[0] = ktype; tmp_data[1] = kid; tmp_data[2] = useac; tmp_data[3] = modifyac; tmp_data[8] = 0xFF; if (0x04 == ktype || 0x06 == ktype) { tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO); tmp_data[9] = (EC << 4) | EC; } memcpy(&tmp_data[10], data, dataLen); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 10 + dataLen; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "install_secret_key failed"); return r; } static int internal_install_pre(struct sc_card *card) { int r; /* init key for enc */ r = install_secret_key(card, 0x01, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_enc, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); /* init key for mac */ r = install_secret_key(card, 0x02, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_mac, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); return r; } /* use external auth secret as pin */ static int internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin) { int r; unsigned char hash[HASH_LEN] = { 0 }; r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid, pin->key_data.es_secret.ac[0], pin->key_data.es_secret.ac[1], pin->key_data.es_secret.EC, hash, HASH_LEN); LOG_TEST_RET(card->ctx, r, "Install failed"); return r; } static int epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data) { LOG_FUNC_CALLED(card->ctx); if (data->type & SC_EPASS2003_KEY) { if (data->type == SC_EPASS2003_KEY_RSA) return internal_write_rsa_key(card, data->key_data.es_key.fid, data->key_data.es_key.rsa); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else if (data->type & SC_EPASS2003_SECRET) { if (data->type == SC_EPASS2003_SECRET_PRE) return internal_install_pre(card); else if (data->type == SC_EPASS2003_SECRET_PIN) return internal_install_pin(card, data); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data) { int r; size_t len = data->key_length; struct sc_apdu apdu; u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); if(len == 256) { sbuf[0] = 0x02; } else { sbuf[0] = 0x01; } sbuf[1] = (u8) ((len >> 8) & 0xff); sbuf[2] = (u8) (len & 0xff); sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF); sbuf[4] = (u8) ((data->prkey_id) & 0xFF); sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF); sbuf[6] = (u8) ((data->pukey_id) & 0xFF); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.lc = apdu.datalen = 7; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "generate keypair failed"); /* read public key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00); if(len == 256) { apdu.p1 = 0x00; } apdu.cla = 0x80; apdu.lc = apdu.datalen = 2; apdu.data = &sbuf[5]; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x00; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get pukey failed"); if (len < apdu.resplen) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); data->modulus = (u8 *) malloc(len); if (!data->modulus) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(data->modulus, rbuf, len); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_erase_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); sc_invalidate_cache(card); r = sc_delete_file(card, sc_get_mf_path()); LOG_TEST_RET(card->ctx, r, "delete MF failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial) { u8 rbuf[8]; size_t rbuf_len = sizeof(rbuf); LOG_FUNC_CALLED(card->ctx); if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len)) return SC_ERROR_CARD_CMD_FAILED; card->serialnr.len = serial->len = 8; memcpy(card->serialnr.value, rbuf, 8); memcpy(serial->value, rbuf, 8); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd is %0lx", cmd); switch (cmd) { case SC_CARDCTL_ENTERSAFE_WRITE_KEY: return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr); case SC_CARDCTL_ENTERSAFE_GENERATE_KEY: return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr); case SC_CARDCTL_ERASE_CARD: return epass2003_erase_card(card); case SC_CARDCTL_GET_SERIALNR: return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr); default: return SC_ERROR_NOT_SUPPORTED; } } static void internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num) { pin->encoding = SC_PIN_ENCODING_ASCII; pin->min_length = 4; pin->max_length = 16; pin->pad_length = 16; pin->offset = 5 + num * 16; pin->pad_char = 0x00; } static int get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries) { unsigned char maxcounter[2] = { 0 }; static const sc_path_t file_path = { {0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6, 0, 0, SC_PATH_TYPE_PATH, {{0}, 0} }; int ret; ret = sc_select_file(card, &file_path, NULL); LOG_TEST_RET(card->ctx, ret, "select max counter file failed"); ret = sc_read_binary(card, 0, maxcounter, 2, 0); LOG_TEST_RET(card->ctx, ret, "read max counter file failed"); *maxtries = maxcounter[0]; return SC_SUCCESS; } static int get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid); apdu.resp = NULL; apdu.resplen = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed"); if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) { *retries = (apdu.sw2 & 0x0f); r = SC_SUCCESS; } else { LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed"); r = SC_ERROR_CARD_CMD_FAILED; } return r; } static int epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { u8 rbuf[16]; size_t out_len; int r; LOG_FUNC_CALLED(card->ctx); r = iso_ops->get_challenge(card, rbuf, sizeof rbuf); LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed"); if (len < (size_t) r) { out_len = len; } else { out_len = (size_t) r; } memcpy(rnd, rbuf, out_len); LOG_FUNC_RETURN(card->ctx, (int) out_len); } static int external_key_auth(struct sc_card *card, unsigned char kid, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; unsigned char tmp_data[16] = { 0 }; unsigned char hash[HASH_LEN] = { 0 }; unsigned char iv[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed"); r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid); apdu.lc = apdu.datalen = 8; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "external_key_auth failed"); return r; } static int update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, const unsigned char *data, unsigned long datalen) { int r; struct sc_apdu apdu; unsigned char hash[HASH_LEN] = { 0 }; unsigned char tmp_data[256] = { 0 }; unsigned char maxtries = 0; r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); tmp_data[0] = (maxtries << 4) | maxtries; memcpy(&tmp_data[1], hash, HASH_LEN); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid); apdu.cla = 0x80; apdu.lc = apdu.datalen = 1 + HASH_LEN; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "update_secret_key failed"); return r; } /* use external auth secret as pin */ static int epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { int r; u8 kid; u8 retries = 0; u8 pin_low = 3; unsigned char maxtries = 0; LOG_FUNC_CALLED(card->ctx); internal_sanitize_pin_info(&data->pin1, 0); internal_sanitize_pin_info(&data->pin2, 1); data->flags |= SC_PIN_CMD_NEED_PADDING; kid = data->pin_reference; /* get pin retries */ if (data->cmd == SC_PIN_CMD_GET_INFO) { r = get_external_key_retries(card, 0x80 | kid, &retries); if (r == SC_SUCCESS) { data->pin1.tries_left = retries; if (tries_left) *tries_left = retries; r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); data->pin1.max_tries = maxtries; } //remove below code, because the old implement only return PIN retries, now modify the code and return PIN status // return r; } else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */ r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data, data->pin1.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */ r = update_secret_key(card, 0x04, kid, data->pin2.data, (unsigned long)data->pin2.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else { r = external_key_auth(card, kid, (unsigned char *)data->pin1.data, data->pin1.len); get_external_key_retries(card, 0x80 | kid, &retries); if (retries < pin_low) sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries); } LOG_TEST_RET(card->ctx, r, "verify pin failed"); if (r == SC_SUCCESS) { data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN; } return r; } static struct sc_card_driver *sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; epass2003_ops = *iso_ops; epass2003_ops.match_card = epass2003_match_card; epass2003_ops.init = epass2003_init; epass2003_ops.finish = epass2003_finish; epass2003_ops.write_binary = NULL; epass2003_ops.write_record = NULL; epass2003_ops.select_file = epass2003_select_file; epass2003_ops.get_response = NULL; epass2003_ops.restore_security_env = epass2003_restore_security_env; epass2003_ops.set_security_env = epass2003_set_security_env; epass2003_ops.decipher = epass2003_decipher; epass2003_ops.compute_signature = epass2003_decipher; epass2003_ops.create_file = epass2003_create_file; epass2003_ops.delete_file = epass2003_delete_file; epass2003_ops.list_files = epass2003_list_files; epass2003_ops.card_ctl = epass2003_card_ctl; epass2003_ops.process_fci = epass2003_process_fci; epass2003_ops.construct_fci = epass2003_construct_fci; epass2003_ops.pin_cmd = epass2003_pin_cmd; epass2003_ops.check_sw = epass2003_check_sw; epass2003_ops.get_challenge = epass2003_get_challenge; return &epass2003_drv; } struct sc_card_driver *sc_get_epass2003_driver(void) { return sc_get_driver(); } #endif /* #ifdef ENABLE_OPENSSL */ #endif /* #ifdef ENABLE_SM */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_344_1
crossvul-cpp_data_good_4945_1
/* (See Documentation/git-fast-import.txt for maintained documentation.) Format of STDIN stream: stream ::= cmd*; cmd ::= new_blob | new_commit | new_tag | reset_branch | checkpoint | progress ; new_blob ::= 'blob' lf mark? file_content; file_content ::= data; new_commit ::= 'commit' sp ref_str lf mark? ('author' (sp name)? sp '<' email '>' sp when lf)? 'committer' (sp name)? sp '<' email '>' sp when lf commit_msg ('from' sp commit-ish lf)? ('merge' sp commit-ish lf)* (file_change | ls)* lf?; commit_msg ::= data; ls ::= 'ls' sp '"' quoted(path) '"' lf; file_change ::= file_clr | file_del | file_rnm | file_cpy | file_obm | file_inm; file_clr ::= 'deleteall' lf; file_del ::= 'D' sp path_str lf; file_rnm ::= 'R' sp path_str sp path_str lf; file_cpy ::= 'C' sp path_str sp path_str lf; file_obm ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf; file_inm ::= 'M' sp mode sp 'inline' sp path_str lf data; note_obm ::= 'N' sp (hexsha1 | idnum) sp commit-ish lf; note_inm ::= 'N' sp 'inline' sp commit-ish lf data; new_tag ::= 'tag' sp tag_str lf 'from' sp commit-ish lf ('tagger' (sp name)? sp '<' email '>' sp when lf)? tag_msg; tag_msg ::= data; reset_branch ::= 'reset' sp ref_str lf ('from' sp commit-ish lf)? lf?; checkpoint ::= 'checkpoint' lf lf?; progress ::= 'progress' sp not_lf* lf lf?; # note: the first idnum in a stream should be 1 and subsequent # idnums should not have gaps between values as this will cause # the stream parser to reserve space for the gapped values. An # idnum can be updated in the future to a new object by issuing # a new mark directive with the old idnum. # mark ::= 'mark' sp idnum lf; data ::= (delimited_data | exact_data) lf?; # note: delim may be any string but must not contain lf. # data_line may contain any data but must not be exactly # delim. delimited_data ::= 'data' sp '<<' delim lf (data_line lf)* delim lf; # note: declen indicates the length of binary_data in bytes. # declen does not include the lf preceding the binary data. # exact_data ::= 'data' sp declen lf binary_data; # note: quoted strings are C-style quoting supporting \c for # common escapes of 'c' (e..g \n, \t, \\, \") or \nnn where nnn # is the signed byte value in octal. Note that the only # characters which must actually be escaped to protect the # stream formatting is: \, " and LF. Otherwise these values # are UTF8. # commit-ish ::= (ref_str | hexsha1 | sha1exp_str | idnum); ref_str ::= ref; sha1exp_str ::= sha1exp; tag_str ::= tag; path_str ::= path | '"' quoted(path) '"' ; mode ::= '100644' | '644' | '100755' | '755' | '120000' ; declen ::= # unsigned 32 bit value, ascii base10 notation; bigint ::= # unsigned integer value, ascii base10 notation; binary_data ::= # file content, not interpreted; when ::= raw_when | rfc2822_when; raw_when ::= ts sp tz; rfc2822_when ::= # Valid RFC 2822 date and time; sp ::= # ASCII space character; lf ::= # ASCII newline (LF) character; # note: a colon (':') must precede the numerical value assigned to # an idnum. This is to distinguish it from a ref or tag name as # GIT does not permit ':' in ref or tag strings. # idnum ::= ':' bigint; path ::= # GIT style file path, e.g. "a/b/c"; ref ::= # GIT ref name, e.g. "refs/heads/MOZ_GECKO_EXPERIMENT"; tag ::= # GIT tag name, e.g. "FIREFOX_1_5"; sha1exp ::= # Any valid GIT SHA1 expression; hexsha1 ::= # SHA1 in hexadecimal format; # note: name and email are UTF8 strings, however name must not # contain '<' or lf and email must not contain any of the # following: '<', '>', lf. # name ::= # valid GIT author/committer name; email ::= # valid GIT author/committer email; ts ::= # time since the epoch in seconds, ascii base10 notation; tz ::= # GIT style timezone; # note: comments, get-mark, ls-tree, and cat-blob requests may # appear anywhere in the input, except within a data command. Any # form of the data command always escapes the related input from # comment processing. # # In case it is not clear, the '#' that starts the comment # must be the first character on that line (an lf # preceded it). # get_mark ::= 'get-mark' sp idnum lf; cat_blob ::= 'cat-blob' sp (hexsha1 | idnum) lf; ls_tree ::= 'ls' sp (hexsha1 | idnum) sp path_str lf; comment ::= '#' not_lf* lf; not_lf ::= # Any byte that is not ASCII newline (LF); */ #include "builtin.h" #include "cache.h" #include "lockfile.h" #include "object.h" #include "blob.h" #include "tree.h" #include "commit.h" #include "delta.h" #include "pack.h" #include "refs.h" #include "csum-file.h" #include "quote.h" #include "exec_cmd.h" #include "dir.h" #define PACK_ID_BITS 16 #define MAX_PACK_ID ((1<<PACK_ID_BITS)-1) #define DEPTH_BITS 13 #define MAX_DEPTH ((1<<DEPTH_BITS)-1) /* * We abuse the setuid bit on directories to mean "do not delta". */ #define NO_DELTA S_ISUID struct object_entry { struct pack_idx_entry idx; struct object_entry *next; uint32_t type : TYPE_BITS, pack_id : PACK_ID_BITS, depth : DEPTH_BITS; }; struct object_entry_pool { struct object_entry_pool *next_pool; struct object_entry *next_free; struct object_entry *end; struct object_entry entries[FLEX_ARRAY]; /* more */ }; struct mark_set { union { struct object_entry *marked[1024]; struct mark_set *sets[1024]; } data; unsigned int shift; }; struct last_object { struct strbuf data; off_t offset; unsigned int depth; unsigned no_swap : 1; }; struct mem_pool { struct mem_pool *next_pool; char *next_free; char *end; uintmax_t space[FLEX_ARRAY]; /* more */ }; struct atom_str { struct atom_str *next_atom; unsigned short str_len; char str_dat[FLEX_ARRAY]; /* more */ }; struct tree_content; struct tree_entry { struct tree_content *tree; struct atom_str *name; struct tree_entry_ms { uint16_t mode; unsigned char sha1[20]; } versions[2]; }; struct tree_content { unsigned int entry_capacity; /* must match avail_tree_content */ unsigned int entry_count; unsigned int delta_depth; struct tree_entry *entries[FLEX_ARRAY]; /* more */ }; struct avail_tree_content { unsigned int entry_capacity; /* must match tree_content */ struct avail_tree_content *next_avail; }; struct branch { struct branch *table_next_branch; struct branch *active_next_branch; const char *name; struct tree_entry branch_tree; uintmax_t last_commit; uintmax_t num_notes; unsigned active : 1; unsigned delete : 1; unsigned pack_id : PACK_ID_BITS; unsigned char sha1[20]; }; struct tag { struct tag *next_tag; const char *name; unsigned int pack_id; unsigned char sha1[20]; }; struct hash_list { struct hash_list *next; unsigned char sha1[20]; }; typedef enum { WHENSPEC_RAW = 1, WHENSPEC_RFC2822, WHENSPEC_NOW } whenspec_type; struct recent_command { struct recent_command *prev; struct recent_command *next; char *buf; }; /* Configured limits on output */ static unsigned long max_depth = 10; static off_t max_packsize; static int force_update; static int pack_compression_level = Z_DEFAULT_COMPRESSION; static int pack_compression_seen; /* Stats and misc. counters */ static uintmax_t alloc_count; static uintmax_t marks_set_count; static uintmax_t object_count_by_type[1 << TYPE_BITS]; static uintmax_t duplicate_count_by_type[1 << TYPE_BITS]; static uintmax_t delta_count_by_type[1 << TYPE_BITS]; static uintmax_t delta_count_attempts_by_type[1 << TYPE_BITS]; static unsigned long object_count; static unsigned long branch_count; static unsigned long branch_load_count; static int failure; static FILE *pack_edges; static unsigned int show_stats = 1; static int global_argc; static char **global_argv; /* Memory pools */ static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool); static size_t total_allocd; static struct mem_pool *mem_pool; /* Atom management */ static unsigned int atom_table_sz = 4451; static unsigned int atom_cnt; static struct atom_str **atom_table; /* The .pack file being generated */ static struct pack_idx_option pack_idx_opts; static unsigned int pack_id; static struct sha1file *pack_file; static struct packed_git *pack_data; static struct packed_git **all_packs; static off_t pack_size; /* Table of objects we've written. */ static unsigned int object_entry_alloc = 5000; static struct object_entry_pool *blocks; static struct object_entry *object_table[1 << 16]; static struct mark_set *marks; static const char *export_marks_file; static const char *import_marks_file; static int import_marks_file_from_stream; static int import_marks_file_ignore_missing; static int relative_marks_paths; /* Our last blob */ static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 }; /* Tree management */ static unsigned int tree_entry_alloc = 1000; static void *avail_tree_entry; static unsigned int avail_tree_table_sz = 100; static struct avail_tree_content **avail_tree_table; static struct strbuf old_tree = STRBUF_INIT; static struct strbuf new_tree = STRBUF_INIT; /* Branch data */ static unsigned long max_active_branches = 5; static unsigned long cur_active_branches; static unsigned long branch_table_sz = 1039; static struct branch **branch_table; static struct branch *active_branches; /* Tag data */ static struct tag *first_tag; static struct tag *last_tag; /* Input stream parsing */ static whenspec_type whenspec = WHENSPEC_RAW; static struct strbuf command_buf = STRBUF_INIT; static int unread_command_buf; static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL}; static struct recent_command *cmd_tail = &cmd_hist; static struct recent_command *rc_free; static unsigned int cmd_save = 100; static uintmax_t next_mark; static struct strbuf new_data = STRBUF_INIT; static int seen_data_command; static int require_explicit_termination; /* Signal handling */ static volatile sig_atomic_t checkpoint_requested; /* Where to write output of cat-blob commands */ static int cat_blob_fd = STDOUT_FILENO; static void parse_argv(void); static void parse_get_mark(const char *p); static void parse_cat_blob(const char *p); static void parse_ls(const char *p, struct branch *b); static void write_branch_report(FILE *rpt, struct branch *b) { fprintf(rpt, "%s:\n", b->name); fprintf(rpt, " status :"); if (b->active) fputs(" active", rpt); if (b->branch_tree.tree) fputs(" loaded", rpt); if (is_null_sha1(b->branch_tree.versions[1].sha1)) fputs(" dirty", rpt); fputc('\n', rpt); fprintf(rpt, " tip commit : %s\n", sha1_to_hex(b->sha1)); fprintf(rpt, " old tree : %s\n", sha1_to_hex(b->branch_tree.versions[0].sha1)); fprintf(rpt, " cur tree : %s\n", sha1_to_hex(b->branch_tree.versions[1].sha1)); fprintf(rpt, " commit clock: %" PRIuMAX "\n", b->last_commit); fputs(" last pack : ", rpt); if (b->pack_id < MAX_PACK_ID) fprintf(rpt, "%u", b->pack_id); fputc('\n', rpt); fputc('\n', rpt); } static void dump_marks_helper(FILE *, uintmax_t, struct mark_set *); static void write_crash_report(const char *err) { char *loc = git_pathdup("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid()); FILE *rpt = fopen(loc, "w"); struct branch *b; unsigned long lu; struct recent_command *rc; if (!rpt) { error("can't write crash report %s: %s", loc, strerror(errno)); free(loc); return; } fprintf(stderr, "fast-import: dumping crash report to %s\n", loc); fprintf(rpt, "fast-import crash report:\n"); fprintf(rpt, " fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid()); fprintf(rpt, " parent process : %"PRIuMAX"\n", (uintmax_t) getppid()); fprintf(rpt, " at %s\n", show_date(time(NULL), 0, DATE_MODE(LOCAL))); fputc('\n', rpt); fputs("fatal: ", rpt); fputs(err, rpt); fputc('\n', rpt); fputc('\n', rpt); fputs("Most Recent Commands Before Crash\n", rpt); fputs("---------------------------------\n", rpt); for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) { if (rc->next == &cmd_hist) fputs("* ", rpt); else fputs(" ", rpt); fputs(rc->buf, rpt); fputc('\n', rpt); } fputc('\n', rpt); fputs("Active Branch LRU\n", rpt); fputs("-----------------\n", rpt); fprintf(rpt, " active_branches = %lu cur, %lu max\n", cur_active_branches, max_active_branches); fputc('\n', rpt); fputs(" pos clock name\n", rpt); fputs(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt); for (b = active_branches, lu = 0; b; b = b->active_next_branch) fprintf(rpt, " %2lu) %6" PRIuMAX" %s\n", ++lu, b->last_commit, b->name); fputc('\n', rpt); fputs("Inactive Branches\n", rpt); fputs("-----------------\n", rpt); for (lu = 0; lu < branch_table_sz; lu++) { for (b = branch_table[lu]; b; b = b->table_next_branch) write_branch_report(rpt, b); } if (first_tag) { struct tag *tg; fputc('\n', rpt); fputs("Annotated Tags\n", rpt); fputs("--------------\n", rpt); for (tg = first_tag; tg; tg = tg->next_tag) { fputs(sha1_to_hex(tg->sha1), rpt); fputc(' ', rpt); fputs(tg->name, rpt); fputc('\n', rpt); } } fputc('\n', rpt); fputs("Marks\n", rpt); fputs("-----\n", rpt); if (export_marks_file) fprintf(rpt, " exported to %s\n", export_marks_file); else dump_marks_helper(rpt, 0, marks); fputc('\n', rpt); fputs("-------------------\n", rpt); fputs("END OF CRASH REPORT\n", rpt); fclose(rpt); free(loc); } static void end_packfile(void); static void unkeep_all_packs(void); static void dump_marks(void); static NORETURN void die_nicely(const char *err, va_list params) { static int zombie; char message[2 * PATH_MAX]; vsnprintf(message, sizeof(message), err, params); fputs("fatal: ", stderr); fputs(message, stderr); fputc('\n', stderr); if (!zombie) { zombie = 1; write_crash_report(message); end_packfile(); unkeep_all_packs(); dump_marks(); } exit(128); } #ifndef SIGUSR1 /* Windows, for example */ static void set_checkpoint_signal(void) { } #else static void checkpoint_signal(int signo) { checkpoint_requested = 1; } static void set_checkpoint_signal(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = checkpoint_signal; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sigaction(SIGUSR1, &sa, NULL); } #endif static void alloc_objects(unsigned int cnt) { struct object_entry_pool *b; b = xmalloc(sizeof(struct object_entry_pool) + cnt * sizeof(struct object_entry)); b->next_pool = blocks; b->next_free = b->entries; b->end = b->entries + cnt; blocks = b; alloc_count += cnt; } static struct object_entry *new_object(unsigned char *sha1) { struct object_entry *e; if (blocks->next_free == blocks->end) alloc_objects(object_entry_alloc); e = blocks->next_free++; hashcpy(e->idx.sha1, sha1); return e; } static struct object_entry *find_object(unsigned char *sha1) { unsigned int h = sha1[0] << 8 | sha1[1]; struct object_entry *e; for (e = object_table[h]; e; e = e->next) if (!hashcmp(sha1, e->idx.sha1)) return e; return NULL; } static struct object_entry *insert_object(unsigned char *sha1) { unsigned int h = sha1[0] << 8 | sha1[1]; struct object_entry *e = object_table[h]; while (e) { if (!hashcmp(sha1, e->idx.sha1)) return e; e = e->next; } e = new_object(sha1); e->next = object_table[h]; e->idx.offset = 0; object_table[h] = e; return e; } static unsigned int hc_str(const char *s, size_t len) { unsigned int r = 0; while (len-- > 0) r = r * 31 + *s++; return r; } static void *pool_alloc(size_t len) { struct mem_pool *p; void *r; /* round up to a 'uintmax_t' alignment */ if (len & (sizeof(uintmax_t) - 1)) len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1)); for (p = mem_pool; p; p = p->next_pool) if ((p->end - p->next_free >= len)) break; if (!p) { if (len >= (mem_pool_alloc/2)) { total_allocd += len; return xmalloc(len); } total_allocd += sizeof(struct mem_pool) + mem_pool_alloc; p = xmalloc(sizeof(struct mem_pool) + mem_pool_alloc); p->next_pool = mem_pool; p->next_free = (char *) p->space; p->end = p->next_free + mem_pool_alloc; mem_pool = p; } r = p->next_free; p->next_free += len; return r; } static void *pool_calloc(size_t count, size_t size) { size_t len = count * size; void *r = pool_alloc(len); memset(r, 0, len); return r; } static char *pool_strdup(const char *s) { size_t len = strlen(s) + 1; char *r = pool_alloc(len); memcpy(r, s, len); return r; } static void insert_mark(uintmax_t idnum, struct object_entry *oe) { struct mark_set *s = marks; while ((idnum >> s->shift) >= 1024) { s = pool_calloc(1, sizeof(struct mark_set)); s->shift = marks->shift + 10; s->data.sets[0] = marks; marks = s; } while (s->shift) { uintmax_t i = idnum >> s->shift; idnum -= i << s->shift; if (!s->data.sets[i]) { s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set)); s->data.sets[i]->shift = s->shift - 10; } s = s->data.sets[i]; } if (!s->data.marked[idnum]) marks_set_count++; s->data.marked[idnum] = oe; } static struct object_entry *find_mark(uintmax_t idnum) { uintmax_t orig_idnum = idnum; struct mark_set *s = marks; struct object_entry *oe = NULL; if ((idnum >> s->shift) < 1024) { while (s && s->shift) { uintmax_t i = idnum >> s->shift; idnum -= i << s->shift; s = s->data.sets[i]; } if (s) oe = s->data.marked[idnum]; } if (!oe) die("mark :%" PRIuMAX " not declared", orig_idnum); return oe; } static struct atom_str *to_atom(const char *s, unsigned short len) { unsigned int hc = hc_str(s, len) % atom_table_sz; struct atom_str *c; for (c = atom_table[hc]; c; c = c->next_atom) if (c->str_len == len && !strncmp(s, c->str_dat, len)) return c; c = pool_alloc(sizeof(struct atom_str) + len + 1); c->str_len = len; strncpy(c->str_dat, s, len); c->str_dat[len] = 0; c->next_atom = atom_table[hc]; atom_table[hc] = c; atom_cnt++; return c; } static struct branch *lookup_branch(const char *name) { unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz; struct branch *b; for (b = branch_table[hc]; b; b = b->table_next_branch) if (!strcmp(name, b->name)) return b; return NULL; } static struct branch *new_branch(const char *name) { unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz; struct branch *b = lookup_branch(name); if (b) die("Invalid attempt to create duplicate branch: %s", name); if (check_refname_format(name, REFNAME_ALLOW_ONELEVEL)) die("Branch name doesn't conform to GIT standards: %s", name); b = pool_calloc(1, sizeof(struct branch)); b->name = pool_strdup(name); b->table_next_branch = branch_table[hc]; b->branch_tree.versions[0].mode = S_IFDIR; b->branch_tree.versions[1].mode = S_IFDIR; b->num_notes = 0; b->active = 0; b->pack_id = MAX_PACK_ID; branch_table[hc] = b; branch_count++; return b; } static unsigned int hc_entries(unsigned int cnt) { cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8; return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1; } static struct tree_content *new_tree_content(unsigned int cnt) { struct avail_tree_content *f, *l = NULL; struct tree_content *t; unsigned int hc = hc_entries(cnt); for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail) if (f->entry_capacity >= cnt) break; if (f) { if (l) l->next_avail = f->next_avail; else avail_tree_table[hc] = f->next_avail; } else { cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt; f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt); f->entry_capacity = cnt; } t = (struct tree_content*)f; t->entry_count = 0; t->delta_depth = 0; return t; } static void release_tree_entry(struct tree_entry *e); static void release_tree_content(struct tree_content *t) { struct avail_tree_content *f = (struct avail_tree_content*)t; unsigned int hc = hc_entries(f->entry_capacity); f->next_avail = avail_tree_table[hc]; avail_tree_table[hc] = f; } static void release_tree_content_recursive(struct tree_content *t) { unsigned int i; for (i = 0; i < t->entry_count; i++) release_tree_entry(t->entries[i]); release_tree_content(t); } static struct tree_content *grow_tree_content( struct tree_content *t, int amt) { struct tree_content *r = new_tree_content(t->entry_count + amt); r->entry_count = t->entry_count; r->delta_depth = t->delta_depth; memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0])); release_tree_content(t); return r; } static struct tree_entry *new_tree_entry(void) { struct tree_entry *e; if (!avail_tree_entry) { unsigned int n = tree_entry_alloc; total_allocd += n * sizeof(struct tree_entry); avail_tree_entry = e = xmalloc(n * sizeof(struct tree_entry)); while (n-- > 1) { *((void**)e) = e + 1; e++; } *((void**)e) = NULL; } e = avail_tree_entry; avail_tree_entry = *((void**)e); return e; } static void release_tree_entry(struct tree_entry *e) { if (e->tree) release_tree_content_recursive(e->tree); *((void**)e) = avail_tree_entry; avail_tree_entry = e; } static struct tree_content *dup_tree_content(struct tree_content *s) { struct tree_content *d; struct tree_entry *a, *b; unsigned int i; if (!s) return NULL; d = new_tree_content(s->entry_count); for (i = 0; i < s->entry_count; i++) { a = s->entries[i]; b = new_tree_entry(); memcpy(b, a, sizeof(*a)); if (a->tree && is_null_sha1(b->versions[1].sha1)) b->tree = dup_tree_content(a->tree); else b->tree = NULL; d->entries[i] = b; } d->entry_count = s->entry_count; d->delta_depth = s->delta_depth; return d; } static void start_packfile(void) { static char tmp_file[PATH_MAX]; struct packed_git *p; int namelen; struct pack_header hdr; int pack_fd; pack_fd = odb_mkstemp(tmp_file, sizeof(tmp_file), "pack/tmp_pack_XXXXXX"); namelen = strlen(tmp_file) + 2; p = xcalloc(1, sizeof(*p) + namelen); xsnprintf(p->pack_name, namelen, "%s", tmp_file); p->pack_fd = pack_fd; p->do_not_close = 1; pack_file = sha1fd(pack_fd, p->pack_name); hdr.hdr_signature = htonl(PACK_SIGNATURE); hdr.hdr_version = htonl(2); hdr.hdr_entries = 0; sha1write(pack_file, &hdr, sizeof(hdr)); pack_data = p; pack_size = sizeof(hdr); object_count = 0; REALLOC_ARRAY(all_packs, pack_id + 1); all_packs[pack_id] = p; } static const char *create_index(void) { const char *tmpfile; struct pack_idx_entry **idx, **c, **last; struct object_entry *e; struct object_entry_pool *o; /* Build the table of object IDs. */ idx = xmalloc(object_count * sizeof(*idx)); c = idx; for (o = blocks; o; o = o->next_pool) for (e = o->next_free; e-- != o->entries;) if (pack_id == e->pack_id) *c++ = &e->idx; last = idx + object_count; if (c != last) die("internal consistency error creating the index"); tmpfile = write_idx_file(NULL, idx, object_count, &pack_idx_opts, pack_data->sha1); free(idx); return tmpfile; } static char *keep_pack(const char *curr_index_name) { static char name[PATH_MAX]; static const char *keep_msg = "fast-import"; int keep_fd; keep_fd = odb_pack_keep(name, sizeof(name), pack_data->sha1); if (keep_fd < 0) die_errno("cannot create keep file"); write_or_die(keep_fd, keep_msg, strlen(keep_msg)); if (close(keep_fd)) die_errno("failed to write keep file"); snprintf(name, sizeof(name), "%s/pack/pack-%s.pack", get_object_directory(), sha1_to_hex(pack_data->sha1)); if (finalize_object_file(pack_data->pack_name, name)) die("cannot store pack file"); snprintf(name, sizeof(name), "%s/pack/pack-%s.idx", get_object_directory(), sha1_to_hex(pack_data->sha1)); if (finalize_object_file(curr_index_name, name)) die("cannot store index file"); free((void *)curr_index_name); return name; } static void unkeep_all_packs(void) { static char name[PATH_MAX]; int k; for (k = 0; k < pack_id; k++) { struct packed_git *p = all_packs[k]; snprintf(name, sizeof(name), "%s/pack/pack-%s.keep", get_object_directory(), sha1_to_hex(p->sha1)); unlink_or_warn(name); } } static void end_packfile(void) { static int running; if (running || !pack_data) return; running = 1; clear_delta_base_cache(); if (object_count) { struct packed_git *new_p; unsigned char cur_pack_sha1[20]; char *idx_name; int i; struct branch *b; struct tag *t; close_pack_windows(pack_data); sha1close(pack_file, cur_pack_sha1, 0); fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1, pack_data->pack_name, object_count, cur_pack_sha1, pack_size); close(pack_data->pack_fd); idx_name = keep_pack(create_index()); /* Register the packfile with core git's machinery. */ new_p = add_packed_git(idx_name, strlen(idx_name), 1); if (!new_p) die("core git rejected index %s", idx_name); all_packs[pack_id] = new_p; install_packed_git(new_p); /* Print the boundary */ if (pack_edges) { fprintf(pack_edges, "%s:", new_p->pack_name); for (i = 0; i < branch_table_sz; i++) { for (b = branch_table[i]; b; b = b->table_next_branch) { if (b->pack_id == pack_id) fprintf(pack_edges, " %s", sha1_to_hex(b->sha1)); } } for (t = first_tag; t; t = t->next_tag) { if (t->pack_id == pack_id) fprintf(pack_edges, " %s", sha1_to_hex(t->sha1)); } fputc('\n', pack_edges); fflush(pack_edges); } pack_id++; } else { close(pack_data->pack_fd); unlink_or_warn(pack_data->pack_name); } free(pack_data); pack_data = NULL; running = 0; /* We can't carry a delta across packfiles. */ strbuf_release(&last_blob.data); last_blob.offset = 0; last_blob.depth = 0; } static void cycle_packfile(void) { end_packfile(); start_packfile(); } static int store_object( enum object_type type, struct strbuf *dat, struct last_object *last, unsigned char *sha1out, uintmax_t mark) { void *out, *delta; struct object_entry *e; unsigned char hdr[96]; unsigned char sha1[20]; unsigned long hdrlen, deltalen; git_SHA_CTX c; git_zstream s; hdrlen = xsnprintf((char *)hdr, sizeof(hdr), "%s %lu", typename(type), (unsigned long)dat->len) + 1; git_SHA1_Init(&c); git_SHA1_Update(&c, hdr, hdrlen); git_SHA1_Update(&c, dat->buf, dat->len); git_SHA1_Final(sha1, &c); if (sha1out) hashcpy(sha1out, sha1); e = insert_object(sha1); if (mark) insert_mark(mark, e); if (e->idx.offset) { duplicate_count_by_type[type]++; return 1; } else if (find_sha1_pack(sha1, packed_git)) { e->type = type; e->pack_id = MAX_PACK_ID; e->idx.offset = 1; /* just not zero! */ duplicate_count_by_type[type]++; return 1; } if (last && last->data.buf && last->depth < max_depth && dat->len > 20) { delta_count_attempts_by_type[type]++; delta = diff_delta(last->data.buf, last->data.len, dat->buf, dat->len, &deltalen, dat->len - 20); } else delta = NULL; git_deflate_init(&s, pack_compression_level); if (delta) { s.next_in = delta; s.avail_in = deltalen; } else { s.next_in = (void *)dat->buf; s.avail_in = dat->len; } s.avail_out = git_deflate_bound(&s, s.avail_in); s.next_out = out = xmalloc(s.avail_out); while (git_deflate(&s, Z_FINISH) == Z_OK) ; /* nothing */ git_deflate_end(&s); /* Determine if we should auto-checkpoint. */ if ((max_packsize && (pack_size + 60 + s.total_out) > max_packsize) || (pack_size + 60 + s.total_out) < pack_size) { /* This new object needs to *not* have the current pack_id. */ e->pack_id = pack_id + 1; cycle_packfile(); /* We cannot carry a delta into the new pack. */ if (delta) { free(delta); delta = NULL; git_deflate_init(&s, pack_compression_level); s.next_in = (void *)dat->buf; s.avail_in = dat->len; s.avail_out = git_deflate_bound(&s, s.avail_in); s.next_out = out = xrealloc(out, s.avail_out); while (git_deflate(&s, Z_FINISH) == Z_OK) ; /* nothing */ git_deflate_end(&s); } } e->type = type; e->pack_id = pack_id; e->idx.offset = pack_size; object_count++; object_count_by_type[type]++; crc32_begin(pack_file); if (delta) { off_t ofs = e->idx.offset - last->offset; unsigned pos = sizeof(hdr) - 1; delta_count_by_type[type]++; e->depth = last->depth + 1; hdrlen = encode_in_pack_object_header(OBJ_OFS_DELTA, deltalen, hdr); sha1write(pack_file, hdr, hdrlen); pack_size += hdrlen; hdr[pos] = ofs & 127; while (ofs >>= 7) hdr[--pos] = 128 | (--ofs & 127); sha1write(pack_file, hdr + pos, sizeof(hdr) - pos); pack_size += sizeof(hdr) - pos; } else { e->depth = 0; hdrlen = encode_in_pack_object_header(type, dat->len, hdr); sha1write(pack_file, hdr, hdrlen); pack_size += hdrlen; } sha1write(pack_file, out, s.total_out); pack_size += s.total_out; e->idx.crc32 = crc32_end(pack_file); free(out); free(delta); if (last) { if (last->no_swap) { last->data = *dat; } else { strbuf_swap(&last->data, dat); } last->offset = e->idx.offset; last->depth = e->depth; } return 0; } static void truncate_pack(struct sha1file_checkpoint *checkpoint) { if (sha1file_truncate(pack_file, checkpoint)) die_errno("cannot truncate pack to skip duplicate"); pack_size = checkpoint->offset; } static void stream_blob(uintmax_t len, unsigned char *sha1out, uintmax_t mark) { size_t in_sz = 64 * 1024, out_sz = 64 * 1024; unsigned char *in_buf = xmalloc(in_sz); unsigned char *out_buf = xmalloc(out_sz); struct object_entry *e; unsigned char sha1[20]; unsigned long hdrlen; off_t offset; git_SHA_CTX c; git_zstream s; struct sha1file_checkpoint checkpoint; int status = Z_OK; /* Determine if we should auto-checkpoint. */ if ((max_packsize && (pack_size + 60 + len) > max_packsize) || (pack_size + 60 + len) < pack_size) cycle_packfile(); sha1file_checkpoint(pack_file, &checkpoint); offset = checkpoint.offset; hdrlen = snprintf((char *)out_buf, out_sz, "blob %" PRIuMAX, len) + 1; if (out_sz <= hdrlen) die("impossibly large object header"); git_SHA1_Init(&c); git_SHA1_Update(&c, out_buf, hdrlen); crc32_begin(pack_file); git_deflate_init(&s, pack_compression_level); hdrlen = encode_in_pack_object_header(OBJ_BLOB, len, out_buf); if (out_sz <= hdrlen) die("impossibly large object header"); s.next_out = out_buf + hdrlen; s.avail_out = out_sz - hdrlen; while (status != Z_STREAM_END) { if (0 < len && !s.avail_in) { size_t cnt = in_sz < len ? in_sz : (size_t)len; size_t n = fread(in_buf, 1, cnt, stdin); if (!n && feof(stdin)) die("EOF in data (%" PRIuMAX " bytes remaining)", len); git_SHA1_Update(&c, in_buf, n); s.next_in = in_buf; s.avail_in = n; len -= n; } status = git_deflate(&s, len ? 0 : Z_FINISH); if (!s.avail_out || status == Z_STREAM_END) { size_t n = s.next_out - out_buf; sha1write(pack_file, out_buf, n); pack_size += n; s.next_out = out_buf; s.avail_out = out_sz; } switch (status) { case Z_OK: case Z_BUF_ERROR: case Z_STREAM_END: continue; default: die("unexpected deflate failure: %d", status); } } git_deflate_end(&s); git_SHA1_Final(sha1, &c); if (sha1out) hashcpy(sha1out, sha1); e = insert_object(sha1); if (mark) insert_mark(mark, e); if (e->idx.offset) { duplicate_count_by_type[OBJ_BLOB]++; truncate_pack(&checkpoint); } else if (find_sha1_pack(sha1, packed_git)) { e->type = OBJ_BLOB; e->pack_id = MAX_PACK_ID; e->idx.offset = 1; /* just not zero! */ duplicate_count_by_type[OBJ_BLOB]++; truncate_pack(&checkpoint); } else { e->depth = 0; e->type = OBJ_BLOB; e->pack_id = pack_id; e->idx.offset = offset; e->idx.crc32 = crc32_end(pack_file); object_count++; object_count_by_type[OBJ_BLOB]++; } free(in_buf); free(out_buf); } /* All calls must be guarded by find_object() or find_mark() to * ensure the 'struct object_entry' passed was written by this * process instance. We unpack the entry by the offset, avoiding * the need for the corresponding .idx file. This unpacking rule * works because we only use OBJ_REF_DELTA within the packfiles * created by fast-import. * * oe must not be NULL. Such an oe usually comes from giving * an unknown SHA-1 to find_object() or an undefined mark to * find_mark(). Callers must test for this condition and use * the standard read_sha1_file() when it happens. * * oe->pack_id must not be MAX_PACK_ID. Such an oe is usually from * find_mark(), where the mark was reloaded from an existing marks * file and is referencing an object that this fast-import process * instance did not write out to a packfile. Callers must test for * this condition and use read_sha1_file() instead. */ static void *gfi_unpack_entry( struct object_entry *oe, unsigned long *sizep) { enum object_type type; struct packed_git *p = all_packs[oe->pack_id]; if (p == pack_data && p->pack_size < (pack_size + 20)) { /* The object is stored in the packfile we are writing to * and we have modified it since the last time we scanned * back to read a previously written object. If an old * window covered [p->pack_size, p->pack_size + 20) its * data is stale and is not valid. Closing all windows * and updating the packfile length ensures we can read * the newly written data. */ close_pack_windows(p); sha1flush(pack_file); /* We have to offer 20 bytes additional on the end of * the packfile as the core unpacker code assumes the * footer is present at the file end and must promise * at least 20 bytes within any window it maps. But * we don't actually create the footer here. */ p->pack_size = pack_size + 20; } return unpack_entry(p, oe->idx.offset, &type, sizep); } static const char *get_mode(const char *str, uint16_t *modep) { unsigned char c; uint16_t mode = 0; while ((c = *str++) != ' ') { if (c < '0' || c > '7') return NULL; mode = (mode << 3) + (c - '0'); } *modep = mode; return str; } static void load_tree(struct tree_entry *root) { unsigned char *sha1 = root->versions[1].sha1; struct object_entry *myoe; struct tree_content *t; unsigned long size; char *buf; const char *c; root->tree = t = new_tree_content(8); if (is_null_sha1(sha1)) return; myoe = find_object(sha1); if (myoe && myoe->pack_id != MAX_PACK_ID) { if (myoe->type != OBJ_TREE) die("Not a tree: %s", sha1_to_hex(sha1)); t->delta_depth = myoe->depth; buf = gfi_unpack_entry(myoe, &size); if (!buf) die("Can't load tree %s", sha1_to_hex(sha1)); } else { enum object_type type; buf = read_sha1_file(sha1, &type, &size); if (!buf || type != OBJ_TREE) die("Can't load tree %s", sha1_to_hex(sha1)); } c = buf; while (c != (buf + size)) { struct tree_entry *e = new_tree_entry(); if (t->entry_count == t->entry_capacity) root->tree = t = grow_tree_content(t, t->entry_count); t->entries[t->entry_count++] = e; e->tree = NULL; c = get_mode(c, &e->versions[1].mode); if (!c) die("Corrupt mode in %s", sha1_to_hex(sha1)); e->versions[0].mode = e->versions[1].mode; e->name = to_atom(c, strlen(c)); c += e->name->str_len + 1; hashcpy(e->versions[0].sha1, (unsigned char *)c); hashcpy(e->versions[1].sha1, (unsigned char *)c); c += 20; } free(buf); } static int tecmp0 (const void *_a, const void *_b) { struct tree_entry *a = *((struct tree_entry**)_a); struct tree_entry *b = *((struct tree_entry**)_b); return base_name_compare( a->name->str_dat, a->name->str_len, a->versions[0].mode, b->name->str_dat, b->name->str_len, b->versions[0].mode); } static int tecmp1 (const void *_a, const void *_b) { struct tree_entry *a = *((struct tree_entry**)_a); struct tree_entry *b = *((struct tree_entry**)_b); return base_name_compare( a->name->str_dat, a->name->str_len, a->versions[1].mode, b->name->str_dat, b->name->str_len, b->versions[1].mode); } static void mktree(struct tree_content *t, int v, struct strbuf *b) { size_t maxlen = 0; unsigned int i; if (!v) qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp0); else qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp1); for (i = 0; i < t->entry_count; i++) { if (t->entries[i]->versions[v].mode) maxlen += t->entries[i]->name->str_len + 34; } strbuf_reset(b); strbuf_grow(b, maxlen); for (i = 0; i < t->entry_count; i++) { struct tree_entry *e = t->entries[i]; if (!e->versions[v].mode) continue; strbuf_addf(b, "%o %s%c", (unsigned int)(e->versions[v].mode & ~NO_DELTA), e->name->str_dat, '\0'); strbuf_add(b, e->versions[v].sha1, 20); } } static void store_tree(struct tree_entry *root) { struct tree_content *t; unsigned int i, j, del; struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 }; struct object_entry *le = NULL; if (!is_null_sha1(root->versions[1].sha1)) return; if (!root->tree) load_tree(root); t = root->tree; for (i = 0; i < t->entry_count; i++) { if (t->entries[i]->tree) store_tree(t->entries[i]); } if (!(root->versions[0].mode & NO_DELTA)) le = find_object(root->versions[0].sha1); if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) { mktree(t, 0, &old_tree); lo.data = old_tree; lo.offset = le->idx.offset; lo.depth = t->delta_depth; } mktree(t, 1, &new_tree); store_object(OBJ_TREE, &new_tree, &lo, root->versions[1].sha1, 0); t->delta_depth = lo.depth; for (i = 0, j = 0, del = 0; i < t->entry_count; i++) { struct tree_entry *e = t->entries[i]; if (e->versions[1].mode) { e->versions[0].mode = e->versions[1].mode; hashcpy(e->versions[0].sha1, e->versions[1].sha1); t->entries[j++] = e; } else { release_tree_entry(e); del++; } } t->entry_count -= del; } static void tree_content_replace( struct tree_entry *root, const unsigned char *sha1, const uint16_t mode, struct tree_content *newtree) { if (!S_ISDIR(mode)) die("Root cannot be a non-directory"); hashclr(root->versions[0].sha1); hashcpy(root->versions[1].sha1, sha1); if (root->tree) release_tree_content_recursive(root->tree); root->tree = newtree; } static int tree_content_set( struct tree_entry *root, const char *p, const unsigned char *sha1, const uint16_t mode, struct tree_content *subtree) { struct tree_content *t; const char *slash1; unsigned int i, n; struct tree_entry *e; slash1 = strchrnul(p, '/'); n = slash1 - p; if (!n) die("Empty path component found in input"); if (!*slash1 && !S_ISDIR(mode) && subtree) die("Non-directories cannot have subtrees"); if (!root->tree) load_tree(root); t = root->tree; for (i = 0; i < t->entry_count; i++) { e = t->entries[i]; if (e->name->str_len == n && !strncmp_icase(p, e->name->str_dat, n)) { if (!*slash1) { if (!S_ISDIR(mode) && e->versions[1].mode == mode && !hashcmp(e->versions[1].sha1, sha1)) return 0; e->versions[1].mode = mode; hashcpy(e->versions[1].sha1, sha1); if (e->tree) release_tree_content_recursive(e->tree); e->tree = subtree; /* * We need to leave e->versions[0].sha1 alone * to avoid modifying the preimage tree used * when writing out the parent directory. * But after replacing the subdir with a * completely different one, it's not a good * delta base any more, and besides, we've * thrown away the tree entries needed to * make a delta against it. * * So let's just explicitly disable deltas * for the subtree. */ if (S_ISDIR(e->versions[0].mode)) e->versions[0].mode |= NO_DELTA; hashclr(root->versions[1].sha1); return 1; } if (!S_ISDIR(e->versions[1].mode)) { e->tree = new_tree_content(8); e->versions[1].mode = S_IFDIR; } if (!e->tree) load_tree(e); if (tree_content_set(e, slash1 + 1, sha1, mode, subtree)) { hashclr(root->versions[1].sha1); return 1; } return 0; } } if (t->entry_count == t->entry_capacity) root->tree = t = grow_tree_content(t, t->entry_count); e = new_tree_entry(); e->name = to_atom(p, n); e->versions[0].mode = 0; hashclr(e->versions[0].sha1); t->entries[t->entry_count++] = e; if (*slash1) { e->tree = new_tree_content(8); e->versions[1].mode = S_IFDIR; tree_content_set(e, slash1 + 1, sha1, mode, subtree); } else { e->tree = subtree; e->versions[1].mode = mode; hashcpy(e->versions[1].sha1, sha1); } hashclr(root->versions[1].sha1); return 1; } static int tree_content_remove( struct tree_entry *root, const char *p, struct tree_entry *backup_leaf, int allow_root) { struct tree_content *t; const char *slash1; unsigned int i, n; struct tree_entry *e; slash1 = strchrnul(p, '/'); n = slash1 - p; if (!root->tree) load_tree(root); if (!*p && allow_root) { e = root; goto del_entry; } t = root->tree; for (i = 0; i < t->entry_count; i++) { e = t->entries[i]; if (e->name->str_len == n && !strncmp_icase(p, e->name->str_dat, n)) { if (*slash1 && !S_ISDIR(e->versions[1].mode)) /* * If p names a file in some subdirectory, and a * file or symlink matching the name of the * parent directory of p exists, then p cannot * exist and need not be deleted. */ return 1; if (!*slash1 || !S_ISDIR(e->versions[1].mode)) goto del_entry; if (!e->tree) load_tree(e); if (tree_content_remove(e, slash1 + 1, backup_leaf, 0)) { for (n = 0; n < e->tree->entry_count; n++) { if (e->tree->entries[n]->versions[1].mode) { hashclr(root->versions[1].sha1); return 1; } } backup_leaf = NULL; goto del_entry; } return 0; } } return 0; del_entry: if (backup_leaf) memcpy(backup_leaf, e, sizeof(*backup_leaf)); else if (e->tree) release_tree_content_recursive(e->tree); e->tree = NULL; e->versions[1].mode = 0; hashclr(e->versions[1].sha1); hashclr(root->versions[1].sha1); return 1; } static int tree_content_get( struct tree_entry *root, const char *p, struct tree_entry *leaf, int allow_root) { struct tree_content *t; const char *slash1; unsigned int i, n; struct tree_entry *e; slash1 = strchrnul(p, '/'); n = slash1 - p; if (!n && !allow_root) die("Empty path component found in input"); if (!root->tree) load_tree(root); if (!n) { e = root; goto found_entry; } t = root->tree; for (i = 0; i < t->entry_count; i++) { e = t->entries[i]; if (e->name->str_len == n && !strncmp_icase(p, e->name->str_dat, n)) { if (!*slash1) goto found_entry; if (!S_ISDIR(e->versions[1].mode)) return 0; if (!e->tree) load_tree(e); return tree_content_get(e, slash1 + 1, leaf, 0); } } return 0; found_entry: memcpy(leaf, e, sizeof(*leaf)); if (e->tree && is_null_sha1(e->versions[1].sha1)) leaf->tree = dup_tree_content(e->tree); else leaf->tree = NULL; return 1; } static int update_branch(struct branch *b) { static const char *msg = "fast-import"; struct ref_transaction *transaction; unsigned char old_sha1[20]; struct strbuf err = STRBUF_INIT; if (is_null_sha1(b->sha1)) { if (b->delete) delete_ref(b->name, NULL, 0); return 0; } if (read_ref(b->name, old_sha1)) hashclr(old_sha1); if (!force_update && !is_null_sha1(old_sha1)) { struct commit *old_cmit, *new_cmit; old_cmit = lookup_commit_reference_gently(old_sha1, 0); new_cmit = lookup_commit_reference_gently(b->sha1, 0); if (!old_cmit || !new_cmit) return error("Branch %s is missing commits.", b->name); if (!in_merge_bases(old_cmit, new_cmit)) { warning("Not updating %s" " (new tip %s does not contain %s)", b->name, sha1_to_hex(b->sha1), sha1_to_hex(old_sha1)); return -1; } } transaction = ref_transaction_begin(&err); if (!transaction || ref_transaction_update(transaction, b->name, b->sha1, old_sha1, 0, msg, &err) || ref_transaction_commit(transaction, &err)) { ref_transaction_free(transaction); error("%s", err.buf); strbuf_release(&err); return -1; } ref_transaction_free(transaction); strbuf_release(&err); return 0; } static void dump_branches(void) { unsigned int i; struct branch *b; for (i = 0; i < branch_table_sz; i++) { for (b = branch_table[i]; b; b = b->table_next_branch) failure |= update_branch(b); } } static void dump_tags(void) { static const char *msg = "fast-import"; struct tag *t; struct strbuf ref_name = STRBUF_INIT; struct strbuf err = STRBUF_INIT; struct ref_transaction *transaction; transaction = ref_transaction_begin(&err); if (!transaction) { failure |= error("%s", err.buf); goto cleanup; } for (t = first_tag; t; t = t->next_tag) { strbuf_reset(&ref_name); strbuf_addf(&ref_name, "refs/tags/%s", t->name); if (ref_transaction_update(transaction, ref_name.buf, t->sha1, NULL, 0, msg, &err)) { failure |= error("%s", err.buf); goto cleanup; } } if (ref_transaction_commit(transaction, &err)) failure |= error("%s", err.buf); cleanup: ref_transaction_free(transaction); strbuf_release(&ref_name); strbuf_release(&err); } static void dump_marks_helper(FILE *f, uintmax_t base, struct mark_set *m) { uintmax_t k; if (m->shift) { for (k = 0; k < 1024; k++) { if (m->data.sets[k]) dump_marks_helper(f, base + (k << m->shift), m->data.sets[k]); } } else { for (k = 0; k < 1024; k++) { if (m->data.marked[k]) fprintf(f, ":%" PRIuMAX " %s\n", base + k, sha1_to_hex(m->data.marked[k]->idx.sha1)); } } } static void dump_marks(void) { static struct lock_file mark_lock; FILE *f; if (!export_marks_file) return; if (hold_lock_file_for_update(&mark_lock, export_marks_file, 0) < 0) { failure |= error("Unable to write marks file %s: %s", export_marks_file, strerror(errno)); return; } f = fdopen_lock_file(&mark_lock, "w"); if (!f) { int saved_errno = errno; rollback_lock_file(&mark_lock); failure |= error("Unable to write marks file %s: %s", export_marks_file, strerror(saved_errno)); return; } dump_marks_helper(f, 0, marks); if (commit_lock_file(&mark_lock)) { failure |= error("Unable to commit marks file %s: %s", export_marks_file, strerror(errno)); return; } } static void read_marks(void) { char line[512]; FILE *f = fopen(import_marks_file, "r"); if (f) ; else if (import_marks_file_ignore_missing && errno == ENOENT) return; /* Marks file does not exist */ else die_errno("cannot read '%s'", import_marks_file); while (fgets(line, sizeof(line), f)) { uintmax_t mark; char *end; unsigned char sha1[20]; struct object_entry *e; end = strchr(line, '\n'); if (line[0] != ':' || !end) die("corrupt mark line: %s", line); *end = 0; mark = strtoumax(line + 1, &end, 10); if (!mark || end == line + 1 || *end != ' ' || get_sha1_hex(end + 1, sha1)) die("corrupt mark line: %s", line); e = find_object(sha1); if (!e) { enum object_type type = sha1_object_info(sha1, NULL); if (type < 0) die("object not found: %s", sha1_to_hex(sha1)); e = insert_object(sha1); e->type = type; e->pack_id = MAX_PACK_ID; e->idx.offset = 1; /* just not zero! */ } insert_mark(mark, e); } fclose(f); } static int read_next_command(void) { static int stdin_eof = 0; if (stdin_eof) { unread_command_buf = 0; return EOF; } for (;;) { const char *p; if (unread_command_buf) { unread_command_buf = 0; } else { struct recent_command *rc; strbuf_detach(&command_buf, NULL); stdin_eof = strbuf_getline(&command_buf, stdin, '\n'); if (stdin_eof) return EOF; if (!seen_data_command && !starts_with(command_buf.buf, "feature ") && !starts_with(command_buf.buf, "option ")) { parse_argv(); } rc = rc_free; if (rc) rc_free = rc->next; else { rc = cmd_hist.next; cmd_hist.next = rc->next; cmd_hist.next->prev = &cmd_hist; free(rc->buf); } rc->buf = command_buf.buf; rc->prev = cmd_tail; rc->next = cmd_hist.prev; rc->prev->next = rc; cmd_tail = rc; } if (skip_prefix(command_buf.buf, "get-mark ", &p)) { parse_get_mark(p); continue; } if (skip_prefix(command_buf.buf, "cat-blob ", &p)) { parse_cat_blob(p); continue; } if (command_buf.buf[0] == '#') continue; return 0; } } static void skip_optional_lf(void) { int term_char = fgetc(stdin); if (term_char != '\n' && term_char != EOF) ungetc(term_char, stdin); } static void parse_mark(void) { const char *v; if (skip_prefix(command_buf.buf, "mark :", &v)) { next_mark = strtoumax(v, NULL, 10); read_next_command(); } else next_mark = 0; } static int parse_data(struct strbuf *sb, uintmax_t limit, uintmax_t *len_res) { const char *data; strbuf_reset(sb); if (!skip_prefix(command_buf.buf, "data ", &data)) die("Expected 'data n' command, found: %s", command_buf.buf); if (skip_prefix(data, "<<", &data)) { char *term = xstrdup(data); size_t term_len = command_buf.len - (data - command_buf.buf); strbuf_detach(&command_buf, NULL); for (;;) { if (strbuf_getline(&command_buf, stdin, '\n') == EOF) die("EOF in data (terminator '%s' not found)", term); if (term_len == command_buf.len && !strcmp(term, command_buf.buf)) break; strbuf_addbuf(sb, &command_buf); strbuf_addch(sb, '\n'); } free(term); } else { uintmax_t len = strtoumax(data, NULL, 10); size_t n = 0, length = (size_t)len; if (limit && limit < len) { *len_res = len; return 0; } if (length < len) die("data is too large to use in this context"); while (n < length) { size_t s = strbuf_fread(sb, length - n, stdin); if (!s && feof(stdin)) die("EOF in data (%lu bytes remaining)", (unsigned long)(length - n)); n += s; } } skip_optional_lf(); return 1; } static int validate_raw_date(const char *src, struct strbuf *result) { const char *orig_src = src; char *endp; unsigned long num; errno = 0; num = strtoul(src, &endp, 10); /* NEEDSWORK: perhaps check for reasonable values? */ if (errno || endp == src || *endp != ' ') return -1; src = endp + 1; if (*src != '-' && *src != '+') return -1; num = strtoul(src + 1, &endp, 10); if (errno || endp == src + 1 || *endp || 1400 < num) return -1; strbuf_addstr(result, orig_src); return 0; } static char *parse_ident(const char *buf) { const char *ltgt; size_t name_len; struct strbuf ident = STRBUF_INIT; /* ensure there is a space delimiter even if there is no name */ if (*buf == '<') --buf; ltgt = buf + strcspn(buf, "<>"); if (*ltgt != '<') die("Missing < in ident string: %s", buf); if (ltgt != buf && ltgt[-1] != ' ') die("Missing space before < in ident string: %s", buf); ltgt = ltgt + 1 + strcspn(ltgt + 1, "<>"); if (*ltgt != '>') die("Missing > in ident string: %s", buf); ltgt++; if (*ltgt != ' ') die("Missing space after > in ident string: %s", buf); ltgt++; name_len = ltgt - buf; strbuf_add(&ident, buf, name_len); switch (whenspec) { case WHENSPEC_RAW: if (validate_raw_date(ltgt, &ident) < 0) die("Invalid raw date \"%s\" in ident: %s", ltgt, buf); break; case WHENSPEC_RFC2822: if (parse_date(ltgt, &ident) < 0) die("Invalid rfc2822 date \"%s\" in ident: %s", ltgt, buf); break; case WHENSPEC_NOW: if (strcmp("now", ltgt)) die("Date in ident must be 'now': %s", buf); datestamp(&ident); break; } return strbuf_detach(&ident, NULL); } static void parse_and_store_blob( struct last_object *last, unsigned char *sha1out, uintmax_t mark) { static struct strbuf buf = STRBUF_INIT; uintmax_t len; if (parse_data(&buf, big_file_threshold, &len)) store_object(OBJ_BLOB, &buf, last, sha1out, mark); else { if (last) { strbuf_release(&last->data); last->offset = 0; last->depth = 0; } stream_blob(len, sha1out, mark); skip_optional_lf(); } } static void parse_new_blob(void) { read_next_command(); parse_mark(); parse_and_store_blob(&last_blob, NULL, next_mark); } static void unload_one_branch(void) { while (cur_active_branches && cur_active_branches >= max_active_branches) { uintmax_t min_commit = ULONG_MAX; struct branch *e, *l = NULL, *p = NULL; for (e = active_branches; e; e = e->active_next_branch) { if (e->last_commit < min_commit) { p = l; min_commit = e->last_commit; } l = e; } if (p) { e = p->active_next_branch; p->active_next_branch = e->active_next_branch; } else { e = active_branches; active_branches = e->active_next_branch; } e->active = 0; e->active_next_branch = NULL; if (e->branch_tree.tree) { release_tree_content_recursive(e->branch_tree.tree); e->branch_tree.tree = NULL; } cur_active_branches--; } } static void load_branch(struct branch *b) { load_tree(&b->branch_tree); if (!b->active) { b->active = 1; b->active_next_branch = active_branches; active_branches = b; cur_active_branches++; branch_load_count++; } } static unsigned char convert_num_notes_to_fanout(uintmax_t num_notes) { unsigned char fanout = 0; while ((num_notes >>= 8)) fanout++; return fanout; } static void construct_path_with_fanout(const char *hex_sha1, unsigned char fanout, char *path) { unsigned int i = 0, j = 0; if (fanout >= 20) die("Too large fanout (%u)", fanout); while (fanout) { path[i++] = hex_sha1[j++]; path[i++] = hex_sha1[j++]; path[i++] = '/'; fanout--; } memcpy(path + i, hex_sha1 + j, 40 - j); path[i + 40 - j] = '\0'; } static uintmax_t do_change_note_fanout( struct tree_entry *orig_root, struct tree_entry *root, char *hex_sha1, unsigned int hex_sha1_len, char *fullpath, unsigned int fullpath_len, unsigned char fanout) { struct tree_content *t = root->tree; struct tree_entry *e, leaf; unsigned int i, tmp_hex_sha1_len, tmp_fullpath_len; uintmax_t num_notes = 0; unsigned char sha1[20]; char realpath[60]; for (i = 0; t && i < t->entry_count; i++) { e = t->entries[i]; tmp_hex_sha1_len = hex_sha1_len + e->name->str_len; tmp_fullpath_len = fullpath_len; /* * We're interested in EITHER existing note entries (entries * with exactly 40 hex chars in path, not including directory * separators), OR directory entries that may contain note * entries (with < 40 hex chars in path). * Also, each path component in a note entry must be a multiple * of 2 chars. */ if (!e->versions[1].mode || tmp_hex_sha1_len > 40 || e->name->str_len % 2) continue; /* This _may_ be a note entry, or a subdir containing notes */ memcpy(hex_sha1 + hex_sha1_len, e->name->str_dat, e->name->str_len); if (tmp_fullpath_len) fullpath[tmp_fullpath_len++] = '/'; memcpy(fullpath + tmp_fullpath_len, e->name->str_dat, e->name->str_len); tmp_fullpath_len += e->name->str_len; fullpath[tmp_fullpath_len] = '\0'; if (tmp_hex_sha1_len == 40 && !get_sha1_hex(hex_sha1, sha1)) { /* This is a note entry */ if (fanout == 0xff) { /* Counting mode, no rename */ num_notes++; continue; } construct_path_with_fanout(hex_sha1, fanout, realpath); if (!strcmp(fullpath, realpath)) { /* Note entry is in correct location */ num_notes++; continue; } /* Rename fullpath to realpath */ if (!tree_content_remove(orig_root, fullpath, &leaf, 0)) die("Failed to remove path %s", fullpath); tree_content_set(orig_root, realpath, leaf.versions[1].sha1, leaf.versions[1].mode, leaf.tree); } else if (S_ISDIR(e->versions[1].mode)) { /* This is a subdir that may contain note entries */ if (!e->tree) load_tree(e); num_notes += do_change_note_fanout(orig_root, e, hex_sha1, tmp_hex_sha1_len, fullpath, tmp_fullpath_len, fanout); } /* The above may have reallocated the current tree_content */ t = root->tree; } return num_notes; } static uintmax_t change_note_fanout(struct tree_entry *root, unsigned char fanout) { char hex_sha1[40], path[60]; return do_change_note_fanout(root, root, hex_sha1, 0, path, 0, fanout); } /* * Given a pointer into a string, parse a mark reference: * * idnum ::= ':' bigint; * * Return the first character after the value in *endptr. * * Complain if the following character is not what is expected, * either a space or end of the string. */ static uintmax_t parse_mark_ref(const char *p, char **endptr) { uintmax_t mark; assert(*p == ':'); p++; mark = strtoumax(p, endptr, 10); if (*endptr == p) die("No value after ':' in mark: %s", command_buf.buf); return mark; } /* * Parse the mark reference, and complain if this is not the end of * the string. */ static uintmax_t parse_mark_ref_eol(const char *p) { char *end; uintmax_t mark; mark = parse_mark_ref(p, &end); if (*end != '\0') die("Garbage after mark: %s", command_buf.buf); return mark; } /* * Parse the mark reference, demanding a trailing space. Return a * pointer to the space. */ static uintmax_t parse_mark_ref_space(const char **p) { uintmax_t mark; char *end; mark = parse_mark_ref(*p, &end); if (*end++ != ' ') die("Missing space after mark: %s", command_buf.buf); *p = end; return mark; } static void file_change_m(const char *p, struct branch *b) { static struct strbuf uq = STRBUF_INIT; const char *endp; struct object_entry *oe; unsigned char sha1[20]; uint16_t mode, inline_data = 0; p = get_mode(p, &mode); if (!p) die("Corrupt mode: %s", command_buf.buf); switch (mode) { case 0644: case 0755: mode |= S_IFREG; case S_IFREG | 0644: case S_IFREG | 0755: case S_IFLNK: case S_IFDIR: case S_IFGITLINK: /* ok */ break; default: die("Corrupt mode: %s", command_buf.buf); } if (*p == ':') { oe = find_mark(parse_mark_ref_space(&p)); hashcpy(sha1, oe->idx.sha1); } else if (skip_prefix(p, "inline ", &p)) { inline_data = 1; oe = NULL; /* not used with inline_data, but makes gcc happy */ } else { if (get_sha1_hex(p, sha1)) die("Invalid dataref: %s", command_buf.buf); oe = find_object(sha1); p += 40; if (*p++ != ' ') die("Missing space after SHA1: %s", command_buf.buf); } strbuf_reset(&uq); if (!unquote_c_style(&uq, p, &endp)) { if (*endp) die("Garbage after path in: %s", command_buf.buf); p = uq.buf; } /* Git does not track empty, non-toplevel directories. */ if (S_ISDIR(mode) && !hashcmp(sha1, EMPTY_TREE_SHA1_BIN) && *p) { tree_content_remove(&b->branch_tree, p, NULL, 0); return; } if (S_ISGITLINK(mode)) { if (inline_data) die("Git links cannot be specified 'inline': %s", command_buf.buf); else if (oe) { if (oe->type != OBJ_COMMIT) die("Not a commit (actually a %s): %s", typename(oe->type), command_buf.buf); } /* * Accept the sha1 without checking; it expected to be in * another repository. */ } else if (inline_data) { if (S_ISDIR(mode)) die("Directories cannot be specified 'inline': %s", command_buf.buf); if (p != uq.buf) { strbuf_addstr(&uq, p); p = uq.buf; } read_next_command(); parse_and_store_blob(&last_blob, sha1, 0); } else { enum object_type expected = S_ISDIR(mode) ? OBJ_TREE: OBJ_BLOB; enum object_type type = oe ? oe->type : sha1_object_info(sha1, NULL); if (type < 0) die("%s not found: %s", S_ISDIR(mode) ? "Tree" : "Blob", command_buf.buf); if (type != expected) die("Not a %s (actually a %s): %s", typename(expected), typename(type), command_buf.buf); } if (!*p) { tree_content_replace(&b->branch_tree, sha1, mode, NULL); return; } tree_content_set(&b->branch_tree, p, sha1, mode, NULL); } static void file_change_d(const char *p, struct branch *b) { static struct strbuf uq = STRBUF_INIT; const char *endp; strbuf_reset(&uq); if (!unquote_c_style(&uq, p, &endp)) { if (*endp) die("Garbage after path in: %s", command_buf.buf); p = uq.buf; } tree_content_remove(&b->branch_tree, p, NULL, 1); } static void file_change_cr(const char *s, struct branch *b, int rename) { const char *d; static struct strbuf s_uq = STRBUF_INIT; static struct strbuf d_uq = STRBUF_INIT; const char *endp; struct tree_entry leaf; strbuf_reset(&s_uq); if (!unquote_c_style(&s_uq, s, &endp)) { if (*endp != ' ') die("Missing space after source: %s", command_buf.buf); } else { endp = strchr(s, ' '); if (!endp) die("Missing space after source: %s", command_buf.buf); strbuf_add(&s_uq, s, endp - s); } s = s_uq.buf; endp++; if (!*endp) die("Missing dest: %s", command_buf.buf); d = endp; strbuf_reset(&d_uq); if (!unquote_c_style(&d_uq, d, &endp)) { if (*endp) die("Garbage after dest in: %s", command_buf.buf); d = d_uq.buf; } memset(&leaf, 0, sizeof(leaf)); if (rename) tree_content_remove(&b->branch_tree, s, &leaf, 1); else tree_content_get(&b->branch_tree, s, &leaf, 1); if (!leaf.versions[1].mode) die("Path %s not in branch", s); if (!*d) { /* C "path/to/subdir" "" */ tree_content_replace(&b->branch_tree, leaf.versions[1].sha1, leaf.versions[1].mode, leaf.tree); return; } tree_content_set(&b->branch_tree, d, leaf.versions[1].sha1, leaf.versions[1].mode, leaf.tree); } static void note_change_n(const char *p, struct branch *b, unsigned char *old_fanout) { static struct strbuf uq = STRBUF_INIT; struct object_entry *oe; struct branch *s; unsigned char sha1[20], commit_sha1[20]; char path[60]; uint16_t inline_data = 0; unsigned char new_fanout; /* * When loading a branch, we don't traverse its tree to count the real * number of notes (too expensive to do this for all non-note refs). * This means that recently loaded notes refs might incorrectly have * b->num_notes == 0, and consequently, old_fanout might be wrong. * * Fix this by traversing the tree and counting the number of notes * when b->num_notes == 0. If the notes tree is truly empty, the * calculation should not take long. */ if (b->num_notes == 0 && *old_fanout == 0) { /* Invoke change_note_fanout() in "counting mode". */ b->num_notes = change_note_fanout(&b->branch_tree, 0xff); *old_fanout = convert_num_notes_to_fanout(b->num_notes); } /* Now parse the notemodify command. */ /* <dataref> or 'inline' */ if (*p == ':') { oe = find_mark(parse_mark_ref_space(&p)); hashcpy(sha1, oe->idx.sha1); } else if (skip_prefix(p, "inline ", &p)) { inline_data = 1; oe = NULL; /* not used with inline_data, but makes gcc happy */ } else { if (get_sha1_hex(p, sha1)) die("Invalid dataref: %s", command_buf.buf); oe = find_object(sha1); p += 40; if (*p++ != ' ') die("Missing space after SHA1: %s", command_buf.buf); } /* <commit-ish> */ s = lookup_branch(p); if (s) { if (is_null_sha1(s->sha1)) die("Can't add a note on empty branch."); hashcpy(commit_sha1, s->sha1); } else if (*p == ':') { uintmax_t commit_mark = parse_mark_ref_eol(p); struct object_entry *commit_oe = find_mark(commit_mark); if (commit_oe->type != OBJ_COMMIT) die("Mark :%" PRIuMAX " not a commit", commit_mark); hashcpy(commit_sha1, commit_oe->idx.sha1); } else if (!get_sha1(p, commit_sha1)) { unsigned long size; char *buf = read_object_with_reference(commit_sha1, commit_type, &size, commit_sha1); if (!buf || size < 46) die("Not a valid commit: %s", p); free(buf); } else die("Invalid ref name or SHA1 expression: %s", p); if (inline_data) { if (p != uq.buf) { strbuf_addstr(&uq, p); p = uq.buf; } read_next_command(); parse_and_store_blob(&last_blob, sha1, 0); } else if (oe) { if (oe->type != OBJ_BLOB) die("Not a blob (actually a %s): %s", typename(oe->type), command_buf.buf); } else if (!is_null_sha1(sha1)) { enum object_type type = sha1_object_info(sha1, NULL); if (type < 0) die("Blob not found: %s", command_buf.buf); if (type != OBJ_BLOB) die("Not a blob (actually a %s): %s", typename(type), command_buf.buf); } construct_path_with_fanout(sha1_to_hex(commit_sha1), *old_fanout, path); if (tree_content_remove(&b->branch_tree, path, NULL, 0)) b->num_notes--; if (is_null_sha1(sha1)) return; /* nothing to insert */ b->num_notes++; new_fanout = convert_num_notes_to_fanout(b->num_notes); construct_path_with_fanout(sha1_to_hex(commit_sha1), new_fanout, path); tree_content_set(&b->branch_tree, path, sha1, S_IFREG | 0644, NULL); } static void file_change_deleteall(struct branch *b) { release_tree_content_recursive(b->branch_tree.tree); hashclr(b->branch_tree.versions[0].sha1); hashclr(b->branch_tree.versions[1].sha1); load_tree(&b->branch_tree); b->num_notes = 0; } static void parse_from_commit(struct branch *b, char *buf, unsigned long size) { if (!buf || size < 46) die("Not a valid commit: %s", sha1_to_hex(b->sha1)); if (memcmp("tree ", buf, 5) || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1)) die("The commit %s is corrupt", sha1_to_hex(b->sha1)); hashcpy(b->branch_tree.versions[0].sha1, b->branch_tree.versions[1].sha1); } static void parse_from_existing(struct branch *b) { if (is_null_sha1(b->sha1)) { hashclr(b->branch_tree.versions[0].sha1); hashclr(b->branch_tree.versions[1].sha1); } else { unsigned long size; char *buf; buf = read_object_with_reference(b->sha1, commit_type, &size, b->sha1); parse_from_commit(b, buf, size); free(buf); } } static int parse_from(struct branch *b) { const char *from; struct branch *s; unsigned char sha1[20]; if (!skip_prefix(command_buf.buf, "from ", &from)) return 0; hashcpy(sha1, b->branch_tree.versions[1].sha1); s = lookup_branch(from); if (b == s) die("Can't create a branch from itself: %s", b->name); else if (s) { unsigned char *t = s->branch_tree.versions[1].sha1; hashcpy(b->sha1, s->sha1); hashcpy(b->branch_tree.versions[0].sha1, t); hashcpy(b->branch_tree.versions[1].sha1, t); } else if (*from == ':') { uintmax_t idnum = parse_mark_ref_eol(from); struct object_entry *oe = find_mark(idnum); if (oe->type != OBJ_COMMIT) die("Mark :%" PRIuMAX " not a commit", idnum); if (hashcmp(b->sha1, oe->idx.sha1)) { hashcpy(b->sha1, oe->idx.sha1); if (oe->pack_id != MAX_PACK_ID) { unsigned long size; char *buf = gfi_unpack_entry(oe, &size); parse_from_commit(b, buf, size); free(buf); } else parse_from_existing(b); } } else if (!get_sha1(from, b->sha1)) { parse_from_existing(b); if (is_null_sha1(b->sha1)) b->delete = 1; } else die("Invalid ref name or SHA1 expression: %s", from); if (b->branch_tree.tree && hashcmp(sha1, b->branch_tree.versions[1].sha1)) { release_tree_content_recursive(b->branch_tree.tree); b->branch_tree.tree = NULL; } read_next_command(); return 1; } static struct hash_list *parse_merge(unsigned int *count) { struct hash_list *list = NULL, **tail = &list, *n; const char *from; struct branch *s; *count = 0; while (skip_prefix(command_buf.buf, "merge ", &from)) { n = xmalloc(sizeof(*n)); s = lookup_branch(from); if (s) hashcpy(n->sha1, s->sha1); else if (*from == ':') { uintmax_t idnum = parse_mark_ref_eol(from); struct object_entry *oe = find_mark(idnum); if (oe->type != OBJ_COMMIT) die("Mark :%" PRIuMAX " not a commit", idnum); hashcpy(n->sha1, oe->idx.sha1); } else if (!get_sha1(from, n->sha1)) { unsigned long size; char *buf = read_object_with_reference(n->sha1, commit_type, &size, n->sha1); if (!buf || size < 46) die("Not a valid commit: %s", from); free(buf); } else die("Invalid ref name or SHA1 expression: %s", from); n->next = NULL; *tail = n; tail = &n->next; (*count)++; read_next_command(); } return list; } static void parse_new_commit(const char *arg) { static struct strbuf msg = STRBUF_INIT; struct branch *b; char *author = NULL; char *committer = NULL; struct hash_list *merge_list = NULL; unsigned int merge_count; unsigned char prev_fanout, new_fanout; const char *v; b = lookup_branch(arg); if (!b) b = new_branch(arg); read_next_command(); parse_mark(); if (skip_prefix(command_buf.buf, "author ", &v)) { author = parse_ident(v); read_next_command(); } if (skip_prefix(command_buf.buf, "committer ", &v)) { committer = parse_ident(v); read_next_command(); } if (!committer) die("Expected committer but didn't get one"); parse_data(&msg, 0, NULL); read_next_command(); parse_from(b); merge_list = parse_merge(&merge_count); /* ensure the branch is active/loaded */ if (!b->branch_tree.tree || !max_active_branches) { unload_one_branch(); load_branch(b); } prev_fanout = convert_num_notes_to_fanout(b->num_notes); /* file_change* */ while (command_buf.len > 0) { if (skip_prefix(command_buf.buf, "M ", &v)) file_change_m(v, b); else if (skip_prefix(command_buf.buf, "D ", &v)) file_change_d(v, b); else if (skip_prefix(command_buf.buf, "R ", &v)) file_change_cr(v, b, 1); else if (skip_prefix(command_buf.buf, "C ", &v)) file_change_cr(v, b, 0); else if (skip_prefix(command_buf.buf, "N ", &v)) note_change_n(v, b, &prev_fanout); else if (!strcmp("deleteall", command_buf.buf)) file_change_deleteall(b); else if (skip_prefix(command_buf.buf, "ls ", &v)) parse_ls(v, b); else { unread_command_buf = 1; break; } if (read_next_command() == EOF) break; } new_fanout = convert_num_notes_to_fanout(b->num_notes); if (new_fanout != prev_fanout) b->num_notes = change_note_fanout(&b->branch_tree, new_fanout); /* build the tree and the commit */ store_tree(&b->branch_tree); hashcpy(b->branch_tree.versions[0].sha1, b->branch_tree.versions[1].sha1); strbuf_reset(&new_data); strbuf_addf(&new_data, "tree %s\n", sha1_to_hex(b->branch_tree.versions[1].sha1)); if (!is_null_sha1(b->sha1)) strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(b->sha1)); while (merge_list) { struct hash_list *next = merge_list->next; strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(merge_list->sha1)); free(merge_list); merge_list = next; } strbuf_addf(&new_data, "author %s\n" "committer %s\n" "\n", author ? author : committer, committer); strbuf_addbuf(&new_data, &msg); free(author); free(committer); if (!store_object(OBJ_COMMIT, &new_data, NULL, b->sha1, next_mark)) b->pack_id = pack_id; b->last_commit = object_count_by_type[OBJ_COMMIT]; } static void parse_new_tag(const char *arg) { static struct strbuf msg = STRBUF_INIT; const char *from; char *tagger; struct branch *s; struct tag *t; uintmax_t from_mark = 0; unsigned char sha1[20]; enum object_type type; const char *v; t = pool_alloc(sizeof(struct tag)); memset(t, 0, sizeof(struct tag)); t->name = pool_strdup(arg); if (last_tag) last_tag->next_tag = t; else first_tag = t; last_tag = t; read_next_command(); /* from ... */ if (!skip_prefix(command_buf.buf, "from ", &from)) die("Expected from command, got %s", command_buf.buf); s = lookup_branch(from); if (s) { if (is_null_sha1(s->sha1)) die("Can't tag an empty branch."); hashcpy(sha1, s->sha1); type = OBJ_COMMIT; } else if (*from == ':') { struct object_entry *oe; from_mark = parse_mark_ref_eol(from); oe = find_mark(from_mark); type = oe->type; hashcpy(sha1, oe->idx.sha1); } else if (!get_sha1(from, sha1)) { struct object_entry *oe = find_object(sha1); if (!oe) { type = sha1_object_info(sha1, NULL); if (type < 0) die("Not a valid object: %s", from); } else type = oe->type; } else die("Invalid ref name or SHA1 expression: %s", from); read_next_command(); /* tagger ... */ if (skip_prefix(command_buf.buf, "tagger ", &v)) { tagger = parse_ident(v); read_next_command(); } else tagger = NULL; /* tag payload/message */ parse_data(&msg, 0, NULL); /* build the tag object */ strbuf_reset(&new_data); strbuf_addf(&new_data, "object %s\n" "type %s\n" "tag %s\n", sha1_to_hex(sha1), typename(type), t->name); if (tagger) strbuf_addf(&new_data, "tagger %s\n", tagger); strbuf_addch(&new_data, '\n'); strbuf_addbuf(&new_data, &msg); free(tagger); if (store_object(OBJ_TAG, &new_data, NULL, t->sha1, 0)) t->pack_id = MAX_PACK_ID; else t->pack_id = pack_id; } static void parse_reset_branch(const char *arg) { struct branch *b; b = lookup_branch(arg); if (b) { hashclr(b->sha1); hashclr(b->branch_tree.versions[0].sha1); hashclr(b->branch_tree.versions[1].sha1); if (b->branch_tree.tree) { release_tree_content_recursive(b->branch_tree.tree); b->branch_tree.tree = NULL; } } else b = new_branch(arg); read_next_command(); parse_from(b); if (command_buf.len > 0) unread_command_buf = 1; } static void cat_blob_write(const char *buf, unsigned long size) { if (write_in_full(cat_blob_fd, buf, size) != size) die_errno("Write to frontend failed"); } static void cat_blob(struct object_entry *oe, unsigned char sha1[20]) { struct strbuf line = STRBUF_INIT; unsigned long size; enum object_type type = 0; char *buf; if (!oe || oe->pack_id == MAX_PACK_ID) { buf = read_sha1_file(sha1, &type, &size); } else { type = oe->type; buf = gfi_unpack_entry(oe, &size); } /* * Output based on batch_one_object() from cat-file.c. */ if (type <= 0) { strbuf_reset(&line); strbuf_addf(&line, "%s missing\n", sha1_to_hex(sha1)); cat_blob_write(line.buf, line.len); strbuf_release(&line); free(buf); return; } if (!buf) die("Can't read object %s", sha1_to_hex(sha1)); if (type != OBJ_BLOB) die("Object %s is a %s but a blob was expected.", sha1_to_hex(sha1), typename(type)); strbuf_reset(&line); strbuf_addf(&line, "%s %s %lu\n", sha1_to_hex(sha1), typename(type), size); cat_blob_write(line.buf, line.len); strbuf_release(&line); cat_blob_write(buf, size); cat_blob_write("\n", 1); if (oe && oe->pack_id == pack_id) { last_blob.offset = oe->idx.offset; strbuf_attach(&last_blob.data, buf, size, size); last_blob.depth = oe->depth; } else free(buf); } static void parse_get_mark(const char *p) { struct object_entry *oe = oe; char output[42]; /* get-mark SP <object> LF */ if (*p != ':') die("Not a mark: %s", p); oe = find_mark(parse_mark_ref_eol(p)); if (!oe) die("Unknown mark: %s", command_buf.buf); snprintf(output, sizeof(output), "%s\n", sha1_to_hex(oe->idx.sha1)); cat_blob_write(output, 41); } static void parse_cat_blob(const char *p) { struct object_entry *oe = oe; unsigned char sha1[20]; /* cat-blob SP <object> LF */ if (*p == ':') { oe = find_mark(parse_mark_ref_eol(p)); if (!oe) die("Unknown mark: %s", command_buf.buf); hashcpy(sha1, oe->idx.sha1); } else { if (get_sha1_hex(p, sha1)) die("Invalid dataref: %s", command_buf.buf); if (p[40]) die("Garbage after SHA1: %s", command_buf.buf); oe = find_object(sha1); } cat_blob(oe, sha1); } static struct object_entry *dereference(struct object_entry *oe, unsigned char sha1[20]) { unsigned long size; char *buf = NULL; if (!oe) { enum object_type type = sha1_object_info(sha1, NULL); if (type < 0) die("object not found: %s", sha1_to_hex(sha1)); /* cache it! */ oe = insert_object(sha1); oe->type = type; oe->pack_id = MAX_PACK_ID; oe->idx.offset = 1; } switch (oe->type) { case OBJ_TREE: /* easy case. */ return oe; case OBJ_COMMIT: case OBJ_TAG: break; default: die("Not a tree-ish: %s", command_buf.buf); } if (oe->pack_id != MAX_PACK_ID) { /* in a pack being written */ buf = gfi_unpack_entry(oe, &size); } else { enum object_type unused; buf = read_sha1_file(sha1, &unused, &size); } if (!buf) die("Can't load object %s", sha1_to_hex(sha1)); /* Peel one layer. */ switch (oe->type) { case OBJ_TAG: if (size < 40 + strlen("object ") || get_sha1_hex(buf + strlen("object "), sha1)) die("Invalid SHA1 in tag: %s", command_buf.buf); break; case OBJ_COMMIT: if (size < 40 + strlen("tree ") || get_sha1_hex(buf + strlen("tree "), sha1)) die("Invalid SHA1 in commit: %s", command_buf.buf); } free(buf); return find_object(sha1); } static struct object_entry *parse_treeish_dataref(const char **p) { unsigned char sha1[20]; struct object_entry *e; if (**p == ':') { /* <mark> */ e = find_mark(parse_mark_ref_space(p)); if (!e) die("Unknown mark: %s", command_buf.buf); hashcpy(sha1, e->idx.sha1); } else { /* <sha1> */ if (get_sha1_hex(*p, sha1)) die("Invalid dataref: %s", command_buf.buf); e = find_object(sha1); *p += 40; if (*(*p)++ != ' ') die("Missing space after tree-ish: %s", command_buf.buf); } while (!e || e->type != OBJ_TREE) e = dereference(e, sha1); return e; } static void print_ls(int mode, const unsigned char *sha1, const char *path) { static struct strbuf line = STRBUF_INIT; /* See show_tree(). */ const char *type = S_ISGITLINK(mode) ? commit_type : S_ISDIR(mode) ? tree_type : blob_type; if (!mode) { /* missing SP path LF */ strbuf_reset(&line); strbuf_addstr(&line, "missing "); quote_c_style(path, &line, NULL, 0); strbuf_addch(&line, '\n'); } else { /* mode SP type SP object_name TAB path LF */ strbuf_reset(&line); strbuf_addf(&line, "%06o %s %s\t", mode & ~NO_DELTA, type, sha1_to_hex(sha1)); quote_c_style(path, &line, NULL, 0); strbuf_addch(&line, '\n'); } cat_blob_write(line.buf, line.len); } static void parse_ls(const char *p, struct branch *b) { struct tree_entry *root = NULL; struct tree_entry leaf = {NULL}; /* ls SP (<tree-ish> SP)? <path> */ if (*p == '"') { if (!b) die("Not in a commit: %s", command_buf.buf); root = &b->branch_tree; } else { struct object_entry *e = parse_treeish_dataref(&p); root = new_tree_entry(); hashcpy(root->versions[1].sha1, e->idx.sha1); if (!is_null_sha1(root->versions[1].sha1)) root->versions[1].mode = S_IFDIR; load_tree(root); } if (*p == '"') { static struct strbuf uq = STRBUF_INIT; const char *endp; strbuf_reset(&uq); if (unquote_c_style(&uq, p, &endp)) die("Invalid path: %s", command_buf.buf); if (*endp) die("Garbage after path in: %s", command_buf.buf); p = uq.buf; } tree_content_get(root, p, &leaf, 1); /* * A directory in preparation would have a sha1 of zero * until it is saved. Save, for simplicity. */ if (S_ISDIR(leaf.versions[1].mode)) store_tree(&leaf); print_ls(leaf.versions[1].mode, leaf.versions[1].sha1, p); if (leaf.tree) release_tree_content_recursive(leaf.tree); if (!b || root != &b->branch_tree) release_tree_entry(root); } static void checkpoint(void) { checkpoint_requested = 0; if (object_count) { cycle_packfile(); dump_branches(); dump_tags(); dump_marks(); } } static void parse_checkpoint(void) { checkpoint_requested = 1; skip_optional_lf(); } static void parse_progress(void) { fwrite(command_buf.buf, 1, command_buf.len, stdout); fputc('\n', stdout); fflush(stdout); skip_optional_lf(); } static char* make_fast_import_path(const char *path) { if (!relative_marks_paths || is_absolute_path(path)) return xstrdup(path); return xstrdup(git_path("info/fast-import/%s", path)); } static void option_import_marks(const char *marks, int from_stream, int ignore_missing) { if (import_marks_file) { if (from_stream) die("Only one import-marks command allowed per stream"); /* read previous mark file */ if(!import_marks_file_from_stream) read_marks(); } import_marks_file = make_fast_import_path(marks); safe_create_leading_directories_const(import_marks_file); import_marks_file_from_stream = from_stream; import_marks_file_ignore_missing = ignore_missing; } static void option_date_format(const char *fmt) { if (!strcmp(fmt, "raw")) whenspec = WHENSPEC_RAW; else if (!strcmp(fmt, "rfc2822")) whenspec = WHENSPEC_RFC2822; else if (!strcmp(fmt, "now")) whenspec = WHENSPEC_NOW; else die("unknown --date-format argument %s", fmt); } static unsigned long ulong_arg(const char *option, const char *arg) { char *endptr; unsigned long rv = strtoul(arg, &endptr, 0); if (strchr(arg, '-') || endptr == arg || *endptr) die("%s: argument must be a non-negative integer", option); return rv; } static void option_depth(const char *depth) { max_depth = ulong_arg("--depth", depth); if (max_depth > MAX_DEPTH) die("--depth cannot exceed %u", MAX_DEPTH); } static void option_active_branches(const char *branches) { max_active_branches = ulong_arg("--active-branches", branches); } static void option_export_marks(const char *marks) { export_marks_file = make_fast_import_path(marks); safe_create_leading_directories_const(export_marks_file); } static void option_cat_blob_fd(const char *fd) { unsigned long n = ulong_arg("--cat-blob-fd", fd); if (n > (unsigned long) INT_MAX) die("--cat-blob-fd cannot exceed %d", INT_MAX); cat_blob_fd = (int) n; } static void option_export_pack_edges(const char *edges) { if (pack_edges) fclose(pack_edges); pack_edges = fopen(edges, "a"); if (!pack_edges) die_errno("Cannot open '%s'", edges); } static int parse_one_option(const char *option) { if (skip_prefix(option, "max-pack-size=", &option)) { unsigned long v; if (!git_parse_ulong(option, &v)) return 0; if (v < 8192) { warning("max-pack-size is now in bytes, assuming --max-pack-size=%lum", v); v *= 1024 * 1024; } else if (v < 1024 * 1024) { warning("minimum max-pack-size is 1 MiB"); v = 1024 * 1024; } max_packsize = v; } else if (skip_prefix(option, "big-file-threshold=", &option)) { unsigned long v; if (!git_parse_ulong(option, &v)) return 0; big_file_threshold = v; } else if (skip_prefix(option, "depth=", &option)) { option_depth(option); } else if (skip_prefix(option, "active-branches=", &option)) { option_active_branches(option); } else if (skip_prefix(option, "export-pack-edges=", &option)) { option_export_pack_edges(option); } else if (starts_with(option, "quiet")) { show_stats = 0; } else if (starts_with(option, "stats")) { show_stats = 1; } else { return 0; } return 1; } static int parse_one_feature(const char *feature, int from_stream) { const char *arg; if (skip_prefix(feature, "date-format=", &arg)) { option_date_format(arg); } else if (skip_prefix(feature, "import-marks=", &arg)) { option_import_marks(arg, from_stream, 0); } else if (skip_prefix(feature, "import-marks-if-exists=", &arg)) { option_import_marks(arg, from_stream, 1); } else if (skip_prefix(feature, "export-marks=", &arg)) { option_export_marks(arg); } else if (!strcmp(feature, "get-mark")) { ; /* Don't die - this feature is supported */ } else if (!strcmp(feature, "cat-blob")) { ; /* Don't die - this feature is supported */ } else if (!strcmp(feature, "relative-marks")) { relative_marks_paths = 1; } else if (!strcmp(feature, "no-relative-marks")) { relative_marks_paths = 0; } else if (!strcmp(feature, "done")) { require_explicit_termination = 1; } else if (!strcmp(feature, "force")) { force_update = 1; } else if (!strcmp(feature, "notes") || !strcmp(feature, "ls")) { ; /* do nothing; we have the feature */ } else { return 0; } return 1; } static void parse_feature(const char *feature) { if (seen_data_command) die("Got feature command '%s' after data command", feature); if (parse_one_feature(feature, 1)) return; die("This version of fast-import does not support feature %s.", feature); } static void parse_option(const char *option) { if (seen_data_command) die("Got option command '%s' after data command", option); if (parse_one_option(option)) return; die("This version of fast-import does not support option: %s", option); } static void git_pack_config(void) { int indexversion_value; unsigned long packsizelimit_value; if (!git_config_get_ulong("pack.depth", &max_depth)) { if (max_depth > MAX_DEPTH) max_depth = MAX_DEPTH; } if (!git_config_get_int("pack.compression", &pack_compression_level)) { if (pack_compression_level == -1) pack_compression_level = Z_DEFAULT_COMPRESSION; else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION) git_die_config("pack.compression", "bad pack compression level %d", pack_compression_level); pack_compression_seen = 1; } if (!git_config_get_int("pack.indexversion", &indexversion_value)) { pack_idx_opts.version = indexversion_value; if (pack_idx_opts.version > 2) git_die_config("pack.indexversion", "bad pack.indexversion=%"PRIu32, pack_idx_opts.version); } if (!git_config_get_ulong("pack.packsizelimit", &packsizelimit_value)) max_packsize = packsizelimit_value; git_config(git_default_config, NULL); } static const char fast_import_usage[] = "git fast-import [--date-format=<f>] [--max-pack-size=<n>] [--big-file-threshold=<n>] [--depth=<n>] [--active-branches=<n>] [--export-marks=<marks.file>]"; static void parse_argv(void) { unsigned int i; for (i = 1; i < global_argc; i++) { const char *a = global_argv[i]; if (*a != '-' || !strcmp(a, "--")) break; if (!skip_prefix(a, "--", &a)) die("unknown option %s", a); if (parse_one_option(a)) continue; if (parse_one_feature(a, 0)) continue; if (skip_prefix(a, "cat-blob-fd=", &a)) { option_cat_blob_fd(a); continue; } die("unknown option --%s", a); } if (i != global_argc) usage(fast_import_usage); seen_data_command = 1; if (import_marks_file) read_marks(); } int main(int argc, char **argv) { unsigned int i; git_extract_argv0_path(argv[0]); git_setup_gettext(); if (argc == 2 && !strcmp(argv[1], "-h")) usage(fast_import_usage); setup_git_directory(); reset_pack_idx_option(&pack_idx_opts); git_pack_config(); if (!pack_compression_seen && core_compression_seen) pack_compression_level = core_compression_level; alloc_objects(object_entry_alloc); strbuf_init(&command_buf, 0); atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*)); branch_table = xcalloc(branch_table_sz, sizeof(struct branch*)); avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*)); marks = pool_calloc(1, sizeof(struct mark_set)); global_argc = argc; global_argv = argv; rc_free = pool_alloc(cmd_save * sizeof(*rc_free)); for (i = 0; i < (cmd_save - 1); i++) rc_free[i].next = &rc_free[i + 1]; rc_free[cmd_save - 1].next = NULL; prepare_packed_git(); start_packfile(); set_die_routine(die_nicely); set_checkpoint_signal(); while (read_next_command() != EOF) { const char *v; if (!strcmp("blob", command_buf.buf)) parse_new_blob(); else if (skip_prefix(command_buf.buf, "ls ", &v)) parse_ls(v, NULL); else if (skip_prefix(command_buf.buf, "commit ", &v)) parse_new_commit(v); else if (skip_prefix(command_buf.buf, "tag ", &v)) parse_new_tag(v); else if (skip_prefix(command_buf.buf, "reset ", &v)) parse_reset_branch(v); else if (!strcmp("checkpoint", command_buf.buf)) parse_checkpoint(); else if (!strcmp("done", command_buf.buf)) break; else if (starts_with(command_buf.buf, "progress ")) parse_progress(); else if (skip_prefix(command_buf.buf, "feature ", &v)) parse_feature(v); else if (skip_prefix(command_buf.buf, "option git ", &v)) parse_option(v); else if (starts_with(command_buf.buf, "option ")) /* ignore non-git options*/; else die("Unsupported command: %s", command_buf.buf); if (checkpoint_requested) checkpoint(); } /* argv hasn't been parsed yet, do so */ if (!seen_data_command) parse_argv(); if (require_explicit_termination && feof(stdin)) die("stream ends early"); end_packfile(); dump_branches(); dump_tags(); unkeep_all_packs(); dump_marks(); if (pack_edges) fclose(pack_edges); if (show_stats) { uintmax_t total_count = 0, duplicate_count = 0; for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++) total_count += object_count_by_type[i]; for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++) duplicate_count += duplicate_count_by_type[i]; fprintf(stderr, "%s statistics:\n", argv[0]); fprintf(stderr, "---------------------------------------------------------------------\n"); fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count); fprintf(stderr, "Total objects: %10" PRIuMAX " (%10" PRIuMAX " duplicates )\n", total_count, duplicate_count); fprintf(stderr, " blobs : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB], delta_count_attempts_by_type[OBJ_BLOB]); fprintf(stderr, " trees : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE], delta_count_attempts_by_type[OBJ_TREE]); fprintf(stderr, " commits: %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT], delta_count_attempts_by_type[OBJ_COMMIT]); fprintf(stderr, " tags : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG], delta_count_attempts_by_type[OBJ_TAG]); fprintf(stderr, "Total branches: %10lu (%10lu loads )\n", branch_count, branch_load_count); fprintf(stderr, " marks: %10" PRIuMAX " (%10" PRIuMAX " unique )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count); fprintf(stderr, " atoms: %10u\n", atom_cnt); fprintf(stderr, "Memory total: %10" PRIuMAX " KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024); fprintf(stderr, " pools: %10lu KiB\n", (unsigned long)(total_allocd/1024)); fprintf(stderr, " objects: %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024); fprintf(stderr, "---------------------------------------------------------------------\n"); pack_report(); fprintf(stderr, "---------------------------------------------------------------------\n"); fprintf(stderr, "\n"); } return failure ? 1 : 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_4945_1
crossvul-cpp_data_bad_1358_0
/** * @file resolve.c * @author Michal Vasko <mvasko@cesnet.cz> * @brief libyang resolve functions * * Copyright (c) 2015 - 2018 CESNET, z.s.p.o. * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */ #define _GNU_SOURCE #include <stdlib.h> #include <assert.h> #include <string.h> #include <ctype.h> #include <limits.h> #include "libyang.h" #include "resolve.h" #include "common.h" #include "xpath.h" #include "parser.h" #include "parser_yang.h" #include "xml_internal.h" #include "hash_table.h" #include "tree_internal.h" #include "extensions.h" #include "validation.h" /* internal parsed predicate structure */ struct parsed_pred { const struct lys_node *schema; int len; struct { const char *mod_name; int mod_name_len; const char *name; int nam_len; const char *value; int val_len; } *pred; }; int parse_range_dec64(const char **str_num, uint8_t dig, int64_t *num) { const char *ptr; int minus = 0; int64_t ret = 0, prev_ret; int8_t str_exp, str_dig = -1, trailing_zeros = 0; ptr = *str_num; if (ptr[0] == '-') { minus = 1; ++ptr; } else if (ptr[0] == '+') { ++ptr; } if (!isdigit(ptr[0])) { /* there must be at least one */ return 1; } for (str_exp = 0; isdigit(ptr[0]) || ((ptr[0] == '.') && (str_dig < 0)); ++ptr) { if (str_exp > 18) { return 1; } if (ptr[0] == '.') { if (ptr[1] == '.') { /* it's the next interval */ break; } ++str_dig; } else { prev_ret = ret; if (minus) { ret = ret * 10 - (ptr[0] - '0'); if (ret > prev_ret) { return 1; } } else { ret = ret * 10 + (ptr[0] - '0'); if (ret < prev_ret) { return 1; } } if (str_dig > -1) { ++str_dig; if (ptr[0] == '0') { /* possibly trailing zero */ trailing_zeros++; } else { trailing_zeros = 0; } } ++str_exp; } } if (str_dig == 0) { /* no digits after '.' */ return 1; } else if (str_dig == -1) { /* there are 0 numbers after the floating point */ str_dig = 0; } /* remove trailing zeros */ if (trailing_zeros) { str_dig -= trailing_zeros; str_exp -= trailing_zeros; ret = ret / dec_pow(trailing_zeros); } /* it's parsed, now adjust the number based on fraction-digits, if needed */ if (str_dig < dig) { if ((str_exp - 1) + (dig - str_dig) > 18) { return 1; } prev_ret = ret; ret *= dec_pow(dig - str_dig); if ((minus && (ret > prev_ret)) || (!minus && (ret < prev_ret))) { return 1; } } if (str_dig > dig) { return 1; } *str_num = ptr; *num = ret; return 0; } /** * @brief Parse an identifier. * * ;; An identifier MUST NOT start with (('X'|'x') ('M'|'m') ('L'|'l')) * identifier = (ALPHA / "_") * *(ALPHA / DIGIT / "_" / "-" / ".") * * @param[in] id Identifier to use. * * @return Number of characters successfully parsed. */ unsigned int parse_identifier(const char *id) { unsigned int parsed = 0; assert(id); if (!isalpha(id[0]) && (id[0] != '_')) { return -parsed; } ++parsed; ++id; while (isalnum(id[0]) || (id[0] == '_') || (id[0] == '-') || (id[0] == '.')) { ++parsed; ++id; } return parsed; } /** * @brief Parse a node-identifier. * * node-identifier = [module-name ":"] identifier * * @param[in] id Identifier to use. * @param[out] mod_name Points to the module name, NULL if there is not any. * @param[out] mod_name_len Length of the module name, 0 if there is not any. * @param[out] name Points to the node name. * @param[out] nam_len Length of the node name. * @param[out] all_desc Whether the path starts with '/', only supported in extended paths. * @param[in] extended Whether to accept an extended path (support for [prefix:]*, /[prefix:]*, /[prefix:]., prefix:#identifier). * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int parse_node_identifier(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len, int *all_desc, int extended) { int parsed = 0, ret, all_desc_local = 0, first_id_len; const char *first_id; assert(id); assert((mod_name && mod_name_len) || (!mod_name && !mod_name_len)); assert((name && nam_len) || (!name && !nam_len)); if (mod_name) { *mod_name = NULL; *mod_name_len = 0; } if (name) { *name = NULL; *nam_len = 0; } if (extended) { /* try to parse only the extended expressions */ if (id[parsed] == '/') { if (all_desc) { *all_desc = 1; } all_desc_local = 1; } else { if (all_desc) { *all_desc = 0; } } /* is there a prefix? */ ret = parse_identifier(id + all_desc_local); if (ret > 0) { if (id[all_desc_local + ret] != ':') { /* this is not a prefix, so not an extended id */ goto standard_id; } if (mod_name) { *mod_name = id + all_desc_local; *mod_name_len = ret; } /* "/" and ":" */ ret += all_desc_local + 1; } else { ret = all_desc_local; } /* parse either "*" or "." */ if (*(id + ret) == '*') { if (name) { *name = id + ret; *nam_len = 1; } ++ret; return ret; } else if (*(id + ret) == '.') { if (!all_desc_local) { /* /. is redundant expression, we do not accept it */ return -ret; } if (name) { *name = id + ret; *nam_len = 1; } ++ret; return ret; } else if (*(id + ret) == '#') { if (all_desc_local || !ret) { /* no prefix */ return 0; } parsed = ret + 1; if ((ret = parse_identifier(id + parsed)) < 1) { return -parsed + ret; } *name = id + parsed - 1; *nam_len = ret + 1; return parsed + ret; } /* else a standard id, parse it all again */ } standard_id: if ((ret = parse_identifier(id)) < 1) { return ret; } first_id = id; first_id_len = ret; parsed += ret; id += ret; /* there is prefix */ if (id[0] == ':') { ++parsed; ++id; /* there isn't */ } else { if (name) { *name = first_id; *nam_len = first_id_len; } return parsed; } /* identifier (node name) */ if ((ret = parse_identifier(id)) < 1) { return -parsed + ret; } if (mod_name) { *mod_name = first_id; *mod_name_len = first_id_len; } if (name) { *name = id; *nam_len = ret; } return parsed + ret; } /** * @brief Parse a path-predicate (leafref). * * path-predicate = "[" *WSP path-equality-expr *WSP "]" * path-equality-expr = node-identifier *WSP "=" *WSP path-key-expr * * @param[in] id Identifier to use. * @param[out] prefix Points to the prefix, NULL if there is not any. * @param[out] pref_len Length of the prefix, 0 if there is not any. * @param[out] name Points to the node name. * @param[out] nam_len Length of the node name. * @param[out] path_key_expr Points to the path-key-expr. * @param[out] pke_len Length of the path-key-expr. * @param[out] has_predicate Flag to mark whether there is another predicate following. * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int parse_path_predicate(const char *id, const char **prefix, int *pref_len, const char **name, int *nam_len, const char **path_key_expr, int *pke_len, int *has_predicate) { const char *ptr; int parsed = 0, ret; assert(id); if (prefix) { *prefix = NULL; } if (pref_len) { *pref_len = 0; } if (name) { *name = NULL; } if (nam_len) { *nam_len = 0; } if (path_key_expr) { *path_key_expr = NULL; } if (pke_len) { *pke_len = 0; } if (has_predicate) { *has_predicate = 0; } if (id[0] != '[') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } if ((ret = parse_node_identifier(id, prefix, pref_len, name, nam_len, NULL, 0)) < 1) { return -parsed+ret; } parsed += ret; id += ret; while (isspace(id[0])) { ++parsed; ++id; } if (id[0] != '=') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } if ((ptr = strchr(id, ']')) == NULL) { return -parsed; } --ptr; while (isspace(ptr[0])) { --ptr; } ++ptr; ret = ptr-id; if (path_key_expr) { *path_key_expr = id; } if (pke_len) { *pke_len = ret; } parsed += ret; id += ret; while (isspace(id[0])) { ++parsed; ++id; } assert(id[0] == ']'); if (id[1] == '[') { *has_predicate = 1; } return parsed+1; } /** * @brief Parse a path-key-expr (leafref). First call parses "current()", all * the ".." and the first node-identifier, other calls parse a single * node-identifier each. * * path-key-expr = current-function-invocation *WSP "/" *WSP * rel-path-keyexpr * rel-path-keyexpr = 1*(".." *WSP "/" *WSP) * *(node-identifier *WSP "/" *WSP) * node-identifier * * @param[in] id Identifier to use. * @param[out] prefix Points to the prefix, NULL if there is not any. * @param[out] pref_len Length of the prefix, 0 if there is not any. * @param[out] name Points to the node name. * @param[out] nam_len Length of the node name. * @param[out] parent_times Number of ".." in the path. Must be 0 on the first call, * must not be changed between consecutive calls. * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int parse_path_key_expr(const char *id, const char **prefix, int *pref_len, const char **name, int *nam_len, int *parent_times) { int parsed = 0, ret, par_times = 0; assert(id); assert(parent_times); if (prefix) { *prefix = NULL; } if (pref_len) { *pref_len = 0; } if (name) { *name = NULL; } if (nam_len) { *nam_len = 0; } if (!*parent_times) { /* current-function-invocation *WSP "/" *WSP rel-path-keyexpr */ if (strncmp(id, "current()", 9)) { return -parsed; } parsed += 9; id += 9; while (isspace(id[0])) { ++parsed; ++id; } if (id[0] != '/') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } /* rel-path-keyexpr */ if (strncmp(id, "..", 2)) { return -parsed; } ++par_times; parsed += 2; id += 2; while (isspace(id[0])) { ++parsed; ++id; } } /* 1*(".." *WSP "/" *WSP) *(node-identifier *WSP "/" *WSP) node-identifier * * first parent reference with whitespaces already parsed */ if (id[0] != '/') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } while (!strncmp(id, "..", 2) && !*parent_times) { ++par_times; parsed += 2; id += 2; while (isspace(id[0])) { ++parsed; ++id; } if (id[0] != '/') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } } if (!*parent_times) { *parent_times = par_times; } /* all parent references must be parsed at this point */ if ((ret = parse_node_identifier(id, prefix, pref_len, name, nam_len, NULL, 0)) < 1) { return -parsed + ret; } parsed += ret; id += ret; return parsed; } /** * @brief Parse path-arg (leafref). * * path-arg = absolute-path / relative-path * absolute-path = 1*("/" (node-identifier *path-predicate)) * relative-path = 1*(".." "/") descendant-path * * @param[in] mod Module of the context node to get correct prefix in case it is not explicitly specified * @param[in] id Identifier to use. * @param[out] prefix Points to the prefix, NULL if there is not any. * @param[out] pref_len Length of the prefix, 0 if there is not any. * @param[out] name Points to the node name. * @param[out] nam_len Length of the node name. * @param[out] parent_times Number of ".." in the path. Must be 0 on the first call, * must not be changed between consecutive calls. -1 if the * path is relative. * @param[out] has_predicate Flag to mark whether there is a predicate specified. * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int parse_path_arg(const struct lys_module *mod, const char *id, const char **prefix, int *pref_len, const char **name, int *nam_len, int *parent_times, int *has_predicate) { int parsed = 0, ret, par_times = 0; assert(id); assert(parent_times); if (prefix) { *prefix = NULL; } if (pref_len) { *pref_len = 0; } if (name) { *name = NULL; } if (nam_len) { *nam_len = 0; } if (has_predicate) { *has_predicate = 0; } if (!*parent_times && !strncmp(id, "..", 2)) { ++par_times; parsed += 2; id += 2; while (!strncmp(id, "/..", 3)) { ++par_times; parsed += 3; id += 3; } } if (!*parent_times) { if (par_times) { *parent_times = par_times; } else { *parent_times = -1; } } if (id[0] != '/') { return -parsed; } /* skip '/' */ ++parsed; ++id; /* node-identifier ([prefix:]identifier) */ if ((ret = parse_node_identifier(id, prefix, pref_len, name, nam_len, NULL, 0)) < 1) { return -parsed - ret; } if (prefix && !(*prefix)) { /* actually we always need prefix even it is not specified */ *prefix = lys_main_module(mod)->name; *pref_len = strlen(*prefix); } parsed += ret; id += ret; /* there is no predicate */ if ((id[0] == '/') || !id[0]) { return parsed; } else if (id[0] != '[') { return -parsed; } if (has_predicate) { *has_predicate = 1; } return parsed; } /** * @brief Parse instance-identifier in JSON data format. That means that prefixes * are actually model names. * * instance-identifier = 1*("/" (node-identifier *predicate)) * * @param[in] id Identifier to use. * @param[out] model Points to the model name. * @param[out] mod_len Length of the model name. * @param[out] name Points to the node name. * @param[out] nam_len Length of the node name. * @param[out] has_predicate Flag to mark whether there is a predicate specified. * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int parse_instance_identifier(const char *id, const char **model, int *mod_len, const char **name, int *nam_len, int *has_predicate) { int parsed = 0, ret; assert(id && model && mod_len && name && nam_len); if (has_predicate) { *has_predicate = 0; } if (id[0] != '/') { return -parsed; } ++parsed; ++id; if ((ret = parse_identifier(id)) < 1) { return ret; } *name = id; *nam_len = ret; parsed += ret; id += ret; if (id[0] == ':') { /* we have prefix */ *model = *name; *mod_len = *nam_len; ++parsed; ++id; if ((ret = parse_identifier(id)) < 1) { return ret; } *name = id; *nam_len = ret; parsed += ret; id += ret; } if (id[0] == '[' && has_predicate) { *has_predicate = 1; } return parsed; } /** * @brief Parse predicate (instance-identifier) in JSON data format. That means that prefixes * (which are mandatory) are actually model names. * * predicate = "[" *WSP (predicate-expr / pos) *WSP "]" * predicate-expr = (node-identifier / ".") *WSP "=" *WSP * ((DQUOTE string DQUOTE) / * (SQUOTE string SQUOTE)) * pos = non-negative-integer-value * * @param[in] id Identifier to use. * @param[out] model Points to the model name. * @param[out] mod_len Length of the model name. * @param[out] name Points to the node name. Can be identifier (from node-identifier), "." or pos. * @param[out] nam_len Length of the node name. * @param[out] value Value the node-identifier must have (string from the grammar), * NULL if there is not any. * @param[out] val_len Length of the value, 0 if there is not any. * @param[out] has_predicate Flag to mark whether there is a predicate specified. * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int parse_predicate(const char *id, const char **model, int *mod_len, const char **name, int *nam_len, const char **value, int *val_len, int *has_predicate) { const char *ptr; int parsed = 0, ret; char quote; assert(id); if (model) { assert(mod_len); *model = NULL; *mod_len = 0; } if (name) { assert(nam_len); *name = NULL; *nam_len = 0; } if (value) { assert(val_len); *value = NULL; *val_len = 0; } if (has_predicate) { *has_predicate = 0; } if (id[0] != '[') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } /* pos */ if (isdigit(id[0])) { if (name) { *name = id; } if (id[0] == '0') { return -parsed; } while (isdigit(id[0])) { ++parsed; ++id; } if (nam_len) { *nam_len = id-(*name); } /* "." or node-identifier */ } else { if (id[0] == '.') { if (name) { *name = id; } if (nam_len) { *nam_len = 1; } ++parsed; ++id; } else { if ((ret = parse_node_identifier(id, model, mod_len, name, nam_len, NULL, 0)) < 1) { return -parsed + ret; } parsed += ret; id += ret; } while (isspace(id[0])) { ++parsed; ++id; } if (id[0] != '=') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } /* ((DQUOTE string DQUOTE) / (SQUOTE string SQUOTE)) */ if ((id[0] == '\"') || (id[0] == '\'')) { quote = id[0]; ++parsed; ++id; if ((ptr = strchr(id, quote)) == NULL) { return -parsed; } ret = ptr - id; if (value) { *value = id; } if (val_len) { *val_len = ret; } parsed += ret + 1; id += ret + 1; } else { return -parsed; } } while (isspace(id[0])) { ++parsed; ++id; } if (id[0] != ']') { return -parsed; } ++parsed; ++id; if ((id[0] == '[') && has_predicate) { *has_predicate = 1; } return parsed; } /** * @brief Parse schema-nodeid. * * schema-nodeid = absolute-schema-nodeid / * descendant-schema-nodeid * absolute-schema-nodeid = 1*("/" node-identifier) * descendant-schema-nodeid = ["." "/"] * node-identifier * absolute-schema-nodeid * * @param[in] id Identifier to use. * @param[out] mod_name Points to the module name, NULL if there is not any. * @param[out] mod_name_len Length of the module name, 0 if there is not any. * @param[out] name Points to the node name. * @param[out] nam_len Length of the node name. * @param[out] is_relative Flag to mark whether the nodeid is absolute or descendant. Must be -1 * on the first call, must not be changed between consecutive calls. * @param[out] has_predicate Flag to mark whether there is a predicate specified. It cannot be * based on the grammar, in those cases use NULL. * @param[in] extended Whether to accept an extended path (support for /[prefix:]*, //[prefix:]*, //[prefix:].). * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ int parse_schema_nodeid(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len, int *is_relative, int *has_predicate, int *all_desc, int extended) { int parsed = 0, ret; assert(id); assert(is_relative); if (has_predicate) { *has_predicate = 0; } if (id[0] != '/') { if (*is_relative != -1) { return -parsed; } else { *is_relative = 1; } if (!strncmp(id, "./", 2)) { parsed += 2; id += 2; } } else { if (*is_relative == -1) { *is_relative = 0; } ++parsed; ++id; } if ((ret = parse_node_identifier(id, mod_name, mod_name_len, name, nam_len, all_desc, extended)) < 1) { return -parsed + ret; } parsed += ret; id += ret; if ((id[0] == '[') && has_predicate) { *has_predicate = 1; } return parsed; } /** * @brief Parse schema predicate (special format internally used). * * predicate = "[" *WSP predicate-expr *WSP "]" * predicate-expr = "." / [prefix:]identifier / positive-integer / key-with-value * key-with-value = identifier *WSP "=" *WSP * ((DQUOTE string DQUOTE) / * (SQUOTE string SQUOTE)) * * @param[in] id Identifier to use. * @param[out] mod_name Points to the list key module name. * @param[out] mod_name_len Length of \p mod_name. * @param[out] name Points to the list key name. * @param[out] nam_len Length of \p name. * @param[out] value Points to the key value. If specified, key-with-value is expected. * @param[out] val_len Length of \p value. * @param[out] has_predicate Flag to mark whether there is another predicate specified. */ int parse_schema_json_predicate(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len, const char **value, int *val_len, int *has_predicate) { const char *ptr; int parsed = 0, ret; char quote; assert(id); if (mod_name) { *mod_name = NULL; } if (mod_name_len) { *mod_name_len = 0; } if (name) { *name = NULL; } if (nam_len) { *nam_len = 0; } if (value) { *value = NULL; } if (val_len) { *val_len = 0; } if (has_predicate) { *has_predicate = 0; } if (id[0] != '[') { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } /* identifier */ if (id[0] == '.') { ret = 1; if (name) { *name = id; } if (nam_len) { *nam_len = ret; } } else if (isdigit(id[0])) { if (id[0] == '0') { return -parsed; } ret = 1; while (isdigit(id[ret])) { ++ret; } if (name) { *name = id; } if (nam_len) { *nam_len = ret; } } else if ((ret = parse_node_identifier(id, mod_name, mod_name_len, name, nam_len, NULL, 0)) < 1) { return -parsed + ret; } parsed += ret; id += ret; while (isspace(id[0])) { ++parsed; ++id; } /* there is value as well */ if (id[0] == '=') { if (name && isdigit(**name)) { return -parsed; } ++parsed; ++id; while (isspace(id[0])) { ++parsed; ++id; } /* ((DQUOTE string DQUOTE) / (SQUOTE string SQUOTE)) */ if ((id[0] == '\"') || (id[0] == '\'')) { quote = id[0]; ++parsed; ++id; if ((ptr = strchr(id, quote)) == NULL) { return -parsed; } ret = ptr - id; if (value) { *value = id; } if (val_len) { *val_len = ret; } parsed += ret + 1; id += ret + 1; } else { return -parsed; } while (isspace(id[0])) { ++parsed; ++id; } } if (id[0] != ']') { return -parsed; } ++parsed; ++id; if ((id[0] == '[') && has_predicate) { *has_predicate = 1; } return parsed; } #ifdef LY_ENABLED_CACHE static int resolve_hash_table_find_equal(void *val1_p, void *val2_p, int mod, void *UNUSED(cb_data)) { struct lyd_node *val2, *elem2; struct parsed_pred pp; const char *str; int i; assert(!mod); (void)mod; pp = *((struct parsed_pred *)val1_p); val2 = *((struct lyd_node **)val2_p); if (val2->schema != pp.schema) { return 0; } switch (val2->schema->nodetype) { case LYS_CONTAINER: case LYS_LEAF: case LYS_ANYXML: case LYS_ANYDATA: return 1; case LYS_LEAFLIST: str = ((struct lyd_node_leaf_list *)val2)->value_str; if (!strncmp(str, pp.pred[0].value, pp.pred[0].val_len) && !str[pp.pred[0].val_len]) { return 1; } return 0; case LYS_LIST: assert(((struct lys_node_list *)val2->schema)->keys_size); assert(((struct lys_node_list *)val2->schema)->keys_size == pp.len); /* lists with keys, their equivalence is based on their keys */ elem2 = val2->child; /* the exact data order is guaranteed */ for (i = 0; elem2 && (i < pp.len); ++i) { /* module check */ if (pp.pred[i].mod_name) { if (strncmp(lyd_node_module(elem2)->name, pp.pred[i].mod_name, pp.pred[i].mod_name_len) || lyd_node_module(elem2)->name[pp.pred[i].mod_name_len]) { break; } } else { if (lyd_node_module(elem2) != lys_node_module(pp.schema)) { break; } } /* name check */ if (strncmp(elem2->schema->name, pp.pred[i].name, pp.pred[i].nam_len) || elem2->schema->name[pp.pred[i].nam_len]) { break; } /* value check */ str = ((struct lyd_node_leaf_list *)elem2)->value_str; if (strncmp(str, pp.pred[i].value, pp.pred[i].val_len) || str[pp.pred[i].val_len]) { break; } /* next key */ elem2 = elem2->next; } if (i == pp.len) { return 1; } return 0; default: break; } LOGINT(val2->schema->module->ctx); return 0; } static struct lyd_node * resolve_json_data_node_hash(struct lyd_node *parent, struct parsed_pred pp) { values_equal_cb prev_cb; struct lyd_node **ret = NULL; uint32_t hash; int i; assert(parent && parent->hash); /* set our value equivalence callback that does not require data nodes */ prev_cb = lyht_set_cb(parent->ht, resolve_hash_table_find_equal); /* get the hash of the searched node */ hash = dict_hash_multi(0, lys_node_module(pp.schema)->name, strlen(lys_node_module(pp.schema)->name)); hash = dict_hash_multi(hash, pp.schema->name, strlen(pp.schema->name)); if (pp.schema->nodetype == LYS_LEAFLIST) { assert((pp.len == 1) && (pp.pred[0].name[0] == '.') && (pp.pred[0].nam_len == 1)); /* leaf-list value in predicate */ hash = dict_hash_multi(hash, pp.pred[0].value, pp.pred[0].val_len); } else if (pp.schema->nodetype == LYS_LIST) { /* list keys in predicates */ for (i = 0; i < pp.len; ++i) { hash = dict_hash_multi(hash, pp.pred[i].value, pp.pred[i].val_len); } } hash = dict_hash_multi(hash, NULL, 0); /* try to find the node */ i = lyht_find(parent->ht, &pp, hash, (void **)&ret); assert(i || *ret); /* restore the original callback */ lyht_set_cb(parent->ht, prev_cb); return (i ? NULL : *ret); } #endif /** * @brief Resolve (find) a feature definition. Logs directly. * * @param[in] feat_name Feature name to resolve. * @param[in] len Length of \p feat_name. * @param[in] node Node with the if-feature expression. * @param[out] feature Pointer to be set to point to the feature definition, if feature not found * (return code 1), the pointer is untouched. * * @return 0 on success, 1 on forward reference, -1 on error. */ static int resolve_feature(const char *feat_name, uint16_t len, const struct lys_node *node, struct lys_feature **feature) { char *str; const char *mod_name, *name; int mod_name_len, nam_len, i, j; const struct lys_module *module; assert(feature); /* check prefix */ if ((i = parse_node_identifier(feat_name, &mod_name, &mod_name_len, &name, &nam_len, NULL, 0)) < 1) { LOGVAL(node->module->ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, feat_name[-i], &feat_name[-i]); return -1; } module = lyp_get_module(lys_node_module(node), NULL, 0, mod_name, mod_name_len, 0); if (!module) { /* identity refers unknown data model */ LOGVAL(node->module->ctx, LYE_INMOD_LEN, LY_VLOG_NONE, NULL, mod_name_len, mod_name); return -1; } if (module != node->module && module == lys_node_module(node)) { /* first, try to search directly in submodule where the feature was mentioned */ for (j = 0; j < node->module->features_size; j++) { if (!strncmp(name, node->module->features[j].name, nam_len) && !node->module->features[j].name[nam_len]) { /* check status */ if (lyp_check_status(node->flags, lys_node_module(node), node->name, node->module->features[j].flags, node->module->features[j].module, node->module->features[j].name, NULL)) { return -1; } *feature = &node->module->features[j]; return 0; } } } /* search in the identified module ... */ for (j = 0; j < module->features_size; j++) { if (!strncmp(name, module->features[j].name, nam_len) && !module->features[j].name[nam_len]) { /* check status */ if (lyp_check_status(node->flags, lys_node_module(node), node->name, module->features[j].flags, module->features[j].module, module->features[j].name, NULL)) { return -1; } *feature = &module->features[j]; return 0; } } /* ... and all its submodules */ for (i = 0; i < module->inc_size && module->inc[i].submodule; i++) { for (j = 0; j < module->inc[i].submodule->features_size; j++) { if (!strncmp(name, module->inc[i].submodule->features[j].name, nam_len) && !module->inc[i].submodule->features[j].name[nam_len]) { /* check status */ if (lyp_check_status(node->flags, lys_node_module(node), node->name, module->inc[i].submodule->features[j].flags, module->inc[i].submodule->features[j].module, module->inc[i].submodule->features[j].name, NULL)) { return -1; } *feature = &module->inc[i].submodule->features[j]; return 0; } } } /* not found */ str = strndup(feat_name, len); LOGVAL(node->module->ctx, LYE_INRESOLV, LY_VLOG_NONE, NULL, "feature", str); free(str); return 1; } /* * @return * - 1 if enabled * - 0 if disabled */ static int resolve_feature_value(const struct lys_feature *feat) { int i; for (i = 0; i < feat->iffeature_size; i++) { if (!resolve_iffeature(&feat->iffeature[i])) { return 0; } } return feat->flags & LYS_FENABLED ? 1 : 0; } static int resolve_iffeature_recursive(struct lys_iffeature *expr, int *index_e, int *index_f) { uint8_t op; int a, b; op = iff_getop(expr->expr, *index_e); (*index_e)++; switch (op) { case LYS_IFF_F: /* resolve feature */ return resolve_feature_value(expr->features[(*index_f)++]); case LYS_IFF_NOT: /* invert result */ return resolve_iffeature_recursive(expr, index_e, index_f) ? 0 : 1; case LYS_IFF_AND: case LYS_IFF_OR: a = resolve_iffeature_recursive(expr, index_e, index_f); b = resolve_iffeature_recursive(expr, index_e, index_f); if (op == LYS_IFF_AND) { return a && b; } else { /* LYS_IFF_OR */ return a || b; } } return 0; } int resolve_iffeature(struct lys_iffeature *expr) { int index_e = 0, index_f = 0; if (expr->expr) { return resolve_iffeature_recursive(expr, &index_e, &index_f); } return 0; } struct iff_stack { int size; int index; /* first empty item */ uint8_t *stack; }; static int iff_stack_push(struct iff_stack *stack, uint8_t value) { if (stack->index == stack->size) { stack->size += 4; stack->stack = ly_realloc(stack->stack, stack->size * sizeof *stack->stack); LY_CHECK_ERR_RETURN(!stack->stack, LOGMEM(NULL); stack->size = 0, EXIT_FAILURE); } stack->stack[stack->index++] = value; return EXIT_SUCCESS; } static uint8_t iff_stack_pop(struct iff_stack *stack) { stack->index--; return stack->stack[stack->index]; } static void iff_stack_clean(struct iff_stack *stack) { stack->size = 0; free(stack->stack); } static void iff_setop(uint8_t *list, uint8_t op, int pos) { uint8_t *item; uint8_t mask = 3; assert(pos >= 0); assert(op <= 3); /* max 2 bits */ item = &list[pos / 4]; mask = mask << 2 * (pos % 4); *item = (*item) & ~mask; *item = (*item) | (op << 2 * (pos % 4)); } uint8_t iff_getop(uint8_t *list, int pos) { uint8_t *item; uint8_t mask = 3, result; assert(pos >= 0); item = &list[pos / 4]; result = (*item) & (mask << 2 * (pos % 4)); return result >> 2 * (pos % 4); } #define LYS_IFF_LP 0x04 /* ( */ #define LYS_IFF_RP 0x08 /* ) */ /* internal structure for passing data for UNRES_IFFEAT */ struct unres_iffeat_data { struct lys_node *node; const char *fname; int infeature; }; void resolve_iffeature_getsizes(struct lys_iffeature *iffeat, unsigned int *expr_size, unsigned int *feat_size) { unsigned int e = 0, f = 0, r = 0; uint8_t op; assert(iffeat); if (!iffeat->expr) { goto result; } do { op = iff_getop(iffeat->expr, e++); switch (op) { case LYS_IFF_NOT: if (!r) { r += 1; } break; case LYS_IFF_AND: case LYS_IFF_OR: if (!r) { r += 2; } else { r += 1; } break; case LYS_IFF_F: f++; if (r) { r--; } break; } } while(r); result: if (expr_size) { *expr_size = e; } if (feat_size) { *feat_size = f; } } int resolve_iffeature_compile(struct lys_iffeature *iffeat_expr, const char *value, struct lys_node *node, int infeature, struct unres_schema *unres) { const char *c = value; int r, rc = EXIT_FAILURE; int i, j, last_not, checkversion = 0; unsigned int f_size = 0, expr_size = 0, f_exp = 1; uint8_t op; struct iff_stack stack = {0, 0, NULL}; struct unres_iffeat_data *iff_data; struct ly_ctx *ctx = node->module->ctx; assert(c); if (isspace(c[0])) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, c[0], c); return EXIT_FAILURE; } /* pre-parse the expression to get sizes for arrays, also do some syntax checks of the expression */ for (i = j = last_not = 0; c[i]; i++) { if (c[i] == '(') { checkversion = 1; j++; continue; } else if (c[i] == ')') { j--; continue; } else if (isspace(c[i])) { continue; } if (!strncmp(&c[i], "not", r = 3) || !strncmp(&c[i], "and", r = 3) || !strncmp(&c[i], "or", r = 2)) { if (c[i + r] == '\0') { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature"); return EXIT_FAILURE; } else if (!isspace(c[i + r])) { /* feature name starting with the not/and/or */ last_not = 0; f_size++; } else if (c[i] == 'n') { /* not operation */ if (last_not) { /* double not */ expr_size = expr_size - 2; last_not = 0; } else { last_not = 1; } } else { /* and, or */ f_exp++; /* not a not operation */ last_not = 0; } i += r; } else { f_size++; last_not = 0; } expr_size++; while (!isspace(c[i])) { if (c[i] == '(') { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature"); return EXIT_FAILURE; } else if (!c[i] || c[i] == ')') { i--; break; } i++; } } if (j || f_exp != f_size) { /* not matching count of ( and ) */ LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature"); return EXIT_FAILURE; } if (checkversion || expr_size > 1) { /* check that we have 1.1 module */ if (node->module->version != LYS_VERSION_1_1) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "YANG 1.1 if-feature expression found in 1.0 module."); return EXIT_FAILURE; } } /* allocate the memory */ iffeat_expr->expr = calloc((j = (expr_size / 4) + ((expr_size % 4) ? 1 : 0)), sizeof *iffeat_expr->expr); iffeat_expr->features = calloc(f_size, sizeof *iffeat_expr->features); stack.stack = malloc(expr_size * sizeof *stack.stack); LY_CHECK_ERR_GOTO(!stack.stack || !iffeat_expr->expr || !iffeat_expr->features, LOGMEM(ctx), error); stack.size = expr_size; f_size--; expr_size--; /* used as indexes from now */ for (i--; i >= 0; i--) { if (c[i] == ')') { /* push it on stack */ iff_stack_push(&stack, LYS_IFF_RP); continue; } else if (c[i] == '(') { /* pop from the stack into result all operators until ) */ while((op = iff_stack_pop(&stack)) != LYS_IFF_RP) { iff_setop(iffeat_expr->expr, op, expr_size--); } continue; } else if (isspace(c[i])) { continue; } /* end operator or operand -> find beginning and get what is it */ j = i + 1; while (i >= 0 && !isspace(c[i]) && c[i] != '(') { i--; } i++; /* get back by one step */ if (!strncmp(&c[i], "not", 3) && isspace(c[i + 3])) { if (stack.index && stack.stack[stack.index - 1] == LYS_IFF_NOT) { /* double not */ iff_stack_pop(&stack); } else { /* not has the highest priority, so do not pop from the stack * as in case of AND and OR */ iff_stack_push(&stack, LYS_IFF_NOT); } } else if (!strncmp(&c[i], "and", 3) && isspace(c[i + 3])) { /* as for OR - pop from the stack all operators with the same or higher * priority and store them to the result, then push the AND to the stack */ while (stack.index && stack.stack[stack.index - 1] <= LYS_IFF_AND) { op = iff_stack_pop(&stack); iff_setop(iffeat_expr->expr, op, expr_size--); } iff_stack_push(&stack, LYS_IFF_AND); } else if (!strncmp(&c[i], "or", 2) && isspace(c[i + 2])) { while (stack.index && stack.stack[stack.index - 1] <= LYS_IFF_OR) { op = iff_stack_pop(&stack); iff_setop(iffeat_expr->expr, op, expr_size--); } iff_stack_push(&stack, LYS_IFF_OR); } else { /* feature name, length is j - i */ /* add it to the result */ iff_setop(iffeat_expr->expr, LYS_IFF_F, expr_size--); /* now get the link to the feature definition. Since it can be * forward referenced, we have to keep the feature name in auxiliary * structure passed into unres */ iff_data = malloc(sizeof *iff_data); LY_CHECK_ERR_GOTO(!iff_data, LOGMEM(ctx), error); iff_data->node = node; iff_data->fname = lydict_insert(node->module->ctx, &c[i], j - i); iff_data->infeature = infeature; r = unres_schema_add_node(node->module, unres, &iffeat_expr->features[f_size], UNRES_IFFEAT, (struct lys_node *)iff_data); f_size--; if (r == -1) { lydict_remove(node->module->ctx, iff_data->fname); free(iff_data); goto error; } } } while (stack.index) { op = iff_stack_pop(&stack); iff_setop(iffeat_expr->expr, op, expr_size--); } if (++expr_size || ++f_size) { /* not all expected operators and operands found */ LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature"); rc = EXIT_FAILURE; } else { rc = EXIT_SUCCESS; } error: /* cleanup */ iff_stack_clean(&stack); return rc; } /** * @brief Resolve (find) a data node based on a schema-nodeid. * * Used for resolving unique statements - so id is expected to be relative and local (without reference to a different * module). * */ struct lyd_node * resolve_data_descendant_schema_nodeid(const char *nodeid, struct lyd_node *start) { char *str, *token, *p; struct lyd_node *result = NULL, *iter; const struct lys_node *schema = NULL; assert(nodeid && start); if (nodeid[0] == '/') { return NULL; } str = p = strdup(nodeid); LY_CHECK_ERR_RETURN(!str, LOGMEM(start->schema->module->ctx), NULL); while (p) { token = p; p = strchr(p, '/'); if (p) { *p = '\0'; p++; } if (p) { /* inner node */ if (resolve_descendant_schema_nodeid(token, schema ? schema->child : start->schema, LYS_CONTAINER | LYS_CHOICE | LYS_CASE | LYS_LEAF, 0, &schema) || !schema) { result = NULL; break; } if (schema->nodetype & (LYS_CHOICE | LYS_CASE)) { continue; } } else { /* final node */ if (resolve_descendant_schema_nodeid(token, schema ? schema->child : start->schema, LYS_LEAF, 0, &schema) || !schema) { result = NULL; break; } } LY_TREE_FOR(result ? result->child : start, iter) { if (iter->schema == schema) { /* move in data tree according to returned schema */ result = iter; break; } } if (!iter) { /* instance not found */ result = NULL; break; } } free(str); return result; } int schema_nodeid_siblingcheck(const struct lys_node *sibling, const struct lys_module *cur_module, const char *mod_name, int mod_name_len, const char *name, int nam_len) { const struct lys_module *prefix_mod; /* handle special names */ if (name[0] == '*') { return 2; } else if (name[0] == '.') { return 3; } /* name check */ if (strncmp(name, sibling->name, nam_len) || sibling->name[nam_len]) { return 1; } /* module check */ if (mod_name) { prefix_mod = lyp_get_module(cur_module, NULL, 0, mod_name, mod_name_len, 0); if (!prefix_mod) { return -1; } } else { prefix_mod = cur_module; } if (prefix_mod != lys_node_module(sibling)) { return 1; } /* match */ return 0; } /* keys do not have to be ordered and do not have to be all of them */ static int resolve_extended_schema_nodeid_predicate(const char *nodeid, const struct lys_node *node, const struct lys_module *cur_module, int *nodeid_end) { int mod_len, nam_len, has_predicate, r, i; const char *model, *name; struct lys_node_list *list; if (!(node->nodetype & (LYS_LIST | LYS_LEAFLIST))) { return 1; } list = (struct lys_node_list *)node; do { r = parse_schema_json_predicate(nodeid, &model, &mod_len, &name, &nam_len, NULL, NULL, &has_predicate); if (r < 1) { LOGVAL(cur_module->ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, nodeid[r], &nodeid[r]); return -1; } nodeid += r; if (node->nodetype == LYS_LEAFLIST) { /* just check syntax */ if (model || !name || (name[0] != '.') || has_predicate) { return 1; } break; } else { /* check the key */ for (i = 0; i < list->keys_size; ++i) { if (strncmp(list->keys[i]->name, name, nam_len) || list->keys[i]->name[nam_len]) { continue; } if (model) { if (strncmp(lys_node_module((struct lys_node *)list->keys[i])->name, model, mod_len) || lys_node_module((struct lys_node *)list->keys[i])->name[mod_len]) { continue; } } else { if (lys_node_module((struct lys_node *)list->keys[i]) != cur_module) { continue; } } /* match */ break; } if (i == list->keys_size) { return 1; } } } while (has_predicate); if (!nodeid[0]) { *nodeid_end = 1; } return 0; } /* start_parent - relative, module - absolute, -1 error (logged), EXIT_SUCCESS ok */ int resolve_schema_nodeid(const char *nodeid, const struct lys_node *start_parent, const struct lys_module *cur_module, struct ly_set **ret, int extended, int no_node_error) { const char *name, *mod_name, *id, *backup_mod_name = NULL, *yang_data_name = NULL; const struct lys_node *sibling, *next, *elem; struct lys_node_augment *last_aug; int r, nam_len, mod_name_len = 0, is_relative = -1, all_desc, has_predicate, nodeid_end = 0; int yang_data_name_len, backup_mod_name_len = 0; /* resolved import module from the start module, it must match the next node-name-match sibling */ const struct lys_module *start_mod, *aux_mod = NULL; char *str; struct ly_ctx *ctx; assert(nodeid && (start_parent || cur_module) && ret); *ret = NULL; if (!cur_module) { cur_module = lys_node_module(start_parent); } ctx = cur_module->ctx; id = nodeid; r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1); if (r < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[r], &id[r]); return -1; } if (name[0] == '#') { if (is_relative) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name); return -1; } yang_data_name = name + 1; yang_data_name_len = nam_len - 1; backup_mod_name = mod_name; backup_mod_name_len = mod_name_len; id += r; } else { is_relative = -1; } r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, (extended ? &all_desc : NULL), extended); if (r < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[r], &id[r]); return -1; } id += r; if (backup_mod_name) { mod_name = backup_mod_name; mod_name_len = backup_mod_name_len; } if (is_relative && !start_parent) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_STR, nodeid, "Starting node must be provided for relative paths."); return -1; } /* descendant-schema-nodeid */ if (is_relative) { cur_module = start_mod = lys_node_module(start_parent); /* absolute-schema-nodeid */ } else { start_mod = lyp_get_module(cur_module, NULL, 0, mod_name, mod_name_len, 0); if (!start_mod) { str = strndup(mod_name, mod_name_len); LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str); free(str); return -1; } start_parent = NULL; if (yang_data_name) { start_parent = lyp_get_yang_data_template(start_mod, yang_data_name, yang_data_name_len); if (!start_parent) { str = strndup(nodeid, (yang_data_name + yang_data_name_len) - nodeid); LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str); free(str); return -1; } } } while (1) { sibling = NULL; last_aug = NULL; if (start_parent) { if (mod_name && (strncmp(mod_name, cur_module->name, mod_name_len) || (mod_name_len != (signed)strlen(cur_module->name)))) { /* we are getting into another module (augment) */ aux_mod = lyp_get_module(cur_module, NULL, 0, mod_name, mod_name_len, 0); if (!aux_mod) { str = strndup(mod_name, mod_name_len); LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str); free(str); return -1; } } else { /* there is no mod_name, so why are we checking augments again? * because this module may be not implemented and it augments something in another module and * there is another augment augmenting that previous one */ aux_mod = cur_module; } /* look into augments */ if (!extended) { get_next_augment: last_aug = lys_getnext_target_aug(last_aug, aux_mod, start_parent); } } while ((sibling = lys_getnext(sibling, (last_aug ? (struct lys_node *)last_aug : start_parent), start_mod, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_WITHINOUT | LYS_GETNEXT_PARENTUSES | LYS_GETNEXT_NOSTATECHECK))) { r = schema_nodeid_siblingcheck(sibling, cur_module, mod_name, mod_name_len, name, nam_len); /* resolve predicate */ if (extended && ((r == 0) || (r == 2) || (r == 3)) && has_predicate) { r = resolve_extended_schema_nodeid_predicate(id, sibling, cur_module, &nodeid_end); if (r == 1) { continue; } else if (r == -1) { return -1; } } else if (!id[0]) { nodeid_end = 1; } if (r == 0) { /* one matching result */ if (nodeid_end) { *ret = ly_set_new(); LY_CHECK_ERR_RETURN(!*ret, LOGMEM(ctx), -1); ly_set_add(*ret, (void *)sibling, LY_SET_OPT_USEASLIST); } else { if (sibling->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { return -1; } start_parent = sibling; } break; } else if (r == 1) { continue; } else if (r == 2) { /* "*" */ if (!*ret) { *ret = ly_set_new(); LY_CHECK_ERR_RETURN(!*ret, LOGMEM(ctx), -1); } ly_set_add(*ret, (void *)sibling, LY_SET_OPT_USEASLIST); if (all_desc) { LY_TREE_DFS_BEGIN(sibling, next, elem) { if (elem != sibling) { ly_set_add(*ret, (void *)elem, LY_SET_OPT_USEASLIST); } LY_TREE_DFS_END(sibling, next, elem); } } } else if (r == 3) { /* "." */ if (!*ret) { *ret = ly_set_new(); LY_CHECK_ERR_RETURN(!*ret, LOGMEM(ctx), -1); ly_set_add(*ret, (void *)start_parent, LY_SET_OPT_USEASLIST); } ly_set_add(*ret, (void *)sibling, LY_SET_OPT_USEASLIST); if (all_desc) { LY_TREE_DFS_BEGIN(sibling, next, elem) { if (elem != sibling) { ly_set_add(*ret, (void *)elem, LY_SET_OPT_USEASLIST); } LY_TREE_DFS_END(sibling, next, elem); } } } else { LOGINT(ctx); return -1; } } /* skip predicate */ if (extended && has_predicate) { while (id[0] == '[') { id = strchr(id, ']'); if (!id) { LOGINT(ctx); return -1; } ++id; } } if (nodeid_end && ((r == 0) || (r == 2) || (r == 3))) { return EXIT_SUCCESS; } /* no match */ if (!sibling) { if (last_aug) { /* it still could be in another augment */ goto get_next_augment; } if (no_node_error) { str = strndup(nodeid, (name - nodeid) + nam_len); LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str); free(str); return -1; } *ret = NULL; return EXIT_SUCCESS; } r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, (extended ? &all_desc : NULL), extended); if (r < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[r], &id[r]); return -1; } id += r; } /* cannot get here */ LOGINT(ctx); return -1; } /* unique, refine, * >0 - unexpected char on position (ret - 1), * 0 - ok (but ret can still be NULL), * -1 - error, * -2 - violated no_innerlist */ int resolve_descendant_schema_nodeid(const char *nodeid, const struct lys_node *start, int ret_nodetype, int no_innerlist, const struct lys_node **ret) { const char *name, *mod_name, *id; const struct lys_node *sibling, *start_parent; int r, nam_len, mod_name_len, is_relative = -1; /* resolved import module from the start module, it must match the next node-name-match sibling */ const struct lys_module *module; assert(nodeid && ret); assert(!(ret_nodetype & (LYS_USES | LYS_AUGMENT | LYS_GROUPING))); if (!start) { /* leaf not found */ return 0; } id = nodeid; module = lys_node_module(start); if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) { return ((id - nodeid) - r) + 1; } id += r; if (!is_relative) { return -1; } start_parent = lys_parent(start); while ((start_parent->nodetype == LYS_USES) && lys_parent(start_parent)) { start_parent = lys_parent(start_parent); } while (1) { sibling = NULL; while ((sibling = lys_getnext(sibling, start_parent, module, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_PARENTUSES | LYS_GETNEXT_NOSTATECHECK))) { r = schema_nodeid_siblingcheck(sibling, module, mod_name, mod_name_len, name, nam_len); if (r == 0) { if (!id[0]) { if (!(sibling->nodetype & ret_nodetype)) { /* wrong node type, too bad */ continue; } *ret = sibling; return EXIT_SUCCESS; } start_parent = sibling; break; } else if (r == 1) { continue; } else { return -1; } } /* no match */ if (!sibling) { *ret = NULL; return EXIT_SUCCESS; } else if (no_innerlist && sibling->nodetype == LYS_LIST) { *ret = NULL; return -2; } if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) { return ((id - nodeid) - r) + 1; } id += r; } /* cannot get here */ LOGINT(module->ctx); return -1; } /* choice default */ int resolve_choice_default_schema_nodeid(const char *nodeid, const struct lys_node *start, const struct lys_node **ret) { /* cannot actually be a path */ if (strchr(nodeid, '/')) { return -1; } return resolve_descendant_schema_nodeid(nodeid, start, LYS_NO_RPC_NOTIF_NODE, 0, ret); } /* uses, -1 error, EXIT_SUCCESS ok (but ret can still be NULL), >0 unexpected char on ret - 1 */ static int resolve_uses_schema_nodeid(const char *nodeid, const struct lys_node *start, const struct lys_node_grp **ret) { const struct lys_module *module; const char *mod_prefix, *name; int i, mod_prefix_len, nam_len; /* parse the identifier, it must be parsed on one call */ if (((i = parse_node_identifier(nodeid, &mod_prefix, &mod_prefix_len, &name, &nam_len, NULL, 0)) < 1) || nodeid[i]) { return -i + 1; } module = lyp_get_module(start->module, mod_prefix, mod_prefix_len, NULL, 0, 0); if (!module) { return -1; } if (module != lys_main_module(start->module)) { start = module->data; } *ret = lys_find_grouping_up(name, (struct lys_node *)start); return EXIT_SUCCESS; } int resolve_absolute_schema_nodeid(const char *nodeid, const struct lys_module *module, int ret_nodetype, const struct lys_node **ret) { const char *name, *mod_name, *id; const struct lys_node *sibling, *start_parent; int r, nam_len, mod_name_len, is_relative = -1; const struct lys_module *abs_start_mod; assert(nodeid && module && ret); assert(!(ret_nodetype & (LYS_USES | LYS_AUGMENT)) && ((ret_nodetype == LYS_GROUPING) || !(ret_nodetype & LYS_GROUPING))); id = nodeid; start_parent = NULL; if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) { return ((id - nodeid) - r) + 1; } id += r; if (is_relative) { return -1; } abs_start_mod = lyp_get_module(module, NULL, 0, mod_name, mod_name_len, 0); if (!abs_start_mod) { return -1; } while (1) { sibling = NULL; while ((sibling = lys_getnext(sibling, start_parent, abs_start_mod, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_WITHINOUT | LYS_GETNEXT_WITHGROUPING | LYS_GETNEXT_NOSTATECHECK))) { r = schema_nodeid_siblingcheck(sibling, module, mod_name, mod_name_len, name, nam_len); if (r == 0) { if (!id[0]) { if (!(sibling->nodetype & ret_nodetype)) { /* wrong node type, too bad */ continue; } *ret = sibling; return EXIT_SUCCESS; } start_parent = sibling; break; } else if (r == 1) { continue; } else { return -1; } } /* no match */ if (!sibling) { *ret = NULL; return EXIT_SUCCESS; } if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) { return ((id - nodeid) - r) + 1; } id += r; } /* cannot get here */ LOGINT(module->ctx); return -1; } static int resolve_json_schema_list_predicate(const char *predicate, const struct lys_node_list *list, int *parsed) { const char *mod_name, *name; int mod_name_len, nam_len, has_predicate, i; struct lys_node *key; if (((i = parse_schema_json_predicate(predicate, &mod_name, &mod_name_len, &name, &nam_len, NULL, NULL, &has_predicate)) < 1) || !strncmp(name, ".", nam_len)) { LOGVAL(list->module->ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, predicate[-i], &predicate[-i]); return -1; } predicate += i; *parsed += i; if (!isdigit(name[0])) { for (i = 0; i < list->keys_size; ++i) { key = (struct lys_node *)list->keys[i]; if (!strncmp(key->name, name, nam_len) && !key->name[nam_len]) { break; } } if (i == list->keys_size) { LOGVAL(list->module->ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, name); return -1; } } /* more predicates? */ if (has_predicate) { return resolve_json_schema_list_predicate(predicate, list, parsed); } return 0; } /* cannot return LYS_GROUPING, LYS_AUGMENT, LYS_USES, logs directly */ const struct lys_node * resolve_json_nodeid(const char *nodeid, struct ly_ctx *ctx, const struct lys_node *start, int output) { char *str; const char *name, *mod_name, *id, *backup_mod_name = NULL, *yang_data_name = NULL; const struct lys_node *sibling, *start_parent, *parent; int r, nam_len, mod_name_len, is_relative = -1, has_predicate; int yang_data_name_len, backup_mod_name_len; /* resolved import module from the start module, it must match the next node-name-match sibling */ const struct lys_module *prefix_mod, *module, *prev_mod; assert(nodeid && (ctx || start)); if (!ctx) { ctx = start->module->ctx; } id = nodeid; if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); return NULL; } if (name[0] == '#') { if (is_relative) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name); return NULL; } yang_data_name = name + 1; yang_data_name_len = nam_len - 1; backup_mod_name = mod_name; backup_mod_name_len = mod_name_len; id += r; } else { is_relative = -1; } if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); return NULL; } id += r; if (backup_mod_name) { mod_name = backup_mod_name; mod_name_len = backup_mod_name_len; } if (is_relative) { assert(start); start_parent = start; while (start_parent && (start_parent->nodetype == LYS_USES)) { start_parent = lys_parent(start_parent); } module = start->module; } else { if (!mod_name) { str = strndup(nodeid, (name + nam_len) - nodeid); LOGVAL(ctx, LYE_PATH_MISSMOD, LY_VLOG_STR, nodeid); free(str); return NULL; } str = strndup(mod_name, mod_name_len); module = ly_ctx_get_module(ctx, str, NULL, 1); free(str); if (!module) { str = strndup(nodeid, (mod_name + mod_name_len) - nodeid); LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str); free(str); return NULL; } start_parent = NULL; if (yang_data_name) { start_parent = lyp_get_yang_data_template(module, yang_data_name, yang_data_name_len); if (!start_parent) { str = strndup(nodeid, (yang_data_name + yang_data_name_len) - nodeid); LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str); free(str); return NULL; } } /* now it's as if there was no module name */ mod_name = NULL; mod_name_len = 0; } prev_mod = module; while (1) { sibling = NULL; while ((sibling = lys_getnext(sibling, start_parent, module, 0))) { /* name match */ if (sibling->name && !strncmp(name, sibling->name, nam_len) && !sibling->name[nam_len]) { /* output check */ for (parent = lys_parent(sibling); parent && !(parent->nodetype & (LYS_INPUT | LYS_OUTPUT)); parent = lys_parent(parent)); if (parent) { if (output && (parent->nodetype == LYS_INPUT)) { continue; } else if (!output && (parent->nodetype == LYS_OUTPUT)) { continue; } } /* module check */ if (mod_name) { /* will also find an augment module */ prefix_mod = ly_ctx_nget_module(ctx, mod_name, mod_name_len, NULL, 1); if (!prefix_mod) { str = strndup(nodeid, (mod_name + mod_name_len) - nodeid); LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str); free(str); return NULL; } } else { prefix_mod = prev_mod; } if (prefix_mod != lys_node_module(sibling)) { continue; } /* do we have some predicates on it? */ if (has_predicate) { r = 0; if (sibling->nodetype & (LYS_LEAF | LYS_LEAFLIST)) { if ((r = parse_schema_json_predicate(id, NULL, NULL, NULL, NULL, NULL, NULL, &has_predicate)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); return NULL; } } else if (sibling->nodetype == LYS_LIST) { if (resolve_json_schema_list_predicate(id, (const struct lys_node_list *)sibling, &r)) { return NULL; } } else { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id); return NULL; } id += r; } /* the result node? */ if (!id[0]) { return sibling; } /* move down the tree, if possible */ if (sibling->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id); return NULL; } start_parent = sibling; /* update prev mod */ prev_mod = (start_parent->child ? lys_node_module(start_parent->child) : module); break; } } /* no match */ if (!sibling) { str = strndup(nodeid, (name + nam_len) - nodeid); LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str); free(str); return NULL; } if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); return NULL; } id += r; } /* cannot get here */ LOGINT(ctx); return NULL; } static int resolve_partial_json_data_list_predicate(struct parsed_pred pp, struct lyd_node *node, int position) { uint16_t i; char *val_str; struct lyd_node_leaf_list *key; struct lys_node_list *slist; struct ly_ctx *ctx; assert(node); assert(node->schema->nodetype == LYS_LIST); assert(pp.len); ctx = node->schema->module->ctx; slist = (struct lys_node_list *)node->schema; /* is the predicate a number? */ if (isdigit(pp.pred[0].name[0])) { if (position == atoi(pp.pred[0].name)) { /* match */ return 0; } else { /* not a match */ return 1; } } key = (struct lyd_node_leaf_list *)node->child; if (!key) { /* it is not a position, so we need a key for it to be a match */ return 1; } /* go through all the keys */ for (i = 0; i < slist->keys_size; ++i) { if (strncmp(key->schema->name, pp.pred[i].name, pp.pred[i].nam_len) || key->schema->name[pp.pred[i].nam_len]) { LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name); return -1; } if (pp.pred[i].mod_name) { /* specific module, check that the found key is from that module */ if (strncmp(lyd_node_module((struct lyd_node *)key)->name, pp.pred[i].mod_name, pp.pred[i].mod_name_len) || lyd_node_module((struct lyd_node *)key)->name[pp.pred[i].mod_name_len]) { LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name); return -1; } /* but if the module is the same as the parent, it should have been omitted */ if (lyd_node_module((struct lyd_node *)key) == lyd_node_module(node)) { LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name); return -1; } } else { /* no module, so it must be the same as the list (parent) */ if (lyd_node_module((struct lyd_node *)key) != lyd_node_module(node)) { LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name); return -1; } } /* get canonical value */ val_str = lyd_make_canonical(key->schema, pp.pred[i].value, pp.pred[i].val_len); if (!val_str) { return -1; } /* value does not match */ if (strcmp(key->value_str, val_str)) { free(val_str); return 1; } free(val_str); key = (struct lyd_node_leaf_list *)key->next; } return 0; } /** * @brief get the closest parent of the node (or the node itself) identified by the nodeid (path) * * @param[in] nodeid Node data path to find * @param[in] llist_value If the \p nodeid identifies leaf-list, this is expected value of the leaf-list instance. * @param[in] options Bitmask of options flags, see @ref pathoptions. * @param[out] parsed Number of characters processed in \p id * @return The closes parent (or the node itself) from the path */ struct lyd_node * resolve_partial_json_data_nodeid(const char *nodeid, const char *llist_value, struct lyd_node *start, int options, int *parsed) { const char *id, *mod_name, *name, *data_val, *llval; int r, ret, mod_name_len, nam_len, is_relative = -1, list_instance_position; int has_predicate, last_parsed = 0, llval_len; struct lyd_node *sibling, *last_match = NULL; struct lyd_node_leaf_list *llist; const struct lys_module *prev_mod; struct ly_ctx *ctx; const struct lys_node *ssibling, *sparent; struct lys_node_list *slist; struct parsed_pred pp; assert(nodeid && start && parsed); memset(&pp, 0, sizeof pp); ctx = start->schema->module->ctx; id = nodeid; /* parse first nodeid in case it is yang-data extension */ if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); goto error; } if (name[0] == '#') { if (is_relative) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name); goto error; } id += r; last_parsed = r; } else { is_relative = -1; } /* parse first nodeid */ if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); goto error; } id += r; /* add it to parsed only after the data node was actually found */ last_parsed += r; if (is_relative) { prev_mod = lyd_node_module(start); start = (start->schema->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_RPC | LYS_ACTION | LYS_NOTIF)) ? start->child : NULL; } else { for (; start->parent; start = start->parent); prev_mod = lyd_node_module(start); } if (!start) { /* there are no siblings to search */ return NULL; } /* do not duplicate code, use predicate parsing from the loop */ goto parse_predicates; while (1) { /* find the correct schema node first */ ssibling = NULL; sparent = (start && start->parent) ? start->parent->schema : NULL; while ((ssibling = lys_getnext(ssibling, sparent, prev_mod, 0))) { /* skip invalid input/output nodes */ if (sparent && (sparent->nodetype & (LYS_RPC | LYS_ACTION))) { if (options & LYD_PATH_OPT_OUTPUT) { if (lys_parent(ssibling)->nodetype == LYS_INPUT) { continue; } } else { if (lys_parent(ssibling)->nodetype == LYS_OUTPUT) { continue; } } } if (!schema_nodeid_siblingcheck(ssibling, prev_mod, mod_name, mod_name_len, name, nam_len)) { break; } } if (!ssibling) { /* there is not even such a schema node */ free(pp.pred); return last_match; } pp.schema = ssibling; /* unify leaf-list value - it is possible to specify last-node value as both a predicate or parameter if * is a leaf-list, unify both cases and the value will in both cases be in the predicate structure */ if (!id[0] && !pp.len && (ssibling->nodetype == LYS_LEAFLIST)) { pp.len = 1; pp.pred = calloc(1, sizeof *pp.pred); LY_CHECK_ERR_GOTO(!pp.pred, LOGMEM(ctx), error); pp.pred[0].name = "."; pp.pred[0].nam_len = 1; pp.pred[0].value = (llist_value ? llist_value : ""); pp.pred[0].val_len = strlen(pp.pred[0].value); } if (ssibling->nodetype & (LYS_LEAFLIST | LYS_LEAF)) { /* check leaf/leaf-list predicate */ if (pp.len > 1) { LOGVAL(ctx, LYE_PATH_PREDTOOMANY, LY_VLOG_NONE, NULL); goto error; } else if (pp.len) { if ((pp.pred[0].name[0] != '.') || (pp.pred[0].nam_len != 1)) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, pp.pred[0].name[0], pp.pred[0].name); goto error; } if ((((struct lys_node_leaf *)ssibling)->type.base == LY_TYPE_IDENT) && !strnchr(pp.pred[0].value, ':', pp.pred[0].val_len)) { LOGVAL(ctx, LYE_PATH_INIDENTREF, LY_VLOG_LYS, ssibling, pp.pred[0].val_len, pp.pred[0].value); goto error; } } } else if (ssibling->nodetype == LYS_LIST) { /* list should have predicates for all the keys or position */ slist = (struct lys_node_list *)ssibling; if (!pp.len) { /* none match */ return last_match; } else if (!isdigit(pp.pred[0].name[0])) { /* list predicate is not a position, so there must be all the keys */ if (pp.len > slist->keys_size) { LOGVAL(ctx, LYE_PATH_PREDTOOMANY, LY_VLOG_NONE, NULL); goto error; } else if (pp.len < slist->keys_size) { LOGVAL(ctx, LYE_PATH_MISSKEY, LY_VLOG_NONE, NULL, slist->keys[pp.len]->name); goto error; } /* check that all identityrefs have module name, otherwise the hash of the list instance will never match!! */ for (r = 0; r < pp.len; ++r) { if ((slist->keys[r]->type.base == LY_TYPE_IDENT) && !strnchr(pp.pred[r].value, ':', pp.pred[r].val_len)) { LOGVAL(ctx, LYE_PATH_INIDENTREF, LY_VLOG_LYS, slist->keys[r], pp.pred[r].val_len, pp.pred[r].value); goto error; } } } } else if (pp.pred) { /* no other nodes allow predicates */ LOGVAL(ctx, LYE_PATH_PREDTOOMANY, LY_VLOG_NONE, NULL); goto error; } #ifdef LY_ENABLED_CACHE /* we will not be matching keyless lists or state leaf-lists this way */ if (start->parent && start->parent->ht && ((pp.schema->nodetype != LYS_LIST) || ((struct lys_node_list *)pp.schema)->keys_size) && ((pp.schema->nodetype != LYS_LEAFLIST) || (pp.schema->flags & LYS_CONFIG_W))) { sibling = resolve_json_data_node_hash(start->parent, pp); } else #endif { list_instance_position = 0; LY_TREE_FOR(start, sibling) { /* RPC/action data check, return simply invalid argument, because the data tree is invalid */ if (lys_parent(sibling->schema)) { if (options & LYD_PATH_OPT_OUTPUT) { if (lys_parent(sibling->schema)->nodetype == LYS_INPUT) { LOGERR(ctx, LY_EINVAL, "Provided data tree includes some RPC input nodes (%s).", sibling->schema->name); goto error; } } else { if (lys_parent(sibling->schema)->nodetype == LYS_OUTPUT) { LOGERR(ctx, LY_EINVAL, "Provided data tree includes some RPC output nodes (%s).", sibling->schema->name); goto error; } } } if (sibling->schema != ssibling) { /* wrong schema node */ continue; } /* leaf-list, did we find it with the correct value or not? */ if (ssibling->nodetype == LYS_LEAFLIST) { if (ssibling->flags & LYS_CONFIG_R) { /* state leaf-lists will never match */ continue; } llist = (struct lyd_node_leaf_list *)sibling; /* get the expected leaf-list value */ llval = NULL; llval_len = 0; if (pp.pred) { /* it was already checked that it is correct */ llval = pp.pred[0].value; llval_len = pp.pred[0].val_len; } /* make value canonical (remove module name prefix) unless it was specified with it */ if (llval && !strchr(llval, ':') && (llist->value_type & LY_TYPE_IDENT) && !strncmp(llist->value_str, lyd_node_module(sibling)->name, strlen(lyd_node_module(sibling)->name)) && (llist->value_str[strlen(lyd_node_module(sibling)->name)] == ':')) { data_val = llist->value_str + strlen(lyd_node_module(sibling)->name) + 1; } else { data_val = llist->value_str; } if ((!llval && data_val && data_val[0]) || (llval && (strncmp(llval, data_val, llval_len) || data_val[llval_len]))) { continue; } } else if (ssibling->nodetype == LYS_LIST) { /* list, we likely need predicates'n'stuff then, but if without a predicate, we are always creating it */ ++list_instance_position; ret = resolve_partial_json_data_list_predicate(pp, sibling, list_instance_position); if (ret == -1) { goto error; } else if (ret == 1) { /* this list instance does not match */ continue; } } break; } } /* no match, return last match */ if (!sibling) { free(pp.pred); return last_match; } /* we found a next matching node */ *parsed += last_parsed; last_match = sibling; prev_mod = lyd_node_module(sibling); /* the result node? */ if (!id[0]) { free(pp.pred); return last_match; } /* move down the tree, if possible, and continue */ if (ssibling->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { /* there can be no children even through expected, error */ LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id); goto error; } else if (!sibling->child) { /* there could be some children, but are not, return what we found so far */ free(pp.pred); return last_match; } start = sibling->child; /* parse nodeid */ if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]); goto error; } id += r; last_parsed = r; parse_predicates: /* parse all the predicates */ free(pp.pred); pp.schema = NULL; pp.len = 0; pp.pred = NULL; while (has_predicate) { ++pp.len; pp.pred = ly_realloc(pp.pred, pp.len * sizeof *pp.pred); LY_CHECK_ERR_GOTO(!pp.pred, LOGMEM(ctx), error); if ((r = parse_schema_json_predicate(id, &pp.pred[pp.len - 1].mod_name, &pp.pred[pp.len - 1].mod_name_len, &pp.pred[pp.len - 1].name, &pp.pred[pp.len - 1].nam_len, &pp.pred[pp.len - 1].value, &pp.pred[pp.len - 1].val_len, &has_predicate)) < 1) { LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id); goto error; } id += r; last_parsed += r; } } error: *parsed = -1; free(pp.pred); return NULL; } /** * @brief Resolves length or range intervals. Does not log. * Syntax is assumed to be correct, *ret MUST be NULL. * * @param[in] ctx Context for errors. * @param[in] str_restr Restriction as a string. * @param[in] type Type of the restriction. * @param[out] ret Final interval structure that starts with * the interval of the initial type, continues with intervals * of any superior types derived from the initial one, and * finishes with intervals from our \p type. * * @return EXIT_SUCCESS on succes, -1 on error. */ int resolve_len_ran_interval(struct ly_ctx *ctx, const char *str_restr, struct lys_type *type, struct len_ran_intv **ret) { /* 0 - unsigned, 1 - signed, 2 - floating point */ int kind; int64_t local_smin = 0, local_smax = 0, local_fmin, local_fmax; uint64_t local_umin, local_umax = 0; uint8_t local_fdig = 0; const char *seg_ptr, *ptr; struct len_ran_intv *local_intv = NULL, *tmp_local_intv = NULL, *tmp_intv, *intv = NULL; switch (type->base) { case LY_TYPE_BINARY: kind = 0; local_umin = 0; local_umax = 18446744073709551615UL; if (!str_restr && type->info.binary.length) { str_restr = type->info.binary.length->expr; } break; case LY_TYPE_DEC64: kind = 2; local_fmin = __INT64_C(-9223372036854775807) - __INT64_C(1); local_fmax = __INT64_C(9223372036854775807); local_fdig = type->info.dec64.dig; if (!str_restr && type->info.dec64.range) { str_restr = type->info.dec64.range->expr; } break; case LY_TYPE_INT8: kind = 1; local_smin = __INT64_C(-128); local_smax = __INT64_C(127); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_INT16: kind = 1; local_smin = __INT64_C(-32768); local_smax = __INT64_C(32767); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_INT32: kind = 1; local_smin = __INT64_C(-2147483648); local_smax = __INT64_C(2147483647); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_INT64: kind = 1; local_smin = __INT64_C(-9223372036854775807) - __INT64_C(1); local_smax = __INT64_C(9223372036854775807); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_UINT8: kind = 0; local_umin = __UINT64_C(0); local_umax = __UINT64_C(255); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_UINT16: kind = 0; local_umin = __UINT64_C(0); local_umax = __UINT64_C(65535); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_UINT32: kind = 0; local_umin = __UINT64_C(0); local_umax = __UINT64_C(4294967295); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_UINT64: kind = 0; local_umin = __UINT64_C(0); local_umax = __UINT64_C(18446744073709551615); if (!str_restr && type->info.num.range) { str_restr = type->info.num.range->expr; } break; case LY_TYPE_STRING: kind = 0; local_umin = __UINT64_C(0); local_umax = __UINT64_C(18446744073709551615); if (!str_restr && type->info.str.length) { str_restr = type->info.str.length->expr; } break; default: return -1; } /* process superior types */ if (type->der) { if (resolve_len_ran_interval(ctx, NULL, &type->der->type, &intv)) { return -1; } assert(!intv || (intv->kind == kind)); } if (!str_restr) { /* we do not have any restriction, return superior ones */ *ret = intv; return EXIT_SUCCESS; } /* adjust local min and max */ if (intv) { tmp_intv = intv; if (kind == 0) { local_umin = tmp_intv->value.uval.min; } else if (kind == 1) { local_smin = tmp_intv->value.sval.min; } else if (kind == 2) { local_fmin = tmp_intv->value.fval.min; } while (tmp_intv->next) { tmp_intv = tmp_intv->next; } if (kind == 0) { local_umax = tmp_intv->value.uval.max; } else if (kind == 1) { local_smax = tmp_intv->value.sval.max; } else if (kind == 2) { local_fmax = tmp_intv->value.fval.max; } } /* finally parse our restriction */ seg_ptr = str_restr; tmp_intv = NULL; while (1) { if (!tmp_local_intv) { assert(!local_intv); local_intv = malloc(sizeof *local_intv); tmp_local_intv = local_intv; } else { tmp_local_intv->next = malloc(sizeof *tmp_local_intv); tmp_local_intv = tmp_local_intv->next; } LY_CHECK_ERR_GOTO(!tmp_local_intv, LOGMEM(ctx), error); tmp_local_intv->kind = kind; tmp_local_intv->type = type; tmp_local_intv->next = NULL; /* min */ ptr = seg_ptr; while (isspace(ptr[0])) { ++ptr; } if (isdigit(ptr[0]) || (ptr[0] == '+') || (ptr[0] == '-')) { if (kind == 0) { tmp_local_intv->value.uval.min = strtoull(ptr, (char **)&ptr, 10); } else if (kind == 1) { tmp_local_intv->value.sval.min = strtoll(ptr, (char **)&ptr, 10); } else if (kind == 2) { if (parse_range_dec64(&ptr, local_fdig, &tmp_local_intv->value.fval.min)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, ptr, "range"); goto error; } } } else if (!strncmp(ptr, "min", 3)) { if (kind == 0) { tmp_local_intv->value.uval.min = local_umin; } else if (kind == 1) { tmp_local_intv->value.sval.min = local_smin; } else if (kind == 2) { tmp_local_intv->value.fval.min = local_fmin; } ptr += 3; } else if (!strncmp(ptr, "max", 3)) { if (kind == 0) { tmp_local_intv->value.uval.min = local_umax; } else if (kind == 1) { tmp_local_intv->value.sval.min = local_smax; } else if (kind == 2) { tmp_local_intv->value.fval.min = local_fmax; } ptr += 3; } else { goto error; } while (isspace(ptr[0])) { ptr++; } /* no interval or interval */ if ((ptr[0] == '|') || !ptr[0]) { if (kind == 0) { tmp_local_intv->value.uval.max = tmp_local_intv->value.uval.min; } else if (kind == 1) { tmp_local_intv->value.sval.max = tmp_local_intv->value.sval.min; } else if (kind == 2) { tmp_local_intv->value.fval.max = tmp_local_intv->value.fval.min; } } else if (!strncmp(ptr, "..", 2)) { /* skip ".." */ ptr += 2; while (isspace(ptr[0])) { ++ptr; } /* max */ if (isdigit(ptr[0]) || (ptr[0] == '+') || (ptr[0] == '-')) { if (kind == 0) { tmp_local_intv->value.uval.max = strtoull(ptr, (char **)&ptr, 10); } else if (kind == 1) { tmp_local_intv->value.sval.max = strtoll(ptr, (char **)&ptr, 10); } else if (kind == 2) { if (parse_range_dec64(&ptr, local_fdig, &tmp_local_intv->value.fval.max)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, ptr, "range"); goto error; } } } else if (!strncmp(ptr, "max", 3)) { if (kind == 0) { tmp_local_intv->value.uval.max = local_umax; } else if (kind == 1) { tmp_local_intv->value.sval.max = local_smax; } else if (kind == 2) { tmp_local_intv->value.fval.max = local_fmax; } } else { goto error; } } else { goto error; } /* check min and max in correct order */ if (kind == 0) { /* current segment */ if (tmp_local_intv->value.uval.min > tmp_local_intv->value.uval.max) { goto error; } if (tmp_local_intv->value.uval.min < local_umin || tmp_local_intv->value.uval.max > local_umax) { goto error; } /* segments sholud be ascending order */ if (tmp_intv && (tmp_intv->value.uval.max >= tmp_local_intv->value.uval.min)) { goto error; } } else if (kind == 1) { if (tmp_local_intv->value.sval.min > tmp_local_intv->value.sval.max) { goto error; } if (tmp_local_intv->value.sval.min < local_smin || tmp_local_intv->value.sval.max > local_smax) { goto error; } if (tmp_intv && (tmp_intv->value.sval.max >= tmp_local_intv->value.sval.min)) { goto error; } } else if (kind == 2) { if (tmp_local_intv->value.fval.min > tmp_local_intv->value.fval.max) { goto error; } if (tmp_local_intv->value.fval.min < local_fmin || tmp_local_intv->value.fval.max > local_fmax) { goto error; } if (tmp_intv && (tmp_intv->value.fval.max >= tmp_local_intv->value.fval.min)) { /* fraction-digits value is always the same (it cannot be changed in derived types) */ goto error; } } /* next segment (next OR) */ seg_ptr = strchr(seg_ptr, '|'); if (!seg_ptr) { break; } seg_ptr++; tmp_intv = tmp_local_intv; } /* check local restrictions against superior ones */ if (intv) { tmp_intv = intv; tmp_local_intv = local_intv; while (tmp_local_intv && tmp_intv) { /* reuse local variables */ if (kind == 0) { local_umin = tmp_local_intv->value.uval.min; local_umax = tmp_local_intv->value.uval.max; /* it must be in this interval */ if ((local_umin >= tmp_intv->value.uval.min) && (local_umin <= tmp_intv->value.uval.max)) { /* this interval is covered, next one */ if (local_umax <= tmp_intv->value.uval.max) { tmp_local_intv = tmp_local_intv->next; continue; /* ascending order of restrictions -> fail */ } else { goto error; } } } else if (kind == 1) { local_smin = tmp_local_intv->value.sval.min; local_smax = tmp_local_intv->value.sval.max; if ((local_smin >= tmp_intv->value.sval.min) && (local_smin <= tmp_intv->value.sval.max)) { if (local_smax <= tmp_intv->value.sval.max) { tmp_local_intv = tmp_local_intv->next; continue; } else { goto error; } } } else if (kind == 2) { local_fmin = tmp_local_intv->value.fval.min; local_fmax = tmp_local_intv->value.fval.max; if ((dec64cmp(local_fmin, local_fdig, tmp_intv->value.fval.min, local_fdig) > -1) && (dec64cmp(local_fmin, local_fdig, tmp_intv->value.fval.max, local_fdig) < 1)) { if (dec64cmp(local_fmax, local_fdig, tmp_intv->value.fval.max, local_fdig) < 1) { tmp_local_intv = tmp_local_intv->next; continue; } else { goto error; } } } tmp_intv = tmp_intv->next; } /* some interval left uncovered -> fail */ if (tmp_local_intv) { goto error; } } /* append the local intervals to all the intervals of the superior types, return it all */ if (intv) { for (tmp_intv = intv; tmp_intv->next; tmp_intv = tmp_intv->next); tmp_intv->next = local_intv; } else { intv = local_intv; } *ret = intv; return EXIT_SUCCESS; error: while (intv) { tmp_intv = intv->next; free(intv); intv = tmp_intv; } while (local_intv) { tmp_local_intv = local_intv->next; free(local_intv); local_intv = tmp_local_intv; } return -1; } static int resolve_superior_type_check(struct lys_type *type) { uint32_t i; if (type->base == LY_TYPE_DER) { /* check that the referenced typedef is resolved */ return EXIT_FAILURE; } else if (type->base == LY_TYPE_UNION) { /* check that all union types are resolved */ for (i = 0; i < type->info.uni.count; ++i) { if (resolve_superior_type_check(&type->info.uni.types[i])) { return EXIT_FAILURE; } } } else if (type->base == LY_TYPE_LEAFREF) { /* check there is path in some derived type */ while (!type->info.lref.path) { assert(type->der); type = &type->der->type; } } return EXIT_SUCCESS; } /** * @brief Resolve a typedef, return only resolved typedefs if derived. If leafref, it must be * resolved for this function to return it. Does not log. * * @param[in] name Typedef name. * @param[in] mod_name Typedef name module name. * @param[in] module Main module. * @param[in] parent Parent of the resolved type definition. * @param[out] ret Pointer to the resolved typedef. Can be NULL. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ int resolve_superior_type(const char *name, const char *mod_name, const struct lys_module *module, const struct lys_node *parent, struct lys_tpdf **ret) { int i, j; struct lys_tpdf *tpdf, *match; int tpdf_size; if (!mod_name) { /* no prefix, try built-in types */ for (i = 1; i < LY_DATA_TYPE_COUNT; i++) { if (!strcmp(ly_types[i]->name, name)) { if (ret) { *ret = ly_types[i]; } return EXIT_SUCCESS; } } } else { if (!strcmp(mod_name, module->name)) { /* prefix refers to the current module, ignore it */ mod_name = NULL; } } if (!mod_name && parent) { /* search in local typedefs */ while (parent) { switch (parent->nodetype) { case LYS_CONTAINER: tpdf_size = ((struct lys_node_container *)parent)->tpdf_size; tpdf = ((struct lys_node_container *)parent)->tpdf; break; case LYS_LIST: tpdf_size = ((struct lys_node_list *)parent)->tpdf_size; tpdf = ((struct lys_node_list *)parent)->tpdf; break; case LYS_GROUPING: tpdf_size = ((struct lys_node_grp *)parent)->tpdf_size; tpdf = ((struct lys_node_grp *)parent)->tpdf; break; case LYS_RPC: case LYS_ACTION: tpdf_size = ((struct lys_node_rpc_action *)parent)->tpdf_size; tpdf = ((struct lys_node_rpc_action *)parent)->tpdf; break; case LYS_NOTIF: tpdf_size = ((struct lys_node_notif *)parent)->tpdf_size; tpdf = ((struct lys_node_notif *)parent)->tpdf; break; case LYS_INPUT: case LYS_OUTPUT: tpdf_size = ((struct lys_node_inout *)parent)->tpdf_size; tpdf = ((struct lys_node_inout *)parent)->tpdf; break; default: parent = lys_parent(parent); continue; } for (i = 0; i < tpdf_size; i++) { if (!strcmp(tpdf[i].name, name)) { match = &tpdf[i]; goto check_typedef; } } parent = lys_parent(parent); } } else { /* get module where to search */ module = lyp_get_module(module, NULL, 0, mod_name, 0, 0); if (!module) { return -1; } } /* search in top level typedefs */ for (i = 0; i < module->tpdf_size; i++) { if (!strcmp(module->tpdf[i].name, name)) { match = &module->tpdf[i]; goto check_typedef; } } /* search in submodules */ for (i = 0; i < module->inc_size && module->inc[i].submodule; i++) { for (j = 0; j < module->inc[i].submodule->tpdf_size; j++) { if (!strcmp(module->inc[i].submodule->tpdf[j].name, name)) { match = &module->inc[i].submodule->tpdf[j]; goto check_typedef; } } } return EXIT_FAILURE; check_typedef: if (resolve_superior_type_check(&match->type)) { return EXIT_FAILURE; } if (ret) { *ret = match; } return EXIT_SUCCESS; } /** * @brief Check the default \p value of the \p type. Logs directly. * * @param[in] type Type definition to use. * @param[in] value Default value to check. * @param[in] module Type module. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int check_default(struct lys_type *type, const char **value, struct lys_module *module, int tpdf) { struct lys_tpdf *base_tpdf = NULL; struct lyd_node_leaf_list node; const char *dflt = NULL; char *s; int ret = EXIT_SUCCESS, r; struct ly_ctx *ctx = module->ctx; assert(value); memset(&node, 0, sizeof node); if (type->base <= LY_TYPE_DER) { /* the type was not resolved yet, nothing to do for now */ ret = EXIT_FAILURE; goto cleanup; } else if (!tpdf && !module->implemented) { /* do not check defaults in not implemented module's data */ goto cleanup; } else if (tpdf && !module->implemented && type->base == LY_TYPE_IDENT) { /* identityrefs are checked when instantiated in data instead of typedef, * but in typedef the value has to be modified to include the prefix */ if (*value) { if (strchr(*value, ':')) { dflt = transform_schema2json(module, *value); } else { /* default prefix of the module where the typedef is defined */ if (asprintf(&s, "%s:%s", lys_main_module(module)->name, *value) == -1) { LOGMEM(ctx); ret = -1; goto cleanup; } dflt = lydict_insert_zc(ctx, s); } lydict_remove(ctx, *value); *value = dflt; dflt = NULL; } goto cleanup; } else if (type->base == LY_TYPE_LEAFREF && tpdf) { /* leafref in typedef cannot be checked */ goto cleanup; } dflt = lydict_insert(ctx, *value, 0); if (!dflt) { /* we do not have a new default value, so is there any to check even, in some base type? */ for (base_tpdf = type->der; base_tpdf->type.der; base_tpdf = base_tpdf->type.der) { if (base_tpdf->dflt) { dflt = lydict_insert(ctx, base_tpdf->dflt, 0); break; } } if (!dflt) { /* no default value, nothing to check, all is well */ goto cleanup; } /* so there is a default value in a base type, but can the default value be no longer valid (did we define some new restrictions)? */ switch (type->base) { case LY_TYPE_IDENT: if (lys_main_module(base_tpdf->type.parent->module)->implemented) { goto cleanup; } else { /* check the default value from typedef, but use also the typedef's module * due to possible searching in imported modules which is expected in * typedef's module instead of module where the typedef is used */ module = base_tpdf->module; } break; case LY_TYPE_INST: case LY_TYPE_LEAFREF: case LY_TYPE_BOOL: case LY_TYPE_EMPTY: /* these have no restrictions, so we would do the exact same work as the unres in the base typedef */ goto cleanup; case LY_TYPE_BITS: /* the default value must match the restricted list of values, if the type was restricted */ if (type->info.bits.count) { break; } goto cleanup; case LY_TYPE_ENUM: /* the default value must match the restricted list of values, if the type was restricted */ if (type->info.enums.count) { break; } goto cleanup; case LY_TYPE_DEC64: if (type->info.dec64.range) { break; } goto cleanup; case LY_TYPE_BINARY: if (type->info.binary.length) { break; } goto cleanup; case LY_TYPE_INT8: case LY_TYPE_INT16: case LY_TYPE_INT32: case LY_TYPE_INT64: case LY_TYPE_UINT8: case LY_TYPE_UINT16: case LY_TYPE_UINT32: case LY_TYPE_UINT64: if (type->info.num.range) { break; } goto cleanup; case LY_TYPE_STRING: if (type->info.str.length || type->info.str.patterns) { break; } goto cleanup; case LY_TYPE_UNION: /* way too much trouble learning whether we need to check the default again, so just do it */ break; default: LOGINT(ctx); ret = -1; goto cleanup; } } else if (type->base == LY_TYPE_EMPTY) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "default", type->parent->name); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The \"empty\" data type cannot have a default value."); ret = -1; goto cleanup; } /* dummy leaf */ memset(&node, 0, sizeof node); node.value_str = lydict_insert(ctx, dflt, 0); node.value_type = type->base; if (tpdf) { node.schema = calloc(1, sizeof (struct lys_node_leaf)); if (!node.schema) { LOGMEM(ctx); ret = -1; goto cleanup; } r = asprintf((char **)&node.schema->name, "typedef-%s-default", ((struct lys_tpdf *)type->parent)->name); if (r == -1) { LOGMEM(ctx); ret = -1; goto cleanup; } node.schema->module = module; memcpy(&((struct lys_node_leaf *)node.schema)->type, type, sizeof *type); } else { node.schema = (struct lys_node *)type->parent; } if (type->base == LY_TYPE_LEAFREF) { if (!type->info.lref.target) { ret = EXIT_FAILURE; LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Default value \"%s\" cannot be checked in an unresolved leafref.", dflt); goto cleanup; } ret = check_default(&type->info.lref.target->type, &dflt, module, 0); if (!ret) { /* adopt possibly changed default value to its canonical form */ if (*value) { lydict_remove(ctx, *value); *value = dflt; dflt = NULL; } } } else { if (!lyp_parse_value(type, &node.value_str, NULL, &node, NULL, module, 1, 1, 0)) { /* possible forward reference */ ret = EXIT_FAILURE; if (base_tpdf) { /* default value is defined in some base typedef */ if ((type->base == LY_TYPE_BITS && type->der->type.der) || (type->base == LY_TYPE_ENUM && type->der->type.der)) { /* we have refined bits/enums */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%s\" of the default statement inherited to \"%s\" from \"%s\" base type.", dflt, type->parent->name, base_tpdf->name); } } } else { /* success - adopt canonical form from the node into the default value */ if (!ly_strequal(dflt, node.value_str, 1)) { /* this can happen only if we have non-inherited default value, * inherited default values are already in canonical form */ assert(ly_strequal(dflt, *value, 1)); lydict_remove(ctx, *value); *value = node.value_str; node.value_str = NULL; } } } cleanup: lyd_free_value(node.value, node.value_type, node.value_flags, type, node.value_str, NULL, NULL, NULL); lydict_remove(ctx, node.value_str); if (tpdf && node.schema) { free((char *)node.schema->name); free(node.schema); } lydict_remove(ctx, dflt); return ret; } /** * @brief Check a key for mandatory attributes. Logs directly. * * @param[in] key The key to check. * @param[in] flags What flags to check. * @param[in] list The list of all the keys. * @param[in] index Index of the key in the key list. * @param[in] name The name of the keys. * @param[in] len The name length. * * @return EXIT_SUCCESS on success, -1 on error. */ static int check_key(struct lys_node_list *list, int index, const char *name, int len) { struct lys_node_leaf *key = list->keys[index]; char *dup = NULL; int j; struct ly_ctx *ctx = list->module->ctx; /* existence */ if (!key) { if (name[len] != '\0') { dup = strdup(name); LY_CHECK_ERR_RETURN(!dup, LOGMEM(ctx), -1); dup[len] = '\0'; name = dup; } LOGVAL(ctx, LYE_KEY_MISS, LY_VLOG_LYS, list, name); free(dup); return -1; } /* uniqueness */ for (j = index - 1; j >= 0; j--) { if (key == list->keys[j]) { LOGVAL(ctx, LYE_KEY_DUP, LY_VLOG_LYS, list, key->name); return -1; } } /* key is a leaf */ if (key->nodetype != LYS_LEAF) { LOGVAL(ctx, LYE_KEY_NLEAF, LY_VLOG_LYS, list, key->name); return -1; } /* type of the leaf is not built-in empty */ if (key->type.base == LY_TYPE_EMPTY && key->module->version < LYS_VERSION_1_1) { LOGVAL(ctx, LYE_KEY_TYPE, LY_VLOG_LYS, list, key->name); return -1; } /* config attribute is the same as of the list */ if ((key->flags & LYS_CONFIG_MASK) && (list->flags & LYS_CONFIG_MASK) && ((list->flags & LYS_CONFIG_MASK) != (key->flags & LYS_CONFIG_MASK))) { LOGVAL(ctx, LYE_KEY_CONFIG, LY_VLOG_LYS, list, key->name); return -1; } /* key is not placed from augment */ if (key->parent->nodetype == LYS_AUGMENT) { LOGVAL(ctx, LYE_KEY_MISS, LY_VLOG_LYS, key, key->name); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Key inserted from augment."); return -1; } /* key is not when/if-feature -conditional */ j = 0; if (key->when || (key->iffeature_size && (j = 1))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, key, j ? "if-feature" : "when", "leaf"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Key definition cannot depend on a \"%s\" condition.", j ? "if-feature" : "when"); return -1; } return EXIT_SUCCESS; } /** * @brief Resolve (test the target exists) unique. Logs directly. * * @param[in] parent The parent node of the unique structure. * @param[in] uniq_str_path One path from the unique string. * * @return EXIT_SUCCESS on succes, EXIT_FAILURE on forward reference, -1 on error. */ int resolve_unique(struct lys_node *parent, const char *uniq_str_path, uint8_t *trg_type) { int rc; const struct lys_node *leaf = NULL; struct ly_ctx *ctx = parent->module->ctx; rc = resolve_descendant_schema_nodeid(uniq_str_path, *lys_child(parent, LYS_LEAF), LYS_LEAF, 1, &leaf); if (rc || !leaf) { if (rc) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique"); if (rc > 0) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_PREV, NULL, uniq_str_path[rc - 1], &uniq_str_path[rc - 1]); } else if (rc == -2) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Unique argument references list."); } rc = -1; } else { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Target leaf not found."); rc = EXIT_FAILURE; } goto error; } if (leaf->nodetype != LYS_LEAF) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Target is not a leaf."); return -1; } /* check status */ if (parent->nodetype != LYS_EXT && lyp_check_status(parent->flags, parent->module, parent->name, leaf->flags, leaf->module, leaf->name, leaf)) { return -1; } /* check that all unique's targets are of the same config type */ if (*trg_type) { if (((*trg_type == 1) && (leaf->flags & LYS_CONFIG_R)) || ((*trg_type == 2) && (leaf->flags & LYS_CONFIG_W))) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Leaf \"%s\" referenced in unique statement is config %s, but previous referenced leaf is config %s.", uniq_str_path, *trg_type == 1 ? "false" : "true", *trg_type == 1 ? "true" : "false"); return -1; } } else { /* first unique */ if (leaf->flags & LYS_CONFIG_W) { *trg_type = 1; } else { *trg_type = 2; } } /* set leaf's unique flag */ ((struct lys_node_leaf *)leaf)->flags |= LYS_UNIQUE; return EXIT_SUCCESS; error: return rc; } void unres_data_del(struct unres_data *unres, uint32_t i) { /* there are items after the one deleted */ if (i+1 < unres->count) { /* we only move the data, memory is left allocated, why bother */ memmove(&unres->node[i], &unres->node[i+1], (unres->count-(i+1)) * sizeof *unres->node); /* deleting the last item */ } else if (i == 0) { free(unres->node); unres->node = NULL; } /* if there are no items after and it is not the last one, just move the counter */ --unres->count; } /** * @brief Resolve (find) a data node from a specific module. Does not log. * * @param[in] mod Module to search in. * @param[in] name Name of the data node. * @param[in] nam_len Length of the name. * @param[in] start Data node to start the search from. * @param[in,out] parents Resolved nodes. If there are some parents, * they are replaced (!!) with the resolvents. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_data(const struct lys_module *mod, const char *name, int nam_len, struct lyd_node *start, struct unres_data *parents) { struct lyd_node *node; int flag; uint32_t i; if (!parents->count) { parents->count = 1; parents->node = malloc(sizeof *parents->node); LY_CHECK_ERR_RETURN(!parents->node, LOGMEM(mod->ctx), -1); parents->node[0] = NULL; } for (i = 0; i < parents->count;) { if (parents->node[i] && (parents->node[i]->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) { /* skip */ ++i; continue; } flag = 0; LY_TREE_FOR(parents->node[i] ? parents->node[i]->child : start, node) { if (lyd_node_module(node) == mod && !strncmp(node->schema->name, name, nam_len) && node->schema->name[nam_len] == '\0') { /* matching target */ if (!flag) { /* put node instead of the current parent */ parents->node[i] = node; flag = 1; } else { /* multiple matching, so create a new node */ ++parents->count; parents->node = ly_realloc(parents->node, parents->count * sizeof *parents->node); LY_CHECK_ERR_RETURN(!parents->node, LOGMEM(mod->ctx), EXIT_FAILURE); parents->node[parents->count-1] = node; ++i; } } } if (!flag) { /* remove item from the parents list */ unres_data_del(parents, i); } else { ++i; } } return parents->count ? EXIT_SUCCESS : EXIT_FAILURE; } static int resolve_schema_leafref_valid_dep_flag(const struct lys_node *op_node, const struct lys_module *local_mod, const struct lys_node *first_node, int abs_path) { int dep1, dep2; const struct lys_node *node; if (!op_node) { /* leafref pointing to a different module */ if (local_mod != lys_node_module(first_node)) { return 1; } } else if (lys_parent(op_node)) { /* inner operation (notif/action) */ if (abs_path) { return 1; } else { /* compare depth of both nodes */ for (dep1 = 0, node = op_node; lys_parent(node); node = lys_parent(node)); for (dep2 = 0, node = first_node; lys_parent(node); node = lys_parent(node)); if ((dep2 > dep1) || ((dep2 == dep1) && (op_node != first_node))) { return 1; } } } else { /* top-level operation (notif/rpc) */ if (op_node != first_node) { return 1; } } return 0; } /** * @brief Resolve a path (leafref) predicate in JSON schema context. Logs directly. * * @param[in] path Path to use. * @param[in] context_node Predicate context node (where the predicate is placed). * @param[in] parent Path context node (where the path begins/is placed). * @param[in] node_set Set where to add nodes whose parent chain must be implemented. * * @return 0 on forward reference, otherwise the number * of characters successfully parsed, * positive on success, negative on failure. */ static int resolve_schema_leafref_predicate(const char *path, const struct lys_node *context_node, struct lys_node *parent, struct ly_set *node_set) { const struct lys_module *trg_mod; const struct lys_node *src_node, *dst_node, *tmp_parent; struct lys_node_augment *last_aug; const char *path_key_expr, *source, *sour_pref, *dest, *dest_pref; int pke_len, sour_len, sour_pref_len, dest_len, dest_pref_len, pke_parsed, parsed = 0; int has_predicate, dest_parent_times, i, rc; struct ly_ctx *ctx = context_node->module->ctx; do { if ((i = parse_path_predicate(path, &sour_pref, &sour_pref_len, &source, &sour_len, &path_key_expr, &pke_len, &has_predicate)) < 1) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, path[-i], path - i); return -parsed + i; } parsed += i; path += i; /* source (must be leaf) */ if (sour_pref) { trg_mod = lyp_get_module(lys_node_module(parent), NULL, 0, sour_pref, sour_pref_len, 0); } else { trg_mod = lys_node_module(parent); } rc = lys_getnext_data(trg_mod, context_node, source, sour_len, LYS_LEAF | LYS_LEAFLIST, LYS_GETNEXT_NOSTATECHECK, &src_node); if (rc) { LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path-parsed); return 0; } /* destination */ dest_parent_times = 0; pke_parsed = 0; if ((i = parse_path_key_expr(path_key_expr, &dest_pref, &dest_pref_len, &dest, &dest_len, &dest_parent_times)) < 1) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, path_key_expr[-i], path_key_expr-i); return -parsed; } pke_parsed += i; for (i = 0, dst_node = parent; i < dest_parent_times; ++i) { if (!dst_node) { /* we went too much into parents, there is no parent anymore */ LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path_key_expr); return 0; } if (dst_node->parent && (dst_node->parent->nodetype == LYS_AUGMENT) && !((struct lys_node_augment *)dst_node->parent)->target) { /* we are in an unresolved augment, cannot evaluate */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, dst_node->parent, "Cannot resolve leafref predicate \"%s\" because it is in an unresolved augment.", path_key_expr); return 0; } /* path is supposed to be evaluated in data tree, so we have to skip * all schema nodes that cannot be instantiated in data tree */ for (dst_node = lys_parent(dst_node); dst_node && !(dst_node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_ACTION | LYS_NOTIF | LYS_RPC)); dst_node = lys_parent(dst_node)); } while (1) { last_aug = NULL; if (dest_pref) { trg_mod = lyp_get_module(lys_node_module(parent), NULL, 0, dest_pref, dest_pref_len, 0); } else { trg_mod = lys_node_module(parent); } if (!trg_mod->implemented && dst_node) { get_next_augment: last_aug = lys_getnext_target_aug(last_aug, trg_mod, dst_node); } tmp_parent = (last_aug ? (struct lys_node *)last_aug : dst_node); rc = lys_getnext_data(trg_mod, tmp_parent, dest, dest_len, LYS_CONTAINER | LYS_LIST | LYS_LEAF, LYS_GETNEXT_NOSTATECHECK, &dst_node); if (rc) { if (last_aug) { /* restore the correct augment target */ dst_node = last_aug->target; goto get_next_augment; } LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path_key_expr); return 0; } if (pke_len == pke_parsed) { break; } if ((i = parse_path_key_expr(path_key_expr + pke_parsed, &dest_pref, &dest_pref_len, &dest, &dest_len, &dest_parent_times)) < 1) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, (path_key_expr + pke_parsed)[-i], (path_key_expr + pke_parsed) - i); return -parsed; } pke_parsed += i; } /* check source - dest match */ if (dst_node->nodetype != src_node->nodetype) { LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path - parsed); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Destination node is not a %s, but a %s.", strnodetype(src_node->nodetype), strnodetype(dst_node->nodetype)); return -parsed; } /* add both nodes into node set */ ly_set_add(node_set, (void *)dst_node, 0); ly_set_add(node_set, (void *)src_node, 0); } while (has_predicate); return parsed; } static int check_leafref_features(struct lys_type *type) { struct lys_node *iter; struct ly_set *src_parents, *trg_parents, *features; struct lys_node_augment *aug; struct ly_ctx *ctx = ((struct lys_tpdf *)type->parent)->module->ctx; unsigned int i, j, size, x; int ret = EXIT_SUCCESS; assert(type->parent); src_parents = ly_set_new(); trg_parents = ly_set_new(); features = ly_set_new(); /* get parents chain of source (leafref) */ for (iter = (struct lys_node *)type->parent; iter; iter = lys_parent(iter)) { if (iter->nodetype & (LYS_INPUT | LYS_OUTPUT)) { continue; } if (iter->parent && (iter->parent->nodetype == LYS_AUGMENT)) { aug = (struct lys_node_augment *)iter->parent; if ((aug->module->implemented && (aug->flags & LYS_NOTAPPLIED)) || !aug->target) { /* unresolved augment, wait until it's resolved */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, aug, "Cannot check leafref \"%s\" if-feature consistency because of an unresolved augment.", type->info.lref.path); ret = EXIT_FAILURE; goto cleanup; } /* also add this augment */ ly_set_add(src_parents, aug, LY_SET_OPT_USEASLIST); } ly_set_add(src_parents, iter, LY_SET_OPT_USEASLIST); } /* get parents chain of target */ for (iter = (struct lys_node *)type->info.lref.target; iter; iter = lys_parent(iter)) { if (iter->nodetype & (LYS_INPUT | LYS_OUTPUT)) { continue; } if (iter->parent && (iter->parent->nodetype == LYS_AUGMENT)) { aug = (struct lys_node_augment *)iter->parent; if ((aug->module->implemented && (aug->flags & LYS_NOTAPPLIED)) || !aug->target) { /* unresolved augment, wait until it's resolved */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, aug, "Cannot check leafref \"%s\" if-feature consistency because of an unresolved augment.", type->info.lref.path); ret = EXIT_FAILURE; goto cleanup; } } ly_set_add(trg_parents, iter, LY_SET_OPT_USEASLIST); } /* compare the features used in if-feature statements in the rest of both * chains of parents. The set of features used for target must be a subset * of features used for the leafref. This is not a perfect, we should compare * the truth tables but it could require too much resources, so we simplify that */ for (i = 0; i < src_parents->number; i++) { iter = src_parents->set.s[i]; /* shortcut */ if (!iter->iffeature_size) { continue; } for (j = 0; j < iter->iffeature_size; j++) { resolve_iffeature_getsizes(&iter->iffeature[j], NULL, &size); for (; size; size--) { if (!iter->iffeature[j].features[size - 1]) { /* not yet resolved feature, postpone this check */ ret = EXIT_FAILURE; goto cleanup; } ly_set_add(features, iter->iffeature[j].features[size - 1], 0); } } } x = features->number; for (i = 0; i < trg_parents->number; i++) { iter = trg_parents->set.s[i]; /* shortcut */ if (!iter->iffeature_size) { continue; } for (j = 0; j < iter->iffeature_size; j++) { resolve_iffeature_getsizes(&iter->iffeature[j], NULL, &size); for (; size; size--) { if (!iter->iffeature[j].features[size - 1]) { /* not yet resolved feature, postpone this check */ ret = EXIT_FAILURE; goto cleanup; } if ((unsigned)ly_set_add(features, iter->iffeature[j].features[size - 1], 0) >= x) { /* the feature is not present in features set of target's parents chain */ LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, type->parent, "leafref", type->info.lref.path); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Leafref is not conditional based on \"%s\" feature as its target.", iter->iffeature[j].features[size - 1]->name); ret = -1; goto cleanup; } } } } cleanup: ly_set_free(features); ly_set_free(src_parents); ly_set_free(trg_parents); return ret; } /** * @brief Resolve a path (leafref) in JSON schema context. Logs directly. * * @param[in] path Path to use. * @param[in] parent_node Parent of the leafref. * @param[out] ret Pointer to the resolved schema node. Can be NULL. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_schema_leafref(struct lys_type *type, struct lys_node *parent, struct unres_schema *unres) { const struct lys_node *node, *op_node = NULL, *tmp_parent; struct ly_set *node_set; struct lys_node_augment *last_aug; const struct lys_module *tmp_mod, *cur_module; const char *id, *prefix, *name; int pref_len, nam_len, parent_times, has_predicate; int i, first_iter; struct ly_ctx *ctx = parent->module->ctx; first_iter = 1; parent_times = 0; id = type->info.lref.path; node_set = ly_set_new(); if (!node_set) { LOGMEM(ctx); return -1; } /* find operation schema we are in */ for (op_node = lys_parent(parent); op_node && !(op_node->nodetype & (LYS_ACTION | LYS_NOTIF | LYS_RPC)); op_node = lys_parent(op_node)); cur_module = lys_node_module(parent); do { if ((i = parse_path_arg(cur_module, id, &prefix, &pref_len, &name, &nam_len, &parent_times, &has_predicate)) < 1) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, id[-i], &id[-i]); ly_set_free(node_set); return -1; } id += i; /* get the current module */ tmp_mod = prefix ? lyp_get_module(cur_module, NULL, 0, prefix, pref_len, 0) : cur_module; if (!tmp_mod) { LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path); ly_set_free(node_set); return EXIT_FAILURE; } last_aug = NULL; if (first_iter) { if (parent_times == -1) { /* use module data */ node = NULL; } else if (parent_times > 0) { /* we are looking for the right parent */ for (i = 0, node = parent; i < parent_times; i++) { if (node->parent && (node->parent->nodetype == LYS_AUGMENT) && !((struct lys_node_augment *)node->parent)->target) { /* we are in an unresolved augment, cannot evaluate */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, node->parent, "Cannot resolve leafref \"%s\" because it is in an unresolved augment.", type->info.lref.path); ly_set_free(node_set); return EXIT_FAILURE; } /* path is supposed to be evaluated in data tree, so we have to skip * all schema nodes that cannot be instantiated in data tree */ for (node = lys_parent(node); node && !(node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_ACTION | LYS_NOTIF | LYS_RPC)); node = lys_parent(node)); if (!node) { if (i == parent_times - 1) { /* top-level */ break; } /* higher than top-level */ LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path); ly_set_free(node_set); return EXIT_FAILURE; } } } else { LOGINT(ctx); ly_set_free(node_set); return -1; } } /* find the next node (either in unconnected augment or as a schema sibling, node is NULL for top-level node - * - useless to search for that in augments) */ if (!tmp_mod->implemented && node) { get_next_augment: last_aug = lys_getnext_target_aug(last_aug, tmp_mod, node); } tmp_parent = (last_aug ? (struct lys_node *)last_aug : node); node = NULL; while ((node = lys_getnext(node, tmp_parent, tmp_mod, LYS_GETNEXT_NOSTATECHECK))) { if (lys_node_module(node) != lys_main_module(tmp_mod)) { continue; } if (strncmp(node->name, name, nam_len) || node->name[nam_len]) { continue; } /* match */ break; } if (!node) { if (last_aug) { /* restore the correct augment target */ node = last_aug->target; goto get_next_augment; } LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path); ly_set_free(node_set); return EXIT_FAILURE; } if (first_iter) { /* set external dependency flag, we can decide based on the first found node */ if (resolve_schema_leafref_valid_dep_flag(op_node, cur_module, node, (parent_times == -1 ? 1 : 0))) { parent->flags |= LYS_LEAFREF_DEP; } first_iter = 0; } if (has_predicate) { /* we have predicate, so the current result must be list */ if (node->nodetype != LYS_LIST) { LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path); ly_set_free(node_set); return -1; } i = resolve_schema_leafref_predicate(id, node, parent, node_set); if (!i) { ly_set_free(node_set); return EXIT_FAILURE; } else if (i < 0) { ly_set_free(node_set); return -1; } id += i; has_predicate = 0; } } while (id[0]); /* the target must be leaf or leaf-list (in YANG 1.1 only) */ if ((node->nodetype != LYS_LEAF) && (node->nodetype != LYS_LEAFLIST)) { LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Leafref target \"%s\" is not a leaf nor a leaf-list.", type->info.lref.path); ly_set_free(node_set); return -1; } /* check status */ if (lyp_check_status(parent->flags, parent->module, parent->name, node->flags, node->module, node->name, node)) { ly_set_free(node_set); return -1; } /* assign */ type->info.lref.target = (struct lys_node_leaf *)node; /* add the target node into a set so its parent chain modules can be implemented */ ly_set_add(node_set, (void *)node, 0); /* as the last thing traverse this leafref and make targets on the path implemented */ if (lys_node_module(parent)->implemented) { /* make all the modules in the path implemented */ for (i = 0; (unsigned)i < node_set->number; ++i) { for (node = node_set->set.s[i]; node; node = lys_parent(node)) { if (!lys_node_module(node)->implemented) { lys_node_module(node)->implemented = 1; if (unres_schema_add_node(lys_node_module(node), unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) { ly_set_free(node_set); return -1; } } } } /* store the backlink from leafref target */ if (lys_leaf_add_leafref_target(type->info.lref.target, (struct lys_node *)type->parent)) { ly_set_free(node_set); return -1; } } ly_set_free(node_set); /* check if leafref and its target are under common if-features */ return check_leafref_features(type); } /** * @brief Compare 2 data node values. * * Comparison performed on canonical forms, the first value * is first transformed into canonical form. * * @param[in] node Leaf/leaf-list with these values. * @param[in] noncan_val Non-canonical value. * @param[in] noncan_val_len Length of \p noncal_val. * @param[in] can_val Canonical value. * @return 1 if equal, 0 if not, -1 on error (logged). */ static int valequal(struct lys_node *node, const char *noncan_val, int noncan_val_len, const char *can_val) { int ret; struct lyd_node_leaf_list leaf; struct lys_node_leaf *sleaf = (struct lys_node_leaf*)node; /* dummy leaf */ memset(&leaf, 0, sizeof leaf); leaf.value_str = lydict_insert(node->module->ctx, noncan_val, noncan_val_len); repeat: leaf.value_type = sleaf->type.base; leaf.schema = node; if (leaf.value_type == LY_TYPE_LEAFREF) { if (!sleaf->type.info.lref.target) { /* it should either be unresolved leafref (leaf.value_type are ORed flags) or it will be resolved */ LOGINT(node->module->ctx); ret = -1; goto finish; } sleaf = sleaf->type.info.lref.target; goto repeat; } else { if (!lyp_parse_value(&sleaf->type, &leaf.value_str, NULL, &leaf, NULL, NULL, 0, 0, 0)) { ret = -1; goto finish; } } if (!strcmp(leaf.value_str, can_val)) { ret = 1; } else { ret = 0; } finish: lydict_remove(node->module->ctx, leaf.value_str); return ret; } /** * @brief Resolve instance-identifier predicate in JSON data format. * Does not log. * * @param[in] prev_mod Previous module to use in case there is no prefix. * @param[in] pred Predicate to use. * @param[in,out] node Node matching the restriction without * the predicate. If it does not satisfy the predicate, * it is set to NULL. * * @return Number of characters successfully parsed, * positive on success, negative on failure. */ static int resolve_instid_predicate(const struct lys_module *prev_mod, const char *pred, struct lyd_node **node, int cur_idx) { /* ... /node[key=value] ... */ struct lyd_node_leaf_list *key; struct lys_node_leaf **list_keys = NULL; struct lys_node_list *slist = NULL; const char *model, *name, *value; int mod_len, nam_len, val_len, i, has_predicate, parsed; struct ly_ctx *ctx = prev_mod->ctx; assert(pred && node && *node); parsed = 0; do { if ((i = parse_predicate(pred + parsed, &model, &mod_len, &name, &nam_len, &value, &val_len, &has_predicate)) < 1) { return -parsed + i; } parsed += i; if (!(*node)) { /* just parse it all */ continue; } /* target */ if (name[0] == '.') { /* leaf-list value */ if ((*node)->schema->nodetype != LYS_LEAFLIST) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects leaf-list, but have %s \"%s\".", strnodetype((*node)->schema->nodetype), (*node)->schema->name); parsed = -1; goto cleanup; } /* check the value */ if (!valequal((*node)->schema, value, val_len, ((struct lyd_node_leaf_list *)*node)->value_str)) { *node = NULL; goto cleanup; } } else if (isdigit(name[0])) { assert(!value); /* keyless list position */ if ((*node)->schema->nodetype != LYS_LIST) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list, but have %s \"%s\".", strnodetype((*node)->schema->nodetype), (*node)->schema->name); parsed = -1; goto cleanup; } if (((struct lys_node_list *)(*node)->schema)->keys) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list without keys, but have list \"%s\".", (*node)->schema->name); parsed = -1; goto cleanup; } /* check the index */ if (atoi(name) != cur_idx) { *node = NULL; goto cleanup; } } else { /* list key value */ if ((*node)->schema->nodetype != LYS_LIST) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list, but have %s \"%s\".", strnodetype((*node)->schema->nodetype), (*node)->schema->name); parsed = -1; goto cleanup; } slist = (struct lys_node_list *)(*node)->schema; /* prepare key array */ if (!list_keys) { list_keys = malloc(slist->keys_size * sizeof *list_keys); LY_CHECK_ERR_RETURN(!list_keys, LOGMEM(ctx), -1); for (i = 0; i < slist->keys_size; ++i) { list_keys[i] = slist->keys[i]; } } /* find the schema key leaf */ for (i = 0; i < slist->keys_size; ++i) { if (list_keys[i] && !strncmp(list_keys[i]->name, name, nam_len) && !list_keys[i]->name[nam_len]) { break; } } if (i == slist->keys_size) { /* this list has no such key */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list with the key \"%.*s\"," " but list \"%s\" does not define it.", nam_len, name, slist->name); parsed = -1; goto cleanup; } /* check module */ if (model) { if (strncmp(list_keys[i]->module->name, model, mod_len) || list_keys[i]->module->name[mod_len]) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects key \"%s\" from module \"%.*s\", not \"%s\".", list_keys[i]->name, model, mod_len, list_keys[i]->module->name); parsed = -1; goto cleanup; } } else { if (list_keys[i]->module != prev_mod) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects key \"%s\" from module \"%s\", not \"%s\".", list_keys[i]->name, prev_mod->name, list_keys[i]->module->name); parsed = -1; goto cleanup; } } /* find the actual data key */ for (key = (struct lyd_node_leaf_list *)(*node)->child; key; key = (struct lyd_node_leaf_list *)key->next) { if (key->schema == (struct lys_node *)list_keys[i]) { break; } } if (!key) { /* list instance is missing a key? definitely should not happen */ LOGINT(ctx); parsed = -1; goto cleanup; } /* check the value */ if (!valequal(key->schema, value, val_len, key->value_str)) { *node = NULL; /* we still want to parse the whole predicate */ continue; } /* everything is fine, mark this key as resolved */ list_keys[i] = NULL; } } while (has_predicate); /* check that all list keys were specified */ if (*node && list_keys) { for (i = 0; i < slist->keys_size; ++i) { if (list_keys[i]) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier is missing list key \"%s\".", list_keys[i]->name); parsed = -1; goto cleanup; } } } cleanup: free(list_keys); return parsed; } static int check_xpath(struct lys_node *node, int check_place) { struct lys_node *parent; struct lyxp_set set; enum int_log_opts prev_ilo; if (check_place) { parent = node; while (parent) { if (parent->nodetype == LYS_GROUPING) { /* unresolved grouping, skip for now (will be checked later) */ return EXIT_SUCCESS; } if (parent->nodetype == LYS_AUGMENT) { if (!((struct lys_node_augment *)parent)->target) { /* unresolved augment, skip for now (will be checked later) */ return EXIT_FAILURE; } else { parent = ((struct lys_node_augment *)parent)->target; continue; } } parent = parent->parent; } } memset(&set, 0, sizeof set); /* produce just warnings */ ly_ilo_change(NULL, ILO_ERR2WRN, &prev_ilo, NULL); lyxp_node_atomize(node, &set, 1); ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (set.val.snodes) { free(set.val.snodes); } return EXIT_SUCCESS; } static int check_leafref_config(struct lys_node_leaf *leaf, struct lys_type *type) { unsigned int i; if (type->base == LY_TYPE_LEAFREF) { if ((leaf->flags & LYS_CONFIG_W) && type->info.lref.target && type->info.lref.req != -1 && (type->info.lref.target->flags & LYS_CONFIG_R)) { LOGVAL(leaf->module->ctx, LYE_SPEC, LY_VLOG_LYS, leaf, "The leafref %s is config but refers to a non-config %s.", strnodetype(leaf->nodetype), strnodetype(type->info.lref.target->nodetype)); return -1; } /* we can skip the test in case the leafref is not yet resolved. In that case the test is done in the time * of leafref resolving (lys_leaf_add_leafref_target()) */ } else if (type->base == LY_TYPE_UNION) { for (i = 0; i < type->info.uni.count; i++) { if (check_leafref_config(leaf, &type->info.uni.types[i])) { return -1; } } } return 0; } /** * @brief Passes config flag down to children, skips nodes without config flags. * Logs. * * @param[in] node Siblings and their children to have flags changed. * @param[in] clear Flag to clear all config flags if parent is LYS_NOTIF, LYS_INPUT, LYS_OUTPUT, LYS_RPC. * @param[in] flags Flags to assign to all the nodes. * @param[in,out] unres List of unresolved items. * * @return 0 on success, -1 on error. */ int inherit_config_flag(struct lys_node *node, int flags, int clear) { struct lys_node_leaf *leaf; struct ly_ctx *ctx; if (!node) { return 0; } assert(!(flags ^ (flags & LYS_CONFIG_MASK))); ctx = node->module->ctx; LY_TREE_FOR(node, node) { if (clear) { node->flags &= ~LYS_CONFIG_MASK; node->flags &= ~LYS_CONFIG_SET; } else { if (node->flags & LYS_CONFIG_SET) { /* skip nodes with an explicit config value */ if ((flags & LYS_CONFIG_R) && (node->flags & LYS_CONFIG_W)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, node, "true", "config"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "State nodes cannot have configuration nodes as children."); return -1; } continue; } if (!(node->nodetype & (LYS_USES | LYS_GROUPING))) { node->flags = (node->flags & ~LYS_CONFIG_MASK) | flags; /* check that configuration lists have keys */ if ((node->nodetype == LYS_LIST) && (node->flags & LYS_CONFIG_W) && !((struct lys_node_list *)node)->keys_size) { LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, node, "key", "list"); return -1; } } } if (!(node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) { if (inherit_config_flag(node->child, flags, clear)) { return -1; } } else if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST)) { leaf = (struct lys_node_leaf *)node; if (check_leafref_config(leaf, &leaf->type)) { return -1; } } } return 0; } /** * @brief Resolve augment target. Logs directly. * * @param[in] aug Augment to use. * @param[in] uses Parent where to start the search in. If set, uses augment, if not, standalone augment. * @param[in,out] unres List of unresolved items. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_augment(struct lys_node_augment *aug, struct lys_node *uses, struct unres_schema *unres) { int rc; struct lys_node *sub; struct lys_module *mod; struct ly_set *set; struct ly_ctx *ctx; assert(aug); mod = lys_main_module(aug->module); ctx = mod->ctx; /* set it as not applied for now */ aug->flags |= LYS_NOTAPPLIED; /* it can already be resolved in case we returned EXIT_FAILURE from if block below */ if (!aug->target) { /* resolve target node */ rc = resolve_schema_nodeid(aug->target_name, uses, (uses ? NULL : lys_node_module((struct lys_node *)aug)), &set, 0, 0); if (rc == -1) { LOGVAL(ctx, LYE_PATH, LY_VLOG_LYS, aug); return -1; } if (!set) { LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, aug, "augment", aug->target_name); return EXIT_FAILURE; } aug->target = set->set.s[0]; ly_set_free(set); } /* make this module implemented if the target module is (if the target is in an unimplemented module, * it is fine because when we will be making that module implemented, its augment will be applied * and that augment target module made implemented, recursively) */ if (mod->implemented && !lys_node_module(aug->target)->implemented) { lys_node_module(aug->target)->implemented = 1; if (unres_schema_add_node(lys_node_module(aug->target), unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) { return -1; } } /* check for mandatory nodes - if the target node is in another module * the added nodes cannot be mandatory */ if (!aug->parent && (lys_node_module((struct lys_node *)aug) != lys_node_module(aug->target)) && (rc = lyp_check_mandatory_augment(aug, aug->target))) { return rc; } /* check augment target type and then augment nodes type */ if (aug->target->nodetype & (LYS_CONTAINER | LYS_LIST)) { LY_TREE_FOR(aug->child, sub) { if (!(sub->nodetype & (LYS_ANYDATA | LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_USES | LYS_CHOICE | LYS_ACTION | LYS_NOTIF))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, aug, strnodetype(sub->nodetype), "augment"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Cannot augment \"%s\" with a \"%s\".", strnodetype(aug->target->nodetype), strnodetype(sub->nodetype)); return -1; } } } else if (aug->target->nodetype & (LYS_CASE | LYS_INPUT | LYS_OUTPUT | LYS_NOTIF)) { LY_TREE_FOR(aug->child, sub) { if (!(sub->nodetype & (LYS_ANYDATA | LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_USES | LYS_CHOICE))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, aug, strnodetype(sub->nodetype), "augment"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Cannot augment \"%s\" with a \"%s\".", strnodetype(aug->target->nodetype), strnodetype(sub->nodetype)); return -1; } } } else if (aug->target->nodetype == LYS_CHOICE) { LY_TREE_FOR(aug->child, sub) { if (!(sub->nodetype & (LYS_CASE | LYS_ANYDATA | LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST))) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, aug, strnodetype(sub->nodetype), "augment"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Cannot augment \"%s\" with a \"%s\".", strnodetype(aug->target->nodetype), strnodetype(sub->nodetype)); return -1; } } } else { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, aug, aug->target_name, "target-node"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Invalid augment target node type \"%s\".", strnodetype(aug->target->nodetype)); return -1; } /* check identifier uniqueness as in lys_node_addchild() */ LY_TREE_FOR(aug->child, sub) { if (lys_check_id(sub, aug->target, NULL)) { return -1; } } if (!aug->child) { /* empty augment, nothing to connect, but it is techincally applied */ LOGWRN(ctx, "Augment \"%s\" without children.", aug->target_name); aug->flags &= ~LYS_NOTAPPLIED; } else if ((aug->parent || mod->implemented) && apply_aug(aug, unres)) { /* we try to connect the augment only in case the module is implemented or * the augment applies on the used grouping, anyway we failed here */ return -1; } return EXIT_SUCCESS; } static int resolve_extension(struct unres_ext *info, struct lys_ext_instance **ext, struct unres_schema *unres) { enum LY_VLOG_ELEM vlog_type; void *vlog_node; unsigned int i, j; struct lys_ext *e; char *ext_name, *ext_prefix, *tmp; struct lyxml_elem *next_yin, *yin; const struct lys_module *mod; struct lys_ext_instance *tmp_ext; struct ly_ctx *ctx = NULL; LYEXT_TYPE etype; switch (info->parent_type) { case LYEXT_PAR_NODE: vlog_node = info->parent; vlog_type = LY_VLOG_LYS; break; case LYEXT_PAR_MODULE: case LYEXT_PAR_IMPORT: case LYEXT_PAR_INCLUDE: vlog_node = NULL; vlog_type = LY_VLOG_LYS; break; default: vlog_node = NULL; vlog_type = LY_VLOG_NONE; break; } if (info->datatype == LYS_IN_YIN) { /* YIN */ /* get the module where the extension is supposed to be defined */ mod = lyp_get_import_module_ns(info->mod, info->data.yin->ns->value); if (!mod) { LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, info->data.yin->name); return EXIT_FAILURE; } ctx = mod->ctx; /* find the extension definition */ e = NULL; for (i = 0; i < mod->extensions_size; i++) { if (ly_strequal(mod->extensions[i].name, info->data.yin->name, 1)) { e = &mod->extensions[i]; break; } } /* try submodules */ for (j = 0; !e && j < mod->inc_size; j++) { for (i = 0; i < mod->inc[j].submodule->extensions_size; i++) { if (ly_strequal(mod->inc[j].submodule->extensions[i].name, info->data.yin->name, 1)) { e = &mod->inc[j].submodule->extensions[i]; break; } } } if (!e) { LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, info->data.yin->name); return EXIT_FAILURE; } /* we have the extension definition, so now it cannot be forward referenced and error is always fatal */ if (e->plugin && e->plugin->check_position) { /* common part - we have plugin with position checking function, use it first */ if ((*e->plugin->check_position)(info->parent, info->parent_type, info->substmt)) { /* extension is not allowed here */ LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, e->name); return -1; } } /* extension type-specific part - allocation */ if (e->plugin) { etype = e->plugin->type; } else { /* default type */ etype = LYEXT_FLAG; } switch (etype) { case LYEXT_FLAG: (*ext) = calloc(1, sizeof(struct lys_ext_instance)); break; case LYEXT_COMPLEX: (*ext) = calloc(1, ((struct lyext_plugin_complex*)e->plugin)->instance_size); break; case LYEXT_ERR: /* we never should be here */ LOGINT(ctx); return -1; } LY_CHECK_ERR_RETURN(!*ext, LOGMEM(ctx), -1); /* common part for all extension types */ (*ext)->def = e; (*ext)->parent = info->parent; (*ext)->parent_type = info->parent_type; (*ext)->insubstmt = info->substmt; (*ext)->insubstmt_index = info->substmt_index; (*ext)->ext_type = e->plugin ? e->plugin->type : LYEXT_FLAG; (*ext)->flags |= e->plugin ? e->plugin->flags : 0; if (e->argument) { if (!(e->flags & LYS_YINELEM)) { (*ext)->arg_value = lyxml_get_attr(info->data.yin, e->argument, NULL); if (!(*ext)->arg_value) { LOGVAL(ctx, LYE_MISSARG, LY_VLOG_NONE, NULL, e->argument, info->data.yin->name); return -1; } (*ext)->arg_value = lydict_insert(mod->ctx, (*ext)->arg_value, 0); } else { LY_TREE_FOR_SAFE(info->data.yin->child, next_yin, yin) { if (ly_strequal(yin->name, e->argument, 1)) { (*ext)->arg_value = lydict_insert(mod->ctx, yin->content, 0); lyxml_free(mod->ctx, yin); break; } } } } if ((*ext)->flags & LYEXT_OPT_VALID && (info->parent_type == LYEXT_PAR_NODE || info->parent_type == LYEXT_PAR_TPDF)) { ((struct lys_node *)info->parent)->flags |= LYS_VALID_EXT; } (*ext)->nodetype = LYS_EXT; (*ext)->module = info->mod; /* extension type-specific part - parsing content */ switch (etype) { case LYEXT_FLAG: LY_TREE_FOR_SAFE(info->data.yin->child, next_yin, yin) { if (!yin->ns) { /* garbage */ lyxml_free(mod->ctx, yin); continue; } else if (!strcmp(yin->ns->value, LY_NSYIN)) { /* standard YANG statements are not expected here */ LOGVAL(ctx, LYE_INCHILDSTMT, vlog_type, vlog_node, yin->name, info->data.yin->name); return -1; } else if (yin->ns == info->data.yin->ns && (e->flags & LYS_YINELEM) && ly_strequal(yin->name, e->argument, 1)) { /* we have the extension's argument */ if ((*ext)->arg_value) { LOGVAL(ctx, LYE_TOOMANY, vlog_type, vlog_node, yin->name, info->data.yin->name); return -1; } (*ext)->arg_value = yin->content; yin->content = NULL; lyxml_free(mod->ctx, yin); } else { /* extension instance */ if (lyp_yin_parse_subnode_ext(info->mod, *ext, LYEXT_PAR_EXTINST, yin, LYEXT_SUBSTMT_SELF, 0, unres)) { return -1; } continue; } } break; case LYEXT_COMPLEX: ((struct lys_ext_instance_complex*)(*ext))->substmt = ((struct lyext_plugin_complex*)e->plugin)->substmt; if (lyp_yin_parse_complex_ext(info->mod, (struct lys_ext_instance_complex*)(*ext), info->data.yin, unres)) { /* TODO memory cleanup */ return -1; } break; default: break; } /* TODO - lyext_check_result_clb, other than LYEXT_FLAG plugins */ } else { /* YANG */ ext_prefix = (char *)(*ext)->def; tmp = strchr(ext_prefix, ':'); if (!tmp) { LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, ext_prefix); goto error; } ext_name = tmp + 1; /* get the module where the extension is supposed to be defined */ mod = lyp_get_module(info->mod, ext_prefix, tmp - ext_prefix, NULL, 0, 0); if (!mod) { LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, ext_prefix); return EXIT_FAILURE; } ctx = mod->ctx; /* find the extension definition */ e = NULL; for (i = 0; i < mod->extensions_size; i++) { if (ly_strequal(mod->extensions[i].name, ext_name, 0)) { e = &mod->extensions[i]; break; } } /* try submodules */ for (j = 0; !e && j < mod->inc_size; j++) { for (i = 0; i < mod->inc[j].submodule->extensions_size; i++) { if (ly_strequal(mod->inc[j].submodule->extensions[i].name, ext_name, 0)) { e = &mod->inc[j].submodule->extensions[i]; break; } } } if (!e) { LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, ext_prefix); return EXIT_FAILURE; } (*ext)->flags &= ~LYEXT_OPT_YANG; (*ext)->def = NULL; /* we have the extension definition, so now it cannot be forward referenced and error is always fatal */ if (e->plugin && e->plugin->check_position) { /* common part - we have plugin with position checking function, use it first */ if ((*e->plugin->check_position)(info->parent, info->parent_type, info->substmt)) { /* extension is not allowed here */ LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, e->name); goto error; } } if (e->argument && !(*ext)->arg_value) { LOGVAL(ctx, LYE_MISSARG, LY_VLOG_NONE, NULL, e->argument, ext_name); goto error; } /* extension common part */ (*ext)->def = e; (*ext)->parent = info->parent; (*ext)->ext_type = e->plugin ? e->plugin->type : LYEXT_FLAG; (*ext)->flags |= e->plugin ? e->plugin->flags : 0; if ((*ext)->flags & LYEXT_OPT_VALID && (info->parent_type == LYEXT_PAR_NODE || info->parent_type == LYEXT_PAR_TPDF)) { ((struct lys_node *)info->parent)->flags |= LYS_VALID_EXT; } (*ext)->module = info->mod; (*ext)->nodetype = LYS_EXT; /* extension type-specific part */ if (e->plugin) { etype = e->plugin->type; } else { /* default type */ etype = LYEXT_FLAG; } switch (etype) { case LYEXT_FLAG: /* nothing change */ break; case LYEXT_COMPLEX: tmp_ext = realloc(*ext, ((struct lyext_plugin_complex*)e->plugin)->instance_size); LY_CHECK_ERR_GOTO(!tmp_ext, LOGMEM(ctx), error); memset((char *)tmp_ext + offsetof(struct lys_ext_instance_complex, content), 0, ((struct lyext_plugin_complex*)e->plugin)->instance_size - offsetof(struct lys_ext_instance_complex, content)); (*ext) = tmp_ext; ((struct lys_ext_instance_complex*)(*ext))->substmt = ((struct lyext_plugin_complex*)e->plugin)->substmt; if (info->data.yang) { *tmp = ':'; if (yang_parse_ext_substatement(info->mod, unres, info->data.yang->ext_substmt, ext_prefix, (struct lys_ext_instance_complex*)(*ext))) { goto error; } if (yang_fill_extcomplex_module(info->mod->ctx, (struct lys_ext_instance_complex*)(*ext), ext_prefix, info->data.yang->ext_modules, info->mod->implemented)) { goto error; } } if (lyp_mand_check_ext((struct lys_ext_instance_complex*)(*ext), ext_prefix)) { goto error; } break; case LYEXT_ERR: /* we never should be here */ LOGINT(ctx); goto error; } if (yang_check_ext_instance(info->mod, &(*ext)->ext, (*ext)->ext_size, *ext, unres)) { goto error; } free(ext_prefix); } return EXIT_SUCCESS; error: free(ext_prefix); return -1; } /** * @brief Resolve (find) choice default case. Does not log. * * @param[in] choic Choice to use. * @param[in] dflt Name of the default case. * * @return Pointer to the default node or NULL. */ static struct lys_node * resolve_choice_dflt(struct lys_node_choice *choic, const char *dflt) { struct lys_node *child, *ret; LY_TREE_FOR(choic->child, child) { if (child->nodetype == LYS_USES) { ret = resolve_choice_dflt((struct lys_node_choice *)child, dflt); if (ret) { return ret; } } if (ly_strequal(child->name, dflt, 1) && (child->nodetype & (LYS_ANYDATA | LYS_CASE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_CHOICE))) { return child; } } return NULL; } /** * @brief Resolve uses, apply augments, refines. Logs directly. * * @param[in] uses Uses to use. * @param[in,out] unres List of unresolved items. * * @return EXIT_SUCCESS on success, -1 on error. */ static int resolve_uses(struct lys_node_uses *uses, struct unres_schema *unres) { struct ly_ctx *ctx = uses->module->ctx; /* shortcut */ struct lys_node *node = NULL, *next, *iter, **refine_nodes = NULL; struct lys_node *node_aux, *parent, *tmp; struct lys_node_leaflist *llist; struct lys_node_leaf *leaf; struct lys_refine *rfn; struct lys_restr *must, **old_must; struct lys_iffeature *iff, **old_iff; int i, j, k, rc; uint8_t size, *old_size; unsigned int usize, usize1, usize2; assert(uses->grp); /* check that the grouping is resolved (no unresolved uses inside) */ assert(!uses->grp->unres_count); /* copy the data nodes from grouping into the uses context */ LY_TREE_FOR(uses->grp->child, node_aux) { if (node_aux->nodetype & LYS_GROUPING) { /* do not instantiate groupings from groupings */ continue; } node = lys_node_dup(uses->module, (struct lys_node *)uses, node_aux, unres, 0); if (!node) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, uses->grp->name, "uses"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Copying data from grouping failed."); goto fail; } /* test the name of siblings */ LY_TREE_FOR((uses->parent) ? *lys_child(uses->parent, LYS_USES) : lys_main_module(uses->module)->data, tmp) { if (!(tmp->nodetype & (LYS_USES | LYS_GROUPING | LYS_CASE)) && ly_strequal(tmp->name, node_aux->name, 1)) { goto fail; } } } /* we managed to copy the grouping, the rest must be possible to resolve */ if (uses->refine_size) { refine_nodes = malloc(uses->refine_size * sizeof *refine_nodes); LY_CHECK_ERR_GOTO(!refine_nodes, LOGMEM(ctx), fail); } /* apply refines */ for (i = 0; i < uses->refine_size; i++) { rfn = &uses->refine[i]; rc = resolve_descendant_schema_nodeid(rfn->target_name, uses->child, LYS_NO_RPC_NOTIF_NODE | LYS_ACTION | LYS_NOTIF, 0, (const struct lys_node **)&node); if (rc || !node) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, rfn->target_name, "refine"); goto fail; } if (rfn->target_type && !(node->nodetype & rfn->target_type)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, rfn->target_name, "refine"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Refine substatements not applicable to the target-node."); goto fail; } refine_nodes[i] = node; /* description on any nodetype */ if (rfn->dsc) { lydict_remove(ctx, node->dsc); node->dsc = lydict_insert(ctx, rfn->dsc, 0); } /* reference on any nodetype */ if (rfn->ref) { lydict_remove(ctx, node->ref); node->ref = lydict_insert(ctx, rfn->ref, 0); } /* config on any nodetype, * in case of notification or rpc/action, the config is not applicable (there is no config status) */ if ((rfn->flags & LYS_CONFIG_MASK) && (node->flags & LYS_CONFIG_MASK)) { node->flags &= ~LYS_CONFIG_MASK; node->flags |= (rfn->flags & LYS_CONFIG_MASK); } /* default value ... */ if (rfn->dflt_size) { if (node->nodetype == LYS_LEAF) { /* leaf */ leaf = (struct lys_node_leaf *)node; /* replace default value */ lydict_remove(ctx, leaf->dflt); leaf->dflt = lydict_insert(ctx, rfn->dflt[0], 0); /* check the default value */ if (unres_schema_add_node(leaf->module, unres, &leaf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&leaf->dflt)) == -1) { goto fail; } } else if (node->nodetype == LYS_LEAFLIST) { /* leaf-list */ llist = (struct lys_node_leaflist *)node; /* remove complete set of defaults in target */ for (j = 0; j < llist->dflt_size; j++) { lydict_remove(ctx, llist->dflt[j]); } free(llist->dflt); /* copy the default set from refine */ llist->dflt = malloc(rfn->dflt_size * sizeof *llist->dflt); LY_CHECK_ERR_GOTO(!llist->dflt, LOGMEM(ctx), fail); llist->dflt_size = rfn->dflt_size; for (j = 0; j < llist->dflt_size; j++) { llist->dflt[j] = lydict_insert(ctx, rfn->dflt[j], 0); } /* check default value */ for (j = 0; j < llist->dflt_size; j++) { if (unres_schema_add_node(llist->module, unres, &llist->type, UNRES_TYPE_DFLT, (struct lys_node *)(&llist->dflt[j])) == -1) { goto fail; } } } } /* mandatory on leaf, anyxml or choice */ if (rfn->flags & LYS_MAND_MASK) { /* remove current value */ node->flags &= ~LYS_MAND_MASK; /* set new value */ node->flags |= (rfn->flags & LYS_MAND_MASK); if (rfn->flags & LYS_MAND_TRUE) { /* check if node has default value */ if ((node->nodetype & LYS_LEAF) && ((struct lys_node_leaf *)node)->dflt) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses, "The \"mandatory\" statement is forbidden on leaf with \"default\"."); goto fail; } if ((node->nodetype & LYS_CHOICE) && ((struct lys_node_choice *)node)->dflt) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses, "The \"mandatory\" statement is forbidden on choices with \"default\"."); goto fail; } } } /* presence on container */ if ((node->nodetype & LYS_CONTAINER) && rfn->mod.presence) { lydict_remove(ctx, ((struct lys_node_container *)node)->presence); ((struct lys_node_container *)node)->presence = lydict_insert(ctx, rfn->mod.presence, 0); } /* min/max-elements on list or leaf-list */ if (node->nodetype == LYS_LIST) { if (rfn->flags & LYS_RFN_MINSET) { ((struct lys_node_list *)node)->min = rfn->mod.list.min; } if (rfn->flags & LYS_RFN_MAXSET) { ((struct lys_node_list *)node)->max = rfn->mod.list.max; } } else if (node->nodetype == LYS_LEAFLIST) { if (rfn->flags & LYS_RFN_MINSET) { ((struct lys_node_leaflist *)node)->min = rfn->mod.list.min; } if (rfn->flags & LYS_RFN_MAXSET) { ((struct lys_node_leaflist *)node)->max = rfn->mod.list.max; } } /* must in leaf, leaf-list, list, container or anyxml */ if (rfn->must_size) { switch (node->nodetype) { case LYS_LEAF: old_size = &((struct lys_node_leaf *)node)->must_size; old_must = &((struct lys_node_leaf *)node)->must; break; case LYS_LEAFLIST: old_size = &((struct lys_node_leaflist *)node)->must_size; old_must = &((struct lys_node_leaflist *)node)->must; break; case LYS_LIST: old_size = &((struct lys_node_list *)node)->must_size; old_must = &((struct lys_node_list *)node)->must; break; case LYS_CONTAINER: old_size = &((struct lys_node_container *)node)->must_size; old_must = &((struct lys_node_container *)node)->must; break; case LYS_ANYXML: case LYS_ANYDATA: old_size = &((struct lys_node_anydata *)node)->must_size; old_must = &((struct lys_node_anydata *)node)->must; break; default: LOGINT(ctx); goto fail; } size = *old_size + rfn->must_size; must = realloc(*old_must, size * sizeof *rfn->must); LY_CHECK_ERR_GOTO(!must, LOGMEM(ctx), fail); for (k = 0, j = *old_size; k < rfn->must_size; k++, j++) { must[j].ext_size = rfn->must[k].ext_size; lys_ext_dup(ctx, rfn->module, rfn->must[k].ext, rfn->must[k].ext_size, &rfn->must[k], LYEXT_PAR_RESTR, &must[j].ext, 0, unres); must[j].expr = lydict_insert(ctx, rfn->must[k].expr, 0); must[j].dsc = lydict_insert(ctx, rfn->must[k].dsc, 0); must[j].ref = lydict_insert(ctx, rfn->must[k].ref, 0); must[j].eapptag = lydict_insert(ctx, rfn->must[k].eapptag, 0); must[j].emsg = lydict_insert(ctx, rfn->must[k].emsg, 0); must[j].flags = rfn->must[k].flags; } *old_must = must; *old_size = size; /* check XPath dependencies again */ if (unres_schema_add_node(node->module, unres, node, UNRES_XPATH, NULL) == -1) { goto fail; } } /* if-feature in leaf, leaf-list, list, container or anyxml */ if (rfn->iffeature_size) { old_size = &node->iffeature_size; old_iff = &node->iffeature; size = *old_size + rfn->iffeature_size; iff = realloc(*old_iff, size * sizeof *rfn->iffeature); LY_CHECK_ERR_GOTO(!iff, LOGMEM(ctx), fail); *old_iff = iff; for (k = 0, j = *old_size; k < rfn->iffeature_size; k++, j++) { resolve_iffeature_getsizes(&rfn->iffeature[k], &usize1, &usize2); if (usize1) { /* there is something to duplicate */ /* duplicate compiled expression */ usize = (usize1 / 4) + (usize1 % 4) ? 1 : 0; iff[j].expr = malloc(usize * sizeof *iff[j].expr); LY_CHECK_ERR_GOTO(!iff[j].expr, LOGMEM(ctx), fail); memcpy(iff[j].expr, rfn->iffeature[k].expr, usize * sizeof *iff[j].expr); /* duplicate list of feature pointers */ iff[j].features = malloc(usize2 * sizeof *iff[k].features); LY_CHECK_ERR_GOTO(!iff[j].expr, LOGMEM(ctx), fail); memcpy(iff[j].features, rfn->iffeature[k].features, usize2 * sizeof *iff[j].features); /* duplicate extensions */ iff[j].ext_size = rfn->iffeature[k].ext_size; lys_ext_dup(ctx, rfn->module, rfn->iffeature[k].ext, rfn->iffeature[k].ext_size, &rfn->iffeature[k], LYEXT_PAR_IFFEATURE, &iff[j].ext, 0, unres); } (*old_size)++; } assert(*old_size == size); } } /* apply augments */ for (i = 0; i < uses->augment_size; i++) { rc = resolve_augment(&uses->augment[i], (struct lys_node *)uses, unres); if (rc) { goto fail; } } /* check refines */ for (i = 0; i < uses->refine_size; i++) { node = refine_nodes[i]; rfn = &uses->refine[i]; /* config on any nodetype */ if ((rfn->flags & LYS_CONFIG_MASK) && (node->flags & LYS_CONFIG_MASK)) { for (parent = lys_parent(node); parent && parent->nodetype == LYS_USES; parent = lys_parent(parent)); if (parent && parent->nodetype != LYS_GROUPING && (parent->flags & LYS_CONFIG_MASK) && ((parent->flags & LYS_CONFIG_MASK) != (rfn->flags & LYS_CONFIG_MASK)) && (rfn->flags & LYS_CONFIG_W)) { /* setting config true under config false is prohibited */ LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, "config", "refine"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "changing config from 'false' to 'true' is prohibited while " "the target's parent is still config 'false'."); goto fail; } /* inherit config change to the target children */ LY_TREE_DFS_BEGIN(node->child, next, iter) { if (rfn->flags & LYS_CONFIG_W) { if (iter->flags & LYS_CONFIG_SET) { /* config is set explicitely, go to next sibling */ next = NULL; goto nextsibling; } } else { /* LYS_CONFIG_R */ if ((iter->flags & LYS_CONFIG_SET) && (iter->flags & LYS_CONFIG_W)) { /* error - we would have config data under status data */ LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, "config", "refine"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "changing config from 'true' to 'false' is prohibited while the target " "has still a children with explicit config 'true'."); goto fail; } } /* change config */ iter->flags &= ~LYS_CONFIG_MASK; iter->flags |= (rfn->flags & LYS_CONFIG_MASK); /* select next iter - modified LY_TREE_DFS_END */ if (iter->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { next = NULL; } else { next = iter->child; } nextsibling: if (!next) { /* try siblings */ next = iter->next; } while (!next) { /* parent is already processed, go to its sibling */ iter = lys_parent(iter); /* no siblings, go back through parents */ if (iter == node) { /* we are done, no next element to process */ break; } next = iter->next; } } } /* default value */ if (rfn->dflt_size) { if (node->nodetype == LYS_CHOICE) { /* choice */ ((struct lys_node_choice *)node)->dflt = resolve_choice_dflt((struct lys_node_choice *)node, rfn->dflt[0]); if (!((struct lys_node_choice *)node)->dflt) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, rfn->dflt[0], "default"); goto fail; } if (lyp_check_mandatory_choice(node)) { goto fail; } } } /* min/max-elements on list or leaf-list */ if (node->nodetype == LYS_LIST && ((struct lys_node_list *)node)->max) { if (((struct lys_node_list *)node)->min > ((struct lys_node_list *)node)->max) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses, "Invalid value \"%d\" of \"%s\".", rfn->mod.list.min, "min-elements"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "\"min-elements\" is bigger than \"max-elements\"."); goto fail; } } else if (node->nodetype == LYS_LEAFLIST && ((struct lys_node_leaflist *)node)->max) { if (((struct lys_node_leaflist *)node)->min > ((struct lys_node_leaflist *)node)->max) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses, "Invalid value \"%d\" of \"%s\".", rfn->mod.list.min, "min-elements"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "\"min-elements\" is bigger than \"max-elements\"."); goto fail; } } /* additional checks */ /* default value with mandatory/min-elements */ if (node->nodetype == LYS_LEAFLIST) { llist = (struct lys_node_leaflist *)node; if (llist->dflt_size && llist->min) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, uses, rfn->dflt_size ? "default" : "min-elements", "refine"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement."); goto fail; } } else if (node->nodetype == LYS_LEAF) { leaf = (struct lys_node_leaf *)node; if (leaf->dflt && (leaf->flags & LYS_MAND_TRUE)) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, uses, rfn->dflt_size ? "default" : "mandatory", "refine"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "The \"mandatory\" statement is forbidden on leafs with the \"default\" statement."); goto fail; } } /* check for mandatory node in default case, first find the closest parent choice to the changed node */ if ((rfn->flags & LYS_MAND_TRUE) || rfn->mod.list.min) { for (parent = node->parent; parent && !(parent->nodetype & (LYS_CHOICE | LYS_GROUPING | LYS_ACTION | LYS_USES)); parent = parent->parent) { if (parent->nodetype == LYS_CONTAINER && ((struct lys_node_container *)parent)->presence) { /* stop also on presence containers */ break; } } /* and if it is a choice with the default case, check it for presence of a mandatory node in it */ if (parent && parent->nodetype == LYS_CHOICE && ((struct lys_node_choice *)parent)->dflt) { if (lyp_check_mandatory_choice(parent)) { goto fail; } } } } free(refine_nodes); return EXIT_SUCCESS; fail: LY_TREE_FOR_SAFE(uses->child, next, iter) { lys_node_free(iter, NULL, 0); } free(refine_nodes); return -1; } void resolve_identity_backlink_update(struct lys_ident *der, struct lys_ident *base) { int i; assert(der && base); if (!base->der) { /* create a set for backlinks if it does not exist */ base->der = ly_set_new(); } /* store backlink */ ly_set_add(base->der, der, LY_SET_OPT_USEASLIST); /* do it recursively */ for (i = 0; i < base->base_size; i++) { resolve_identity_backlink_update(der, base->base[i]); } } /** * @brief Resolve base identity recursively. Does not log. * * @param[in] module Main module. * @param[in] ident Identity to use. * @param[in] basename Base name of the identity. * @param[out] ret Pointer to the resolved identity. Can be NULL. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on crucial error. */ static int resolve_base_ident_sub(const struct lys_module *module, struct lys_ident *ident, const char *basename, struct unres_schema *unres, struct lys_ident **ret) { uint32_t i, j; struct lys_ident *base = NULL; struct ly_ctx *ctx = module->ctx; assert(ret); /* search module */ for (i = 0; i < module->ident_size; i++) { if (!strcmp(basename, module->ident[i].name)) { if (!ident) { /* just search for type, so do not modify anything, just return * the base identity pointer */ *ret = &module->ident[i]; return EXIT_SUCCESS; } base = &module->ident[i]; goto matchfound; } } /* search submodules */ for (j = 0; j < module->inc_size && module->inc[j].submodule; j++) { for (i = 0; i < module->inc[j].submodule->ident_size; i++) { if (!strcmp(basename, module->inc[j].submodule->ident[i].name)) { if (!ident) { *ret = &module->inc[j].submodule->ident[i]; return EXIT_SUCCESS; } base = &module->inc[j].submodule->ident[i]; goto matchfound; } } } matchfound: /* we found it somewhere */ if (base) { /* is it already completely resolved? */ for (i = 0; i < unres->count; i++) { if ((unres->item[i] == base) && (unres->type[i] == UNRES_IDENT)) { /* identity found, but not yet resolved, so do not return it in *res and try it again later */ /* simple check for circular reference, * the complete check is done as a side effect of using only completely * resolved identities (previous check of unres content) */ if (ly_strequal((const char *)unres->str_snode[i], ident->name, 1)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, basename, "base"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Circular reference of \"%s\" identity.", basename); return -1; } return EXIT_FAILURE; } } /* checks done, store the result */ *ret = base; return EXIT_SUCCESS; } /* base not found (maybe a forward reference) */ return EXIT_FAILURE; } /** * @brief Resolve base identity. Logs directly. * * @param[in] module Main module. * @param[in] ident Identity to use. * @param[in] basename Base name of the identity. * @param[in] parent Either "type" or "identity". * @param[in,out] type Type structure where we want to resolve identity. Can be NULL. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_base_ident(const struct lys_module *module, struct lys_ident *ident, const char *basename, const char *parent, struct lys_type *type, struct unres_schema *unres) { const char *name; int mod_name_len = 0, rc; struct lys_ident *target, **ret; uint16_t flags; struct lys_module *mod; struct ly_ctx *ctx = module->ctx; assert((ident && !type) || (!ident && type)); if (!type) { /* have ident to resolve */ ret = &target; flags = ident->flags; mod = ident->module; } else { /* have type to fill */ ++type->info.ident.count; type->info.ident.ref = ly_realloc(type->info.ident.ref, type->info.ident.count * sizeof *type->info.ident.ref); LY_CHECK_ERR_RETURN(!type->info.ident.ref, LOGMEM(ctx), -1); ret = &type->info.ident.ref[type->info.ident.count - 1]; flags = type->parent->flags; mod = type->parent->module; } *ret = NULL; /* search for the base identity */ name = strchr(basename, ':'); if (name) { /* set name to correct position after colon */ mod_name_len = name - basename; name++; if (!strncmp(basename, module->name, mod_name_len) && !module->name[mod_name_len]) { /* prefix refers to the current module, ignore it */ mod_name_len = 0; } } else { name = basename; } /* get module where to search */ module = lyp_get_module(module, NULL, 0, mod_name_len ? basename : NULL, mod_name_len, 0); if (!module) { /* identity refers unknown data model */ LOGVAL(ctx, LYE_INMOD, LY_VLOG_NONE, NULL, basename); return -1; } /* search in the identified module ... */ rc = resolve_base_ident_sub(module, ident, name, unres, ret); if (!rc) { assert(*ret); /* check status */ if (lyp_check_status(flags, mod, ident ? ident->name : "of type", (*ret)->flags, (*ret)->module, (*ret)->name, NULL)) { rc = -1; } else if (ident) { ident->base[ident->base_size++] = *ret; if (lys_main_module(mod)->implemented) { /* in case of the implemented identity, maintain backlinks to it * from the base identities to make it available when resolving * data with the identity values (not implemented identity is not * allowed as an identityref value). */ resolve_identity_backlink_update(ident, *ret); } } } else if (rc == EXIT_FAILURE) { LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_NONE, NULL, parent, basename); if (type) { --type->info.ident.count; } } return rc; } /* * 1 - true (der is derived from base) * 0 - false (der is not derived from base) */ static int search_base_identity(struct lys_ident *der, struct lys_ident *base) { int i; if (der == base) { return 1; } else { for(i = 0; i < der->base_size; i++) { if (search_base_identity(der->base[i], base) == 1) { return 1; } } } return 0; } /** * @brief Resolve JSON data format identityref. Logs directly. * * @param[in] type Identityref type. * @param[in] ident_name Identityref name. * @param[in] node Node where the identityref is being resolved * @param[in] dflt flag if we are resolving default value in the schema * * @return Pointer to the identity resolvent, NULL on error. */ struct lys_ident * resolve_identref(struct lys_type *type, const char *ident_name, struct lyd_node *node, struct lys_module *mod, int dflt) { const char *mod_name, *name; char *str; int mod_name_len, nam_len, rc; int need_implemented = 0; unsigned int i, j; struct lys_ident *der, *cur; struct lys_module *imod = NULL, *m, *tmod; struct ly_ctx *ctx; assert(type && ident_name && mod); ctx = mod->ctx; if (!type || (!type->info.ident.count && !type->der) || !ident_name) { return NULL; } rc = parse_node_identifier(ident_name, &mod_name, &mod_name_len, &name, &nam_len, NULL, 0); if (rc < 1) { LOGVAL(ctx, LYE_INCHAR, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, ident_name[-rc], &ident_name[-rc]); return NULL; } else if (rc < (signed)strlen(ident_name)) { LOGVAL(ctx, LYE_INCHAR, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, ident_name[rc], &ident_name[rc]); return NULL; } m = lys_main_module(mod); /* shortcut */ if (!mod_name || (!strncmp(mod_name, m->name, mod_name_len) && !m->name[mod_name_len])) { /* identity is defined in the same module as node */ imod = m; } else if (dflt) { /* solving identityref in default definition in schema - * find the identity's module in the imported modules list to have a correct revision */ for (i = 0; i < mod->imp_size; i++) { if (!strncmp(mod_name, mod->imp[i].module->name, mod_name_len) && !mod->imp[i].module->name[mod_name_len]) { imod = mod->imp[i].module; break; } } /* We may need to pull it from the module that the typedef came from */ if (!imod && type && type->der) { tmod = type->der->module; for (i = 0; i < tmod->imp_size; i++) { if (!strncmp(mod_name, tmod->imp[i].module->name, mod_name_len) && !tmod->imp[i].module->name[mod_name_len]) { imod = tmod->imp[i].module; break; } } } } else { /* solving identityref in data - get the module from the context */ for (i = 0; i < (unsigned)mod->ctx->models.used; ++i) { imod = mod->ctx->models.list[i]; if (!strncmp(mod_name, imod->name, mod_name_len) && !imod->name[mod_name_len]) { break; } imod = NULL; } if (!imod && mod->ctx->models.parsing_sub_modules_count) { /* we are currently parsing some module and checking XPath or a default value, * so take this module into account */ for (i = 0; i < mod->ctx->models.parsing_sub_modules_count; i++) { imod = mod->ctx->models.parsing_sub_modules[i]; if (imod->type) { /* skip submodules */ continue; } if (!strncmp(mod_name, imod->name, mod_name_len) && !imod->name[mod_name_len]) { break; } imod = NULL; } } } if (!dflt && (!imod || !imod->implemented) && ctx->data_clb) { /* the needed module was not found, but it may have been expected so call the data callback */ if (imod) { ctx->data_clb(ctx, imod->name, imod->ns, LY_MODCLB_NOT_IMPLEMENTED, ctx->data_clb_data); } else if (mod_name) { str = strndup(mod_name, mod_name_len); imod = (struct lys_module *)ctx->data_clb(ctx, str, NULL, 0, ctx->data_clb_data); free(str); } } if (!imod) { goto fail; } if (m != imod || lys_main_module(type->parent->module) != mod) { /* the type is not referencing the same schema, * THEN, we may need to make the module with the identity implemented, but only if it really * contains the identity */ if (!imod->implemented) { cur = NULL; /* get the identity in the module */ for (i = 0; i < imod->ident_size; i++) { if (!strcmp(name, imod->ident[i].name)) { cur = &imod->ident[i]; break; } } if (!cur) { /* go through includes */ for (j = 0; j < imod->inc_size; j++) { for (i = 0; i < imod->inc[j].submodule->ident_size; i++) { if (!strcmp(name, imod->inc[j].submodule->ident[i].name)) { cur = &imod->inc[j].submodule->ident[i]; break; } } } if (!cur) { goto fail; } } /* check that identity is derived from one of the type's base */ while (type->der) { for (i = 0; i < type->info.ident.count; i++) { if (search_base_identity(cur, type->info.ident.ref[i])) { /* cur's base matches the type's base */ need_implemented = 1; goto match; } } type = &type->der->type; } /* matching base not found */ LOGVAL(ctx, LYE_SPEC, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, "Identity used as identityref value is not implemented."); goto fail; } } /* go through all the derived types of all the bases */ while (type->der) { for (i = 0; i < type->info.ident.count; ++i) { cur = type->info.ident.ref[i]; if (cur->der) { /* there are some derived identities */ for (j = 0; j < cur->der->number; j++) { der = (struct lys_ident *)cur->der->set.g[j]; /* shortcut */ if (!strcmp(der->name, name) && lys_main_module(der->module) == imod) { /* we have match */ cur = der; goto match; } } } } type = &type->der->type; } fail: LOGVAL(ctx, LYE_INRESOLV, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, "identityref", ident_name); return NULL; match: for (i = 0; i < cur->iffeature_size; i++) { if (!resolve_iffeature(&cur->iffeature[i])) { if (node) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, node, cur->name, node->schema->name); } LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Identity \"%s\" is disabled by its if-feature condition.", cur->name); return NULL; } } if (need_implemented) { if (dflt) { /* later try to make the module implemented */ LOGVRB("Making \"%s\" module implemented because of identityref default value \"%s\" used in the implemented \"%s\" module", imod->name, cur->name, mod->name); /* to be more effective we should use UNRES_MOD_IMPLEMENT but that would require changing prototype of * several functions with little gain */ if (lys_set_implemented(imod)) { LOGERR(ctx, ly_errno, "Setting the module \"%s\" implemented because of used default identity \"%s\" failed.", imod->name, cur->name); goto fail; } } else { /* just say that it was found, but in a non-implemented module */ LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Identity found, but in a non-implemented module \"%s\".", lys_main_module(cur->module)->name); goto fail; } } return cur; } /** * @brief Resolve unresolved uses. Logs directly. * * @param[in] uses Uses to use. * @param[in] unres Specific unres item. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_unres_schema_uses(struct lys_node_uses *uses, struct unres_schema *unres) { int rc; struct lys_node *par_grp; struct ly_ctx *ctx = uses->module->ctx; /* HACK: when a grouping has uses inside, all such uses have to be resolved before the grouping itself is used * in some uses. When we see such a uses, the grouping's unres counter is used to store number of so far * unresolved uses. The grouping cannot be used unless this counter is decreased back to 0. To remember * that the uses already increased grouping's counter, the LYS_USESGRP flag is used. */ for (par_grp = lys_parent((struct lys_node *)uses); par_grp && (par_grp->nodetype != LYS_GROUPING); par_grp = lys_parent(par_grp)); if (par_grp && ly_strequal(par_grp->name, uses->name, 1)) { LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name); return -1; } if (!uses->grp) { rc = resolve_uses_schema_nodeid(uses->name, (const struct lys_node *)uses, (const struct lys_node_grp **)&uses->grp); if (rc == -1) { LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name); return -1; } else if (rc > 0) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, uses, uses->name[rc - 1], &uses->name[rc - 1]); return -1; } else if (!uses->grp) { if (par_grp && !(uses->flags & LYS_USESGRP)) { if (++((struct lys_node_grp *)par_grp)->unres_count == 0) { LOGERR(ctx, LY_EINT, "Too many unresolved items (uses) inside a grouping."); return -1; } uses->flags |= LYS_USESGRP; } LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name); return EXIT_FAILURE; } } if (uses->grp->unres_count) { if (par_grp && !(uses->flags & LYS_USESGRP)) { if (++((struct lys_node_grp *)par_grp)->unres_count == 0) { LOGERR(ctx, LY_EINT, "Too many unresolved items (uses) inside a grouping."); return -1; } uses->flags |= LYS_USESGRP; } else { /* instantiate grouping only when it is completely resolved */ uses->grp = NULL; } LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name); return EXIT_FAILURE; } rc = resolve_uses(uses, unres); if (!rc) { /* decrease unres count only if not first try */ if (par_grp && (uses->flags & LYS_USESGRP)) { assert(((struct lys_node_grp *)par_grp)->unres_count); ((struct lys_node_grp *)par_grp)->unres_count--; uses->flags &= ~LYS_USESGRP; } /* check status */ if (lyp_check_status(uses->flags, uses->module, "of uses", uses->grp->flags, uses->grp->module, uses->grp->name, (struct lys_node *)uses)) { return -1; } return EXIT_SUCCESS; } return rc; } /** * @brief Resolve list keys. Logs directly. * * @param[in] list List to use. * @param[in] keys_str Keys node value. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_list_keys(struct lys_node_list *list, const char *keys_str) { int i, len, rc; const char *value; char *s = NULL; struct ly_ctx *ctx = list->module->ctx; for (i = 0; i < list->keys_size; ++i) { assert(keys_str); if (!list->child) { /* no child, possible forward reference */ LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, list, "list keys", keys_str); return EXIT_FAILURE; } /* get the key name */ if ((value = strpbrk(keys_str, " \t\n"))) { len = value - keys_str; while (isspace(value[0])) { value++; } } else { len = strlen(keys_str); } rc = lys_getnext_data(lys_node_module((struct lys_node *)list), (struct lys_node *)list, keys_str, len, LYS_LEAF, LYS_GETNEXT_NOSTATECHECK, (const struct lys_node **)&list->keys[i]); if (rc) { LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, list, "list key", keys_str); return EXIT_FAILURE; } if (check_key(list, i, keys_str, len)) { /* check_key logs */ return -1; } /* check status */ if (lyp_check_status(list->flags, list->module, list->name, list->keys[i]->flags, list->keys[i]->module, list->keys[i]->name, (struct lys_node *)list->keys[i])) { return -1; } /* default value - is ignored, keep it but print a warning */ if (list->keys[i]->dflt) { /* log is not hidden only in case this resolving fails and in such a case * we cannot get here */ assert(log_opt == ILO_STORE); log_opt = ILO_LOG; LOGWRN(ctx, "Default value \"%s\" in the list key \"%s\" is ignored. (%s)", list->keys[i]->dflt, list->keys[i]->name, s = lys_path((struct lys_node*)list, LYS_PATH_FIRST_PREFIX)); log_opt = ILO_STORE; free(s); } /* prepare for next iteration */ while (value && isspace(value[0])) { value++; } keys_str = value; } return EXIT_SUCCESS; } /** * @brief Resolve (check) all must conditions of \p node. * Logs directly. * * @param[in] node Data node with optional must statements. * @param[in] inout_parent If set, must in input or output parent of node->schema will be resolved. * * @return EXIT_SUCCESS on pass, EXIT_FAILURE on fail, -1 on error. */ static int resolve_must(struct lyd_node *node, int inout_parent, int ignore_fail) { uint8_t i, must_size; struct lys_node *schema; struct lys_restr *must; struct lyxp_set set; struct ly_ctx *ctx = node->schema->module->ctx; assert(node); memset(&set, 0, sizeof set); if (inout_parent) { for (schema = lys_parent(node->schema); schema && (schema->nodetype & (LYS_CHOICE | LYS_CASE | LYS_USES)); schema = lys_parent(schema)); if (!schema || !(schema->nodetype & (LYS_INPUT | LYS_OUTPUT))) { LOGINT(ctx); return -1; } must_size = ((struct lys_node_inout *)schema)->must_size; must = ((struct lys_node_inout *)schema)->must; /* context node is the RPC/action */ node = node->parent; if (!(node->schema->nodetype & (LYS_RPC | LYS_ACTION))) { LOGINT(ctx); return -1; } } else { switch (node->schema->nodetype) { case LYS_CONTAINER: must_size = ((struct lys_node_container *)node->schema)->must_size; must = ((struct lys_node_container *)node->schema)->must; break; case LYS_LEAF: must_size = ((struct lys_node_leaf *)node->schema)->must_size; must = ((struct lys_node_leaf *)node->schema)->must; break; case LYS_LEAFLIST: must_size = ((struct lys_node_leaflist *)node->schema)->must_size; must = ((struct lys_node_leaflist *)node->schema)->must; break; case LYS_LIST: must_size = ((struct lys_node_list *)node->schema)->must_size; must = ((struct lys_node_list *)node->schema)->must; break; case LYS_ANYXML: case LYS_ANYDATA: must_size = ((struct lys_node_anydata *)node->schema)->must_size; must = ((struct lys_node_anydata *)node->schema)->must; break; case LYS_NOTIF: must_size = ((struct lys_node_notif *)node->schema)->must_size; must = ((struct lys_node_notif *)node->schema)->must; break; default: must_size = 0; break; } } for (i = 0; i < must_size; ++i) { if (lyxp_eval(must[i].expr, node, LYXP_NODE_ELEM, lyd_node_module(node), &set, LYXP_MUST)) { return -1; } lyxp_set_cast(&set, LYXP_SET_BOOLEAN, node, lyd_node_module(node), LYXP_MUST); if (!set.val.bool) { if ((ignore_fail == 1) || ((must[i].flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) && (ignore_fail == 2))) { LOGVRB("Must condition \"%s\" not satisfied, but it is not required.", must[i].expr); } else { LOGVAL(ctx, LYE_NOMUST, LY_VLOG_LYD, node, must[i].expr); if (must[i].emsg) { ly_vlog_str(ctx, LY_VLOG_PREV, must[i].emsg); } if (must[i].eapptag) { ly_err_last_set_apptag(ctx, must[i].eapptag); } return 1; } } } return EXIT_SUCCESS; } /** * @brief Resolve (find) when condition schema context node. Does not log. * * @param[in] schema Schema node with the when condition. * @param[out] ctx_snode When schema context node. * @param[out] ctx_snode_type Schema context node type. */ void resolve_when_ctx_snode(const struct lys_node *schema, struct lys_node **ctx_snode, enum lyxp_node_type *ctx_snode_type) { const struct lys_node *sparent; /* find a not schema-only node */ *ctx_snode_type = LYXP_NODE_ELEM; while (schema->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE | LYS_AUGMENT | LYS_INPUT | LYS_OUTPUT)) { if (schema->nodetype == LYS_AUGMENT) { sparent = ((struct lys_node_augment *)schema)->target; } else { sparent = schema->parent; } if (!sparent) { /* context node is the document root (fake root in our case) */ if (schema->flags & LYS_CONFIG_W) { *ctx_snode_type = LYXP_NODE_ROOT_CONFIG; } else { *ctx_snode_type = LYXP_NODE_ROOT; } /* we need the first top-level sibling, but no uses or groupings */ schema = lys_getnext(NULL, NULL, lys_node_module(schema), LYS_GETNEXT_NOSTATECHECK); break; } schema = sparent; } *ctx_snode = (struct lys_node *)schema; } /** * @brief Resolve (find) when condition context node. Does not log. * * @param[in] node Data node, whose conditional definition is being decided. * @param[in] schema Schema node with the when condition. * @param[out] ctx_node Context node. * @param[out] ctx_node_type Context node type. * * @return EXIT_SUCCESS on success, -1 on error. */ static int resolve_when_ctx_node(struct lyd_node *node, struct lys_node *schema, struct lyd_node **ctx_node, enum lyxp_node_type *ctx_node_type) { struct lyd_node *parent; struct lys_node *sparent; enum lyxp_node_type node_type; uint16_t i, data_depth, schema_depth; resolve_when_ctx_snode(schema, &schema, &node_type); if (node_type == LYXP_NODE_ELEM) { /* standard element context node */ for (parent = node, data_depth = 0; parent; parent = parent->parent, ++data_depth); for (sparent = schema, schema_depth = 0; sparent; sparent = (sparent->nodetype == LYS_AUGMENT ? ((struct lys_node_augment *)sparent)->target : sparent->parent)) { if (sparent->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_ANYDATA | LYS_NOTIF | LYS_RPC)) { ++schema_depth; } } if (data_depth < schema_depth) { return -1; } /* find the corresponding data node */ for (i = 0; i < data_depth - schema_depth; ++i) { node = node->parent; } if (node->schema != schema) { return -1; } } else { /* root context node */ while (node->parent) { node = node->parent; } while (node->prev->next) { node = node->prev; } } *ctx_node = node; *ctx_node_type = node_type; return EXIT_SUCCESS; } /** * @brief Temporarily unlink nodes as per YANG 1.1 RFC section 7.21.5 for when XPath evaluation. * The context node is adjusted if needed. * * @param[in] snode Schema node, whose children instances need to be unlinked. * @param[in,out] node Data siblings where to look for the children of \p snode. If it is unlinked, * it is moved to point to another sibling still in the original tree. * @param[in,out] ctx_node When context node, adjusted if needed. * @param[in] ctx_node_type Context node type, just for information to detect invalid situations. * @param[out] unlinked_nodes Unlinked siblings. Can be safely appended to \p node afterwards. * Ordering may change, but there will be no semantic change. * * @return EXIT_SUCCESS on success, -1 on error. */ static int resolve_when_unlink_nodes(struct lys_node *snode, struct lyd_node **node, struct lyd_node **ctx_node, enum lyxp_node_type ctx_node_type, struct lyd_node **unlinked_nodes) { struct lyd_node *next, *elem; const struct lys_node *slast; struct ly_ctx *ctx = snode->module->ctx; switch (snode->nodetype) { case LYS_AUGMENT: case LYS_USES: case LYS_CHOICE: case LYS_CASE: slast = NULL; while ((slast = lys_getnext(slast, snode, NULL, LYS_GETNEXT_PARENTUSES))) { if (slast->nodetype & (LYS_ACTION | LYS_NOTIF)) { continue; } if (resolve_when_unlink_nodes((struct lys_node *)slast, node, ctx_node, ctx_node_type, unlinked_nodes)) { return -1; } } break; case LYS_CONTAINER: case LYS_LIST: case LYS_LEAF: case LYS_LEAFLIST: case LYS_ANYXML: case LYS_ANYDATA: LY_TREE_FOR_SAFE(lyd_first_sibling(*node), next, elem) { if (elem->schema == snode) { if (elem == *ctx_node) { /* We are going to unlink our context node! This normally cannot happen, * but we use normal top-level data nodes for faking a document root node, * so if this is the context node, we just use the next top-level node. * Additionally, it can even happen that there are no top-level data nodes left, * all were unlinked, so in this case we pass NULL as the context node/data tree, * lyxp_eval() can handle this special situation. */ if (ctx_node_type == LYXP_NODE_ELEM) { LOGINT(ctx); return -1; } if (elem->prev == elem) { /* unlinking last top-level element, use an empty data tree */ *ctx_node = NULL; } else { /* in this case just use the previous/last top-level data node */ *ctx_node = elem->prev; } } else if (elem == *node) { /* We are going to unlink the currently processed node. This does not matter that * much, but we would lose access to the original data tree, so just move our * pointer somewhere still inside it. */ if ((*node)->prev != *node) { *node = (*node)->prev; } else { /* the processed node with sibings were all unlinked, oh well */ *node = NULL; } } /* temporarily unlink the node */ lyd_unlink_internal(elem, 0); if (*unlinked_nodes) { if (lyd_insert_after((*unlinked_nodes)->prev, elem)) { LOGINT(ctx); return -1; } } else { *unlinked_nodes = elem; } if (snode->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_ANYDATA)) { /* there can be only one instance */ break; } } } break; default: LOGINT(ctx); return -1; } return EXIT_SUCCESS; } /** * @brief Relink the unlinked nodes back. * * @param[in] node Data node to link the nodes back to. It can actually be the adjusted context node, * we simply need a sibling from the original data tree. * @param[in] unlinked_nodes Unlinked nodes to relink to \p node. * @param[in] ctx_node_type Context node type to distinguish between \p node being the parent * or the sibling of \p unlinked_nodes. * * @return EXIT_SUCCESS on success, -1 on error. */ static int resolve_when_relink_nodes(struct lyd_node *node, struct lyd_node *unlinked_nodes, enum lyxp_node_type ctx_node_type) { struct lyd_node *elem; LY_TREE_FOR_SAFE(unlinked_nodes, unlinked_nodes, elem) { lyd_unlink_internal(elem, 0); if (ctx_node_type == LYXP_NODE_ELEM) { if (lyd_insert_common(node, NULL, elem, 0)) { return -1; } } else { if (lyd_insert_nextto(node, elem, 0, 0)) { return -1; } } } return EXIT_SUCCESS; } int resolve_applies_must(const struct lyd_node *node) { int ret = 0; uint8_t must_size; struct lys_node *schema, *iter; assert(node); schema = node->schema; /* their own must */ switch (schema->nodetype) { case LYS_CONTAINER: must_size = ((struct lys_node_container *)schema)->must_size; break; case LYS_LEAF: must_size = ((struct lys_node_leaf *)schema)->must_size; break; case LYS_LEAFLIST: must_size = ((struct lys_node_leaflist *)schema)->must_size; break; case LYS_LIST: must_size = ((struct lys_node_list *)schema)->must_size; break; case LYS_ANYXML: case LYS_ANYDATA: must_size = ((struct lys_node_anydata *)schema)->must_size; break; case LYS_NOTIF: must_size = ((struct lys_node_notif *)schema)->must_size; break; default: must_size = 0; break; } if (must_size) { ++ret; } /* schema may be a direct data child of input/output with must (but it must be first, it needs to be evaluated only once) */ if (!node->prev->next) { for (iter = lys_parent(schema); iter && (iter->nodetype & (LYS_CHOICE | LYS_CASE | LYS_USES)); iter = lys_parent(iter)); if (iter && (iter->nodetype & (LYS_INPUT | LYS_OUTPUT))) { ret += 0x2; } } return ret; } static struct lys_when * snode_get_when(const struct lys_node *schema) { switch (schema->nodetype) { case LYS_CONTAINER: return ((struct lys_node_container *)schema)->when; case LYS_CHOICE: return ((struct lys_node_choice *)schema)->when; case LYS_LEAF: return ((struct lys_node_leaf *)schema)->when; case LYS_LEAFLIST: return ((struct lys_node_leaflist *)schema)->when; case LYS_LIST: return ((struct lys_node_list *)schema)->when; case LYS_ANYDATA: case LYS_ANYXML: return ((struct lys_node_anydata *)schema)->when; case LYS_CASE: return ((struct lys_node_case *)schema)->when; case LYS_USES: return ((struct lys_node_uses *)schema)->when; case LYS_AUGMENT: return ((struct lys_node_augment *)schema)->when; default: return NULL; } } int resolve_applies_when(const struct lys_node *schema, int mode, const struct lys_node *stop) { const struct lys_node *parent; assert(schema); if (!(schema->nodetype & (LYS_NOTIF | LYS_RPC)) && snode_get_when(schema)) { return 1; } parent = schema; goto check_augment; while (parent) { /* stop conditions */ if (!mode) { /* stop on node that can be instantiated in data tree */ if (!(parent->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE))) { break; } } else { /* stop on the specified node */ if (parent == stop) { break; } } if (snode_get_when(parent)) { return 1; } check_augment: if (parent->parent && (parent->parent->nodetype == LYS_AUGMENT) && snode_get_when(parent->parent)) { return 1; } parent = lys_parent(parent); } return 0; } /** * @brief Resolve (check) all when conditions relevant for \p node. * Logs directly. * * @param[in] node Data node, whose conditional reference, if such, is being decided. * @param[in] ignore_fail 1 if when does not have to be satisfied, 2 if it does not have to be satisfied * only when requiring external dependencies. * * @return * -1 - error, ly_errno is set * 0 - all "when" statements true * 0, ly_vecode = LYVE_NOWHEN - some "when" statement false, returned in failed_when * 1, ly_vecode = LYVE_INWHEN - nodes needed to resolve are conditional and not yet resolved (under another "when") */ int resolve_when(struct lyd_node *node, int ignore_fail, struct lys_when **failed_when) { struct lyd_node *ctx_node = NULL, *unlinked_nodes, *tmp_node; struct lys_node *sparent; struct lyxp_set set; enum lyxp_node_type ctx_node_type; struct ly_ctx *ctx = node->schema->module->ctx; int rc = 0; assert(node); memset(&set, 0, sizeof set); if (!(node->schema->nodetype & (LYS_NOTIF | LYS_RPC | LYS_ACTION)) && snode_get_when(node->schema)) { /* make the node dummy for the evaluation */ node->validity |= LYD_VAL_INUSE; rc = lyxp_eval(snode_get_when(node->schema)->cond, node, LYXP_NODE_ELEM, lyd_node_module(node), &set, LYXP_WHEN); node->validity &= ~LYD_VAL_INUSE; if (rc) { if (rc == 1) { LOGVAL(ctx, LYE_INWHEN, LY_VLOG_LYD, node, snode_get_when(node->schema)->cond); } goto cleanup; } /* set boolean result of the condition */ lyxp_set_cast(&set, LYXP_SET_BOOLEAN, node, lyd_node_module(node), LYXP_WHEN); if (!set.val.bool) { node->when_status |= LYD_WHEN_FALSE; if ((ignore_fail == 1) || ((snode_get_when(node->schema)->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) && (ignore_fail == 2))) { LOGVRB("When condition \"%s\" is not satisfied, but it is not required.", snode_get_when(node->schema)->cond); } else { LOGVAL(ctx, LYE_NOWHEN, LY_VLOG_LYD, node, snode_get_when(node->schema)->cond); if (failed_when) { *failed_when = snode_get_when(node->schema); } goto cleanup; } } /* free xpath set content */ lyxp_set_cast(&set, LYXP_SET_EMPTY, node, lyd_node_module(node), 0); } sparent = node->schema; goto check_augment; /* check when in every schema node that affects node */ while (sparent && (sparent->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE))) { if (snode_get_when(sparent)) { if (!ctx_node) { rc = resolve_when_ctx_node(node, sparent, &ctx_node, &ctx_node_type); if (rc) { LOGINT(ctx); goto cleanup; } } unlinked_nodes = NULL; /* we do not want our node pointer to change */ tmp_node = node; rc = resolve_when_unlink_nodes(sparent, &tmp_node, &ctx_node, ctx_node_type, &unlinked_nodes); if (rc) { goto cleanup; } rc = lyxp_eval(snode_get_when(sparent)->cond, ctx_node, ctx_node_type, lys_node_module(sparent), &set, LYXP_WHEN); if (unlinked_nodes && ctx_node) { if (resolve_when_relink_nodes(ctx_node, unlinked_nodes, ctx_node_type)) { rc = -1; goto cleanup; } } if (rc) { if (rc == 1) { LOGVAL(ctx, LYE_INWHEN, LY_VLOG_LYD, node, snode_get_when(sparent)->cond); } goto cleanup; } lyxp_set_cast(&set, LYXP_SET_BOOLEAN, ctx_node, lys_node_module(sparent), LYXP_WHEN); if (!set.val.bool) { if ((ignore_fail == 1) || ((snode_get_when(sparent)->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) && (ignore_fail == 2))) { LOGVRB("When condition \"%s\" is not satisfied, but it is not required.", snode_get_when(sparent)->cond); } else { node->when_status |= LYD_WHEN_FALSE; LOGVAL(ctx, LYE_NOWHEN, LY_VLOG_LYD, node, snode_get_when(sparent)->cond); if (failed_when) { *failed_when = snode_get_when(sparent); } goto cleanup; } } /* free xpath set content */ lyxp_set_cast(&set, LYXP_SET_EMPTY, ctx_node, lys_node_module(sparent), 0); } check_augment: if ((sparent->parent && (sparent->parent->nodetype == LYS_AUGMENT) && snode_get_when(sparent->parent))) { if (!ctx_node) { rc = resolve_when_ctx_node(node, sparent->parent, &ctx_node, &ctx_node_type); if (rc) { LOGINT(ctx); goto cleanup; } } unlinked_nodes = NULL; tmp_node = node; rc = resolve_when_unlink_nodes(sparent->parent, &tmp_node, &ctx_node, ctx_node_type, &unlinked_nodes); if (rc) { goto cleanup; } rc = lyxp_eval(snode_get_when(sparent->parent)->cond, ctx_node, ctx_node_type, lys_node_module(sparent->parent), &set, LYXP_WHEN); /* reconnect nodes, if ctx_node is NULL then all the nodes were unlinked, but linked together, * so the tree did not actually change and there is nothing for us to do */ if (unlinked_nodes && ctx_node) { if (resolve_when_relink_nodes(ctx_node, unlinked_nodes, ctx_node_type)) { rc = -1; goto cleanup; } } if (rc) { if (rc == 1) { LOGVAL(ctx, LYE_INWHEN, LY_VLOG_LYD, node, snode_get_when(sparent->parent)->cond); } goto cleanup; } lyxp_set_cast(&set, LYXP_SET_BOOLEAN, ctx_node, lys_node_module(sparent->parent), LYXP_WHEN); if (!set.val.bool) { node->when_status |= LYD_WHEN_FALSE; if ((ignore_fail == 1) || ((snode_get_when(sparent->parent)->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) && (ignore_fail == 2))) { LOGVRB("When condition \"%s\" is not satisfied, but it is not required.", snode_get_when(sparent->parent)->cond); } else { LOGVAL(ctx, LYE_NOWHEN, LY_VLOG_LYD, node, snode_get_when(sparent->parent)->cond); if (failed_when) { *failed_when = snode_get_when(sparent->parent); } goto cleanup; } } /* free xpath set content */ lyxp_set_cast(&set, LYXP_SET_EMPTY, ctx_node, lys_node_module(sparent->parent), 0); } sparent = lys_parent(sparent); } node->when_status |= LYD_WHEN_TRUE; cleanup: /* free xpath set content */ lyxp_set_cast(&set, LYXP_SET_EMPTY, ctx_node ? ctx_node : node, NULL, 0); return rc; } static int check_type_union_leafref(struct lys_type *type) { uint8_t i; if ((type->base == LY_TYPE_UNION) && type->info.uni.count) { /* go through unions and look for leafref */ for (i = 0; i < type->info.uni.count; ++i) { switch (type->info.uni.types[i].base) { case LY_TYPE_LEAFREF: return 1; case LY_TYPE_UNION: if (check_type_union_leafref(&type->info.uni.types[i])) { return 1; } break; default: break; } } return 0; } /* just inherit the flag value */ return type->der->has_union_leafref; } /** * @brief Resolve a single unres schema item. Logs indirectly. * * @param[in] mod Main module. * @param[in] item Item to resolve. Type determined by \p type. * @param[in] type Type of the unresolved item. * @param[in] str_snode String, a schema node, or NULL. * @param[in] unres Unres schema structure to use. * @param[in] final_fail Whether we are just printing errors of the failed unres items. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ static int resolve_unres_schema_item(struct lys_module *mod, void *item, enum UNRES_ITEM type, void *str_snode, struct unres_schema *unres) { /* has_str - whether the str_snode is a string in a dictionary that needs to be freed */ int rc = -1, has_str = 0, parent_type = 0, i, k; unsigned int j; struct ly_ctx * ctx = mod->ctx; struct lys_node *root, *next, *node, *par_grp; const char *expr; uint8_t *u; struct ly_set *refs, *procs; struct lys_feature *ref, *feat; struct lys_ident *ident; struct lys_type *stype; struct lys_node_choice *choic; struct lyxml_elem *yin; struct yang_type *yang; struct unres_list_uniq *unique_info; struct unres_iffeat_data *iff_data; struct unres_ext *ext_data; struct lys_ext_instance *ext, **extlist; struct lyext_plugin *eplugin; switch (type) { case UNRES_IDENT: expr = str_snode; has_str = 1; ident = item; rc = resolve_base_ident(mod, ident, expr, "identity", NULL, unres); break; case UNRES_TYPE_IDENTREF: expr = str_snode; has_str = 1; stype = item; rc = resolve_base_ident(mod, NULL, expr, "type", stype, unres); break; case UNRES_TYPE_LEAFREF: node = str_snode; stype = item; rc = resolve_schema_leafref(stype, node, unres); break; case UNRES_TYPE_DER_EXT: parent_type++; /* falls through */ case UNRES_TYPE_DER_TPDF: parent_type++; /* falls through */ case UNRES_TYPE_DER: /* parent */ node = str_snode; stype = item; /* HACK type->der is temporarily unparsed type statement */ yin = (struct lyxml_elem *)stype->der; stype->der = NULL; if (yin->flags & LY_YANG_STRUCTURE_FLAG) { yang = (struct yang_type *)yin; rc = yang_check_type(mod, node, yang, stype, parent_type, unres); if (rc) { /* may try again later */ stype->der = (struct lys_tpdf *)yang; } else { /* we need to always be able to free this, it's safe only in this case */ lydict_remove(ctx, yang->name); free(yang); } } else { rc = fill_yin_type(mod, node, yin, stype, parent_type, unres); if (!rc || rc == -1) { /* we need to always be able to free this, it's safe only in this case */ lyxml_free(ctx, yin); } else { /* may try again later, put all back how it was */ stype->der = (struct lys_tpdf *)yin; } } if (rc == EXIT_SUCCESS) { /* it does not make sense to have leaf-list of empty type */ if (!parent_type && node->nodetype == LYS_LEAFLIST && stype->base == LY_TYPE_EMPTY) { LOGWRN(ctx, "The leaf-list \"%s\" is of \"empty\" type, which does not make sense.", node->name); } if ((type == UNRES_TYPE_DER_TPDF) && (stype->base == LY_TYPE_UNION)) { /* fill typedef union leafref flag */ ((struct lys_tpdf *)stype->parent)->has_union_leafref = check_type_union_leafref(stype); } else if ((type == UNRES_TYPE_DER) && stype->der->has_union_leafref) { /* copy the type in case it has union leafref flag */ if (lys_copy_union_leafrefs(mod, node, stype, NULL, unres)) { LOGERR(ctx, LY_EINT, "Failed to duplicate type."); return -1; } } } else if (rc == EXIT_FAILURE && !(stype->value_flags & LY_VALUE_UNRESGRP)) { /* forward reference - in case the type is in grouping, we have to make the grouping unusable * by uses statement until the type is resolved. We do that the same way as uses statements inside * grouping. The grouping cannot be used unless the unres counter is 0. * To remember that the grouping already increased the counter, the LYTYPE_GRP is used as value * of the type's base member. */ for (par_grp = node; par_grp && (par_grp->nodetype != LYS_GROUPING); par_grp = lys_parent(par_grp)); if (par_grp) { if (++((struct lys_node_grp *)par_grp)->unres_count == 0) { LOGERR(ctx, LY_EINT, "Too many unresolved items (type) inside a grouping."); return -1; } stype->value_flags |= LY_VALUE_UNRESGRP; } } break; case UNRES_IFFEAT: iff_data = str_snode; rc = resolve_feature(iff_data->fname, strlen(iff_data->fname), iff_data->node, item); if (!rc) { /* success */ if (iff_data->infeature) { /* store backlink into the target feature to allow reverse changes in case of changing feature status */ feat = *((struct lys_feature **)item); if (!feat->depfeatures) { feat->depfeatures = ly_set_new(); } ly_set_add(feat->depfeatures, iff_data->node, LY_SET_OPT_USEASLIST); } /* cleanup temporary data */ lydict_remove(ctx, iff_data->fname); free(iff_data); } break; case UNRES_FEATURE: feat = (struct lys_feature *)item; if (feat->iffeature_size) { refs = ly_set_new(); procs = ly_set_new(); ly_set_add(procs, feat, 0); while (procs->number) { ref = procs->set.g[procs->number - 1]; ly_set_rm_index(procs, procs->number - 1); for (i = 0; i < ref->iffeature_size; i++) { resolve_iffeature_getsizes(&ref->iffeature[i], NULL, &j); for (; j > 0 ; j--) { if (ref->iffeature[i].features[j - 1]) { if (ref->iffeature[i].features[j - 1] == feat) { LOGVAL(ctx, LYE_CIRC_FEATURES, LY_VLOG_NONE, NULL, feat->name); goto featurecheckdone; } if (ref->iffeature[i].features[j - 1]->iffeature_size) { k = refs->number; if (ly_set_add(refs, ref->iffeature[i].features[j - 1], 0) == k) { /* not yet seen feature, add it for processing */ ly_set_add(procs, ref->iffeature[i].features[j - 1], 0); } } } else { /* forward reference */ rc = EXIT_FAILURE; goto featurecheckdone; } } } } rc = EXIT_SUCCESS; featurecheckdone: ly_set_free(refs); ly_set_free(procs); } break; case UNRES_USES: rc = resolve_unres_schema_uses(item, unres); break; case UNRES_TYPEDEF_DFLT: parent_type++; /* falls through */ case UNRES_TYPE_DFLT: stype = item; rc = check_default(stype, (const char **)str_snode, mod, parent_type); if ((rc == EXIT_FAILURE) && !parent_type && (stype->base == LY_TYPE_LEAFREF)) { for (par_grp = (struct lys_node *)stype->parent; par_grp && (par_grp->nodetype != LYS_GROUPING); par_grp = lys_parent(par_grp)); if (par_grp) { /* checking default value in a grouping finished with forward reference means we cannot check the value */ rc = EXIT_SUCCESS; } } break; case UNRES_CHOICE_DFLT: expr = str_snode; has_str = 1; choic = item; if (!choic->dflt) { choic->dflt = resolve_choice_dflt(choic, expr); } if (choic->dflt) { rc = lyp_check_mandatory_choice((struct lys_node *)choic); } else { rc = EXIT_FAILURE; } break; case UNRES_LIST_KEYS: rc = resolve_list_keys(item, ((struct lys_node_list *)item)->keys_str); break; case UNRES_LIST_UNIQ: unique_info = (struct unres_list_uniq *)item; rc = resolve_unique(unique_info->list, unique_info->expr, unique_info->trg_type); break; case UNRES_AUGMENT: rc = resolve_augment(item, NULL, unres); break; case UNRES_XPATH: node = (struct lys_node *)item; rc = check_xpath(node, 1); break; case UNRES_MOD_IMPLEMENT: rc = lys_make_implemented_r(mod, unres); break; case UNRES_EXT: ext_data = (struct unres_ext *)str_snode; extlist = &(*(struct lys_ext_instance ***)item)[ext_data->ext_index]; rc = resolve_extension(ext_data, extlist, unres); if (!rc) { /* success */ /* is there a callback to be done to finalize the extension? */ eplugin = extlist[0]->def->plugin; if (eplugin) { if (eplugin->check_result || (eplugin->flags & LYEXT_OPT_INHERIT)) { u = malloc(sizeof *u); LY_CHECK_ERR_RETURN(!u, LOGMEM(ctx), -1); (*u) = ext_data->ext_index; if (unres_schema_add_node(mod, unres, item, UNRES_EXT_FINALIZE, (struct lys_node *)u) == -1) { /* something really bad happend since the extension finalization is not actually * being resolved while adding into unres, so something more serious with the unres * list itself must happened */ return -1; } } } } if (!rc || rc == -1) { /* cleanup on success or fatal error */ if (ext_data->datatype == LYS_IN_YIN) { /* YIN */ lyxml_free(ctx, ext_data->data.yin); } else { /* YANG */ yang_free_ext_data(ext_data->data.yang); } free(ext_data); } break; case UNRES_EXT_FINALIZE: u = (uint8_t *)str_snode; ext = (*(struct lys_ext_instance ***)item)[*u]; free(u); eplugin = ext->def->plugin; /* inherit */ if ((eplugin->flags & LYEXT_OPT_INHERIT) && (ext->parent_type == LYEXT_PAR_NODE)) { root = (struct lys_node *)ext->parent; if (!(root->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) { LY_TREE_DFS_BEGIN(root->child, next, node) { /* first, check if the node already contain instance of the same extension, * in such a case we won't inherit. In case the node was actually defined as * augment data, we are supposed to check the same way also the augment node itself */ if (lys_ext_instance_presence(ext->def, node->ext, node->ext_size) != -1) { goto inherit_dfs_sibling; } else if (node->parent != root && node->parent->nodetype == LYS_AUGMENT && lys_ext_instance_presence(ext->def, node->parent->ext, node->parent->ext_size) != -1) { goto inherit_dfs_sibling; } if (eplugin->check_inherit) { /* we have a callback to check the inheritance, use it */ switch ((rc = (*eplugin->check_inherit)(ext, node))) { case 0: /* yes - continue with the inheriting code */ break; case 1: /* no - continue with the node's sibling */ goto inherit_dfs_sibling; case 2: /* no, but continue with the children, just skip the inheriting code for this node */ goto inherit_dfs_child; default: LOGERR(ctx, LY_EINT, "Plugin's (%s:%s) check_inherit callback returns invalid value (%d),", ext->def->module->name, ext->def->name, rc); } } /* inherit the extension */ extlist = realloc(node->ext, (node->ext_size + 1) * sizeof *node->ext); LY_CHECK_ERR_RETURN(!extlist, LOGMEM(ctx), -1); extlist[node->ext_size] = malloc(sizeof **extlist); LY_CHECK_ERR_RETURN(!extlist[node->ext_size], LOGMEM(ctx); node->ext = extlist, -1); memcpy(extlist[node->ext_size], ext, sizeof *ext); extlist[node->ext_size]->flags |= LYEXT_OPT_INHERIT; node->ext = extlist; node->ext_size++; inherit_dfs_child: /* modification of - select element for the next run - children first */ if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { next = NULL; } else { next = node->child; } if (!next) { inherit_dfs_sibling: /* no children, try siblings */ next = node->next; } while (!next) { /* go to the parent */ node = lys_parent(node); /* we are done if we are back in the root (the starter's parent */ if (node == root) { break; } /* parent is already processed, go to its sibling */ next = node->next; } } } } /* final check */ if (eplugin->check_result) { if ((*eplugin->check_result)(ext)) { LOGERR(ctx, LY_EPLUGIN, "Resolving extension failed."); return -1; } } rc = 0; break; default: LOGINT(ctx); break; } if (has_str && !rc) { /* the string is no more needed in case of success. * In case of forward reference, we will try to resolve the string later */ lydict_remove(ctx, str_snode); } return rc; } /* logs directly */ static void print_unres_schema_item_fail(void *item, enum UNRES_ITEM type, void *str_node) { struct lyxml_elem *xml; struct lyxml_attr *attr; struct unres_iffeat_data *iff_data; const char *name = NULL; struct unres_ext *extinfo; switch (type) { case UNRES_IDENT: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "identity", (char *)str_node); break; case UNRES_TYPE_IDENTREF: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "identityref", (char *)str_node); break; case UNRES_TYPE_LEAFREF: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "leafref", ((struct lys_type *)item)->info.lref.path); break; case UNRES_TYPE_DER_EXT: case UNRES_TYPE_DER_TPDF: case UNRES_TYPE_DER: xml = (struct lyxml_elem *)((struct lys_type *)item)->der; if (xml->flags & LY_YANG_STRUCTURE_FLAG) { name = ((struct yang_type *)xml)->name; } else { LY_TREE_FOR(xml->attr, attr) { if ((attr->type == LYXML_ATTR_STD) && !strcmp(attr->name, "name")) { name = attr->value; break; } } assert(attr); } LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "derived type", name); break; case UNRES_IFFEAT: iff_data = str_node; LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "if-feature", iff_data->fname); break; case UNRES_FEATURE: LOGVRB("There are unresolved if-features for \"%s\" feature circular dependency check, it will be attempted later", ((struct lys_feature *)item)->name); break; case UNRES_USES: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "uses", ((struct lys_node_uses *)item)->name); break; case UNRES_TYPEDEF_DFLT: case UNRES_TYPE_DFLT: if (*(char **)str_node) { LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "type default", *(char **)str_node); } /* else no default value in the type itself, but we are checking some restrictions against * possible default value of some base type. The failure is caused by not resolved base type, * so it was already reported */ break; case UNRES_CHOICE_DFLT: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "choice default", (char *)str_node); break; case UNRES_LIST_KEYS: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "list keys", (char *)str_node); break; case UNRES_LIST_UNIQ: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "list unique", (char *)str_node); break; case UNRES_AUGMENT: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "augment target", ((struct lys_node_augment *)item)->target_name); break; case UNRES_XPATH: LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "XPath expressions of", ((struct lys_node *)item)->name); break; case UNRES_EXT: extinfo = (struct unres_ext *)str_node; name = extinfo->datatype == LYS_IN_YIN ? extinfo->data.yin->name : NULL; /* TODO YANG extension */ LOGVRB("Resolving extension \"%s\" failed, it will be attempted later.", name); break; default: LOGINT(NULL); break; } } static int resolve_unres_schema_types(struct unres_schema *unres, enum UNRES_ITEM types, struct ly_ctx *ctx, int forward_ref, int print_all_errors, uint32_t *resolved) { uint32_t i, unres_count, res_count; int ret = 0, rc; struct ly_err_item *prev_eitem; enum int_log_opts prev_ilo; LY_ERR prev_ly_errno; /* if there can be no forward references, every failure is final, so we can print it directly */ if (forward_ref) { prev_ly_errno = ly_errno; ly_ilo_change(ctx, ILO_STORE, &prev_ilo, &prev_eitem); } do { unres_count = 0; res_count = 0; for (i = 0; i < unres->count; ++i) { /* UNRES_TYPE_LEAFREF must be resolved (for storing leafref target pointers); * if-features are resolved here to make sure that we will have all if-features for * later check of feature circular dependency */ if (unres->type[i] & types) { ++unres_count; rc = resolve_unres_schema_item(unres->module[i], unres->item[i], unres->type[i], unres->str_snode[i], unres); if (unres->type[i] == UNRES_EXT_FINALIZE) { /* to avoid double free */ unres->type[i] = UNRES_RESOLVED; } if (!rc || (unres->type[i] == UNRES_XPATH)) { /* invalid XPath can never cause an error, only a warning */ if (unres->type[i] == UNRES_LIST_UNIQ) { /* free the allocated structure */ free(unres->item[i]); } unres->type[i] = UNRES_RESOLVED; ++(*resolved); ++res_count; } else if ((rc == EXIT_FAILURE) && forward_ref) { /* forward reference, erase errors */ ly_err_free_next(ctx, prev_eitem); } else if (print_all_errors) { /* just so that we quit the loop */ ++res_count; ret = -1; } else { if (forward_ref) { ly_ilo_restore(ctx, prev_ilo, prev_eitem, 1); } return -1; } } } } while (res_count && (res_count < unres_count)); if (res_count < unres_count) { assert(forward_ref); /* just print the errors (but we must free the ones we have and get them again :-/ ) */ ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0); for (i = 0; i < unres->count; ++i) { if (unres->type[i] & types) { resolve_unres_schema_item(unres->module[i], unres->item[i], unres->type[i], unres->str_snode[i], unres); } } return -1; } if (forward_ref) { /* restore log */ ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0); ly_errno = prev_ly_errno; } return ret; } /** * @brief Resolve every unres schema item in the structure. Logs directly. * * @param[in] mod Main module. * @param[in] unres Unres schema structure to use. * * @return EXIT_SUCCESS on success, -1 on error. */ int resolve_unres_schema(struct lys_module *mod, struct unres_schema *unres) { uint32_t resolved = 0; assert(unres); LOGVRB("Resolving \"%s\" unresolved schema nodes and their constraints...", mod->name); /* UNRES_TYPE_LEAFREF must be resolved (for storing leafref target pointers); * if-features are resolved here to make sure that we will have all if-features for * later check of feature circular dependency */ if (resolve_unres_schema_types(unres, UNRES_USES | UNRES_IFFEAT | UNRES_TYPE_DER | UNRES_TYPE_DER_TPDF | UNRES_TYPE_DER_TPDF | UNRES_TYPE_LEAFREF | UNRES_MOD_IMPLEMENT | UNRES_AUGMENT | UNRES_CHOICE_DFLT | UNRES_IDENT, mod->ctx, 1, 0, &resolved)) { return -1; } /* another batch of resolved items */ if (resolve_unres_schema_types(unres, UNRES_TYPE_IDENTREF | UNRES_FEATURE | UNRES_TYPEDEF_DFLT | UNRES_TYPE_DFLT | UNRES_LIST_KEYS | UNRES_LIST_UNIQ | UNRES_EXT, mod->ctx, 1, 0, &resolved)) { return -1; } /* print xpath warnings and finalize extensions, keep it last to provide the complete schema tree information to the plugin's checkers */ if (resolve_unres_schema_types(unres, UNRES_XPATH | UNRES_EXT_FINALIZE, mod->ctx, 0, 1, &resolved)) { return -1; } LOGVRB("All \"%s\" schema nodes and constraints resolved.", mod->name); unres->count = 0; return EXIT_SUCCESS; } /** * @brief Try to resolve an unres schema item with a string argument. Logs indirectly. * * @param[in] mod Main module. * @param[in] unres Unres schema structure to use. * @param[in] item Item to resolve. Type determined by \p type. * @param[in] type Type of the unresolved item. * @param[in] str String argument. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on storing the item in unres, -1 on error. */ int unres_schema_add_str(struct lys_module *mod, struct unres_schema *unres, void *item, enum UNRES_ITEM type, const char *str) { int rc; const char *dictstr; dictstr = lydict_insert(mod->ctx, str, 0); rc = unres_schema_add_node(mod, unres, item, type, (struct lys_node *)dictstr); if (rc < 0) { lydict_remove(mod->ctx, dictstr); } return rc; } /** * @brief Try to resolve an unres schema item with a schema node argument. Logs indirectly. * * @param[in] mod Main module. * @param[in] unres Unres schema structure to use. * @param[in] item Item to resolve. Type determined by \p type. * @param[in] type Type of the unresolved item. UNRES_TYPE_DER is handled specially! * @param[in] snode Schema node argument. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on storing the item in unres, -1 on error. */ int unres_schema_add_node(struct lys_module *mod, struct unres_schema *unres, void *item, enum UNRES_ITEM type, struct lys_node *snode) { int rc; uint32_t u; enum int_log_opts prev_ilo; struct ly_err_item *prev_eitem; LY_ERR prev_ly_errno; struct lyxml_elem *yin; struct ly_ctx *ctx = mod->ctx; assert(unres && (item || (type == UNRES_MOD_IMPLEMENT)) && ((type != UNRES_LEAFREF) && (type != UNRES_INSTID) && (type != UNRES_WHEN) && (type != UNRES_MUST))); /* check for duplicities in unres */ for (u = 0; u < unres->count; u++) { if (unres->type[u] == type && unres->item[u] == item && unres->str_snode[u] == snode && unres->module[u] == mod) { /* duplication can happen when the node contains multiple statements of the same type to check, * this can happen for example when refinement is being applied, so we just postpone the processing * and do not duplicate the information */ return EXIT_FAILURE; } } if ((type == UNRES_EXT_FINALIZE) || (type == UNRES_XPATH) || (type == UNRES_MOD_IMPLEMENT)) { /* extension finalization is not even tried when adding the item into the inres list, * xpath is not tried because it would hide some potential warnings, * implementing module must be deferred because some other nodes can be added that will need to be traversed * and their targets made implemented */ rc = EXIT_FAILURE; } else { prev_ly_errno = ly_errno; ly_ilo_change(ctx, ILO_STORE, &prev_ilo, &prev_eitem); rc = resolve_unres_schema_item(mod, item, type, snode, unres); if (rc != EXIT_FAILURE) { ly_ilo_restore(ctx, prev_ilo, prev_eitem, rc == -1 ? 1 : 0); if (rc != -1) { ly_errno = prev_ly_errno; } if (type == UNRES_LIST_UNIQ) { /* free the allocated structure */ free(item); } else if (rc == -1 && type == UNRES_IFFEAT) { /* free the allocated resources */ free(*((char **)item)); } return rc; } else { /* erase info about validation errors */ ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0); ly_errno = prev_ly_errno; } print_unres_schema_item_fail(item, type, snode); /* HACK unlinking is performed here so that we do not do any (NS) copying in vain */ if (type == UNRES_TYPE_DER || type == UNRES_TYPE_DER_TPDF) { yin = (struct lyxml_elem *)((struct lys_type *)item)->der; if (!(yin->flags & LY_YANG_STRUCTURE_FLAG)) { lyxml_unlink_elem(mod->ctx, yin, 1); ((struct lys_type *)item)->der = (struct lys_tpdf *)yin; } } } unres->count++; unres->item = ly_realloc(unres->item, unres->count*sizeof *unres->item); LY_CHECK_ERR_RETURN(!unres->item, LOGMEM(ctx), -1); unres->item[unres->count-1] = item; unres->type = ly_realloc(unres->type, unres->count*sizeof *unres->type); LY_CHECK_ERR_RETURN(!unres->type, LOGMEM(ctx), -1); unres->type[unres->count-1] = type; unres->str_snode = ly_realloc(unres->str_snode, unres->count*sizeof *unres->str_snode); LY_CHECK_ERR_RETURN(!unres->str_snode, LOGMEM(ctx), -1); unres->str_snode[unres->count-1] = snode; unres->module = ly_realloc(unres->module, unres->count*sizeof *unres->module); LY_CHECK_ERR_RETURN(!unres->module, LOGMEM(ctx), -1); unres->module[unres->count-1] = mod; return rc; } /** * @brief Duplicate an unres schema item. Logs indirectly. * * @param[in] mod Main module. * @param[in] unres Unres schema structure to use. * @param[in] item Old item to be resolved. * @param[in] type Type of the old unresolved item. * @param[in] new_item New item to use in the duplicate. * * @return EXIT_SUCCESS on success, EXIT_FAILURE if item is not in unres, -1 on error. */ int unres_schema_dup(struct lys_module *mod, struct unres_schema *unres, void *item, enum UNRES_ITEM type, void *new_item) { int i; struct unres_list_uniq aux_uniq; struct unres_iffeat_data *iff_data; assert(item && new_item && ((type != UNRES_LEAFREF) && (type != UNRES_INSTID) && (type != UNRES_WHEN))); /* hack for UNRES_LIST_UNIQ, which stores multiple items behind its item */ if (type == UNRES_LIST_UNIQ) { aux_uniq.list = item; aux_uniq.expr = ((struct unres_list_uniq *)new_item)->expr; item = &aux_uniq; } i = unres_schema_find(unres, -1, item, type); if (i == -1) { if (type == UNRES_LIST_UNIQ) { free(new_item); } return EXIT_FAILURE; } if ((type == UNRES_TYPE_LEAFREF) || (type == UNRES_USES) || (type == UNRES_TYPE_DFLT) || (type == UNRES_FEATURE) || (type == UNRES_LIST_UNIQ)) { if (unres_schema_add_node(mod, unres, new_item, type, unres->str_snode[i]) == -1) { LOGINT(mod->ctx); return -1; } } else if (type == UNRES_IFFEAT) { /* duplicate unres_iffeature_data */ iff_data = malloc(sizeof *iff_data); LY_CHECK_ERR_RETURN(!iff_data, LOGMEM(mod->ctx), -1); iff_data->fname = lydict_insert(mod->ctx, ((struct unres_iffeat_data *)unres->str_snode[i])->fname, 0); iff_data->node = ((struct unres_iffeat_data *)unres->str_snode[i])->node; if (unres_schema_add_node(mod, unres, new_item, type, (struct lys_node *)iff_data) == -1) { LOGINT(mod->ctx); return -1; } } else { if (unres_schema_add_str(mod, unres, new_item, type, unres->str_snode[i]) == -1) { LOGINT(mod->ctx); return -1; } } return EXIT_SUCCESS; } /* does not log */ int unres_schema_find(struct unres_schema *unres, int start_on_backwards, void *item, enum UNRES_ITEM type) { int i; struct unres_list_uniq *aux_uniq1, *aux_uniq2; if (!unres->count) { return -1; } if (start_on_backwards >= 0) { i = start_on_backwards; } else { i = unres->count - 1; } for (; i > -1; i--) { if (unres->type[i] != type) { continue; } if (type != UNRES_LIST_UNIQ) { if (unres->item[i] == item) { break; } } else { aux_uniq1 = (struct unres_list_uniq *)unres->item[i]; aux_uniq2 = (struct unres_list_uniq *)item; if ((aux_uniq1->list == aux_uniq2->list) && ly_strequal(aux_uniq1->expr, aux_uniq2->expr, 0)) { break; } } } return i; } static void unres_schema_free_item(struct ly_ctx *ctx, struct unres_schema *unres, uint32_t i) { struct lyxml_elem *yin; struct yang_type *yang; struct unres_iffeat_data *iff_data; switch (unres->type[i]) { case UNRES_TYPE_DER_TPDF: case UNRES_TYPE_DER: yin = (struct lyxml_elem *)((struct lys_type *)unres->item[i])->der; if (yin->flags & LY_YANG_STRUCTURE_FLAG) { yang =(struct yang_type *)yin; ((struct lys_type *)unres->item[i])->base = yang->base; lydict_remove(ctx, yang->name); free(yang); if (((struct lys_type *)unres->item[i])->base == LY_TYPE_UNION) { yang_free_type_union(ctx, (struct lys_type *)unres->item[i]); } } else { lyxml_free(ctx, yin); } break; case UNRES_IFFEAT: iff_data = (struct unres_iffeat_data *)unres->str_snode[i]; lydict_remove(ctx, iff_data->fname); free(unres->str_snode[i]); break; case UNRES_IDENT: case UNRES_TYPE_IDENTREF: case UNRES_CHOICE_DFLT: case UNRES_LIST_KEYS: lydict_remove(ctx, (const char *)unres->str_snode[i]); break; case UNRES_LIST_UNIQ: free(unres->item[i]); break; case UNRES_EXT: free(unres->str_snode[i]); break; case UNRES_EXT_FINALIZE: free(unres->str_snode[i]); default: break; } unres->type[i] = UNRES_RESOLVED; } void unres_schema_free(struct lys_module *module, struct unres_schema **unres, int all) { uint32_t i; unsigned int unresolved = 0; if (!unres || !(*unres)) { return; } assert(module || ((*unres)->count == 0)); for (i = 0; i < (*unres)->count; ++i) { if (!all && ((*unres)->module[i] != module)) { if ((*unres)->type[i] != UNRES_RESOLVED) { unresolved++; } continue; } /* free heap memory for the specific item */ unres_schema_free_item(module->ctx, *unres, i); } /* free it all */ if (!module || all || (!unresolved && !module->type)) { free((*unres)->item); free((*unres)->type); free((*unres)->str_snode); free((*unres)->module); free((*unres)); (*unres) = NULL; } } /* check whether instance-identifier points outside its data subtree (for operation it is any node * outside the operation subtree, otherwise it is a node from a foreign model) */ static int check_instid_ext_dep(const struct lys_node *sleaf, const char *json_instid) { const struct lys_node *op_node, *first_node; enum int_log_opts prev_ilo; char *buf, *tmp; if (!json_instid || !json_instid[0]) { /* no/empty value */ return 0; } for (op_node = lys_parent(sleaf); op_node && !(op_node->nodetype & (LYS_NOTIF | LYS_RPC | LYS_ACTION)); op_node = lys_parent(op_node)); if (op_node && lys_parent(op_node)) { /* nested operation - any absolute path is external */ return 1; } /* get the first node from the instid */ tmp = strchr(json_instid + 1, '/'); buf = strndup(json_instid, tmp ? (size_t)(tmp - json_instid) : strlen(json_instid)); if (!buf) { /* so that we do not have to bother with logging, say it is not external */ return 0; } /* find the first schema node, do not log */ ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); first_node = ly_ctx_get_node(NULL, sleaf, buf, 0); ly_ilo_restore(NULL, prev_ilo, NULL, 0); free(buf); if (!first_node) { /* unknown path, say it is external */ return 1; } /* based on the first schema node in the path we can decide whether it points to an external tree or not */ if (op_node) { if (op_node != first_node) { /* it is a top-level operation, so we're good if it points somewhere inside it */ return 1; } } else { if (lys_node_module(sleaf) != lys_node_module(first_node)) { /* modules differ */ return 1; } } return 0; } /** * @brief Resolve instance-identifier in JSON data format. Logs directly. * * @param[in] data Data node where the path is used * @param[in] path Instance-identifier node value. * @param[in,out] ret Resolved instance or NULL. * * @return 0 on success (even if unresolved and \p ret is NULL), -1 on error. */ static int resolve_instid(struct lyd_node *data, const char *path, int req_inst, struct lyd_node **ret) { int i = 0, j, parsed, cur_idx; const struct lys_module *mod, *prev_mod = NULL; struct ly_ctx *ctx = data->schema->module->ctx; struct lyd_node *root, *node; const char *model = NULL, *name; char *str; int mod_len, name_len, has_predicate; struct unres_data node_match; memset(&node_match, 0, sizeof node_match); *ret = NULL; /* we need root to resolve absolute path */ for (root = data; root->parent; root = root->parent); /* we're still parsing it and the pointer is not correct yet */ if (root->prev) { for (; root->prev->next; root = root->prev); } /* search for the instance node */ while (path[i]) { j = parse_instance_identifier(&path[i], &model, &mod_len, &name, &name_len, &has_predicate); if (j <= 0) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYD, data, path[i-j], &path[i-j]); goto error; } i += j; if (model) { str = strndup(model, mod_len); if (!str) { LOGMEM(ctx); goto error; } mod = ly_ctx_get_module(ctx, str, NULL, 1); if (ctx->data_clb) { if (!mod) { mod = ctx->data_clb(ctx, str, NULL, 0, ctx->data_clb_data); } else if (!mod->implemented) { mod = ctx->data_clb(ctx, mod->name, mod->ns, LY_MODCLB_NOT_IMPLEMENTED, ctx->data_clb_data); } } free(str); if (!mod || !mod->implemented || mod->disabled) { break; } } else if (!prev_mod) { /* first iteration and we are missing module name */ LOGVAL(ctx, LYE_INELEM_LEN, LY_VLOG_LYD, data, name_len, name); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Instance-identifier is missing prefix in the first node."); goto error; } else { mod = prev_mod; } if (resolve_data(mod, name, name_len, root, &node_match)) { /* no instance exists */ break; } if (has_predicate) { /* we have predicate, so the current results must be list or leaf-list */ parsed = j = 0; /* index of the current node (for lists with position predicates) */ cur_idx = 1; while (j < (signed)node_match.count) { node = node_match.node[j]; parsed = resolve_instid_predicate(mod, &path[i], &node, cur_idx); if (parsed < 1) { LOGVAL(ctx, LYE_INPRED, LY_VLOG_LYD, data, &path[i - parsed]); goto error; } if (!node) { /* current node does not satisfy the predicate */ unres_data_del(&node_match, j); } else { ++j; } ++cur_idx; } i += parsed; } else if (node_match.count) { /* check that we are not addressing lists */ for (j = 0; (unsigned)j < node_match.count; ++j) { if (node_match.node[j]->schema->nodetype == LYS_LIST) { unres_data_del(&node_match, j--); } } if (!node_match.count) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYD, data, "Instance identifier is missing list keys."); } } prev_mod = mod; } if (!node_match.count) { /* no instance exists */ if (req_inst > -1) { LOGVAL(ctx, LYE_NOREQINS, LY_VLOG_LYD, data, path); return EXIT_FAILURE; } LOGVRB("There is no instance of \"%s\", but it is not required.", path); return EXIT_SUCCESS; } else if (node_match.count > 1) { /* instance identifier must resolve to a single node */ LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, data, path, "data tree"); goto error; } else { /* we have required result, remember it and cleanup */ *ret = node_match.node[0]; free(node_match.node); return EXIT_SUCCESS; } error: /* cleanup */ free(node_match.node); return -1; } static int resolve_leafref(struct lyd_node_leaf_list *leaf, const char *path, int req_inst, struct lyd_node **ret) { struct lyxp_set xp_set; uint32_t i; memset(&xp_set, 0, sizeof xp_set); *ret = NULL; /* syntax was already checked, so just evaluate the path using standard XPath */ if (lyxp_eval(path, (struct lyd_node *)leaf, LYXP_NODE_ELEM, lyd_node_module((struct lyd_node *)leaf), &xp_set, 0) != EXIT_SUCCESS) { return -1; } if (xp_set.type == LYXP_SET_NODE_SET) { for (i = 0; i < xp_set.used; ++i) { if ((xp_set.val.nodes[i].type != LYXP_NODE_ELEM) || !(xp_set.val.nodes[i].node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))) { continue; } /* not that the value is already in canonical form since the parsers does the conversion, * so we can simply compare just the values */ if (ly_strequal(leaf->value_str, ((struct lyd_node_leaf_list *)xp_set.val.nodes[i].node)->value_str, 1)) { /* we have the match */ *ret = xp_set.val.nodes[i].node; break; } } } lyxp_set_cast(&xp_set, LYXP_SET_EMPTY, (struct lyd_node *)leaf, NULL, 0); if (!*ret) { /* reference not found */ if (req_inst > -1) { LOGVAL(leaf->schema->module->ctx, LYE_NOLEAFREF, LY_VLOG_LYD, leaf, path, leaf->value_str); return EXIT_FAILURE; } else { LOGVRB("There is no leafref \"%s\" with the value \"%s\", but it is not required.", path, leaf->value_str); } } return EXIT_SUCCESS; } /* ignore fail because we are parsing edit-config, get, or get-config - but only if the union includes leafref or instid */ int resolve_union(struct lyd_node_leaf_list *leaf, struct lys_type *type, int store, int ignore_fail, struct lys_type **resolved_type) { struct ly_ctx *ctx = leaf->schema->module->ctx; struct lys_type *t; struct lyd_node *ret; enum int_log_opts prev_ilo; int found, success = 0, ext_dep, req_inst; const char *json_val = NULL; assert(type->base == LY_TYPE_UNION); if ((leaf->value_type == LY_TYPE_UNION) || ((leaf->value_type == LY_TYPE_INST) && (leaf->value_flags & LY_VALUE_UNRES))) { /* either NULL or instid previously converted to JSON */ json_val = lydict_insert(ctx, leaf->value.string, 0); } if (store) { lyd_free_value(leaf->value, leaf->value_type, leaf->value_flags, &((struct lys_node_leaf *)leaf->schema)->type, leaf->value_str, NULL, NULL, NULL); memset(&leaf->value, 0, sizeof leaf->value); } /* turn logging off, we are going to try to validate the value with all the types in order */ ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, 0); t = NULL; found = 0; while ((t = lyp_get_next_union_type(type, t, &found))) { found = 0; switch (t->base) { case LY_TYPE_LEAFREF: if ((ignore_fail == 1) || ((leaf->schema->flags & LYS_LEAFREF_DEP) && (ignore_fail == 2))) { req_inst = -1; } else { req_inst = t->info.lref.req; } if (!resolve_leafref(leaf, t->info.lref.path, req_inst, &ret)) { if (store) { if (ret && !(leaf->schema->flags & LYS_LEAFREF_DEP)) { /* valid resolved */ leaf->value.leafref = ret; leaf->value_type = LY_TYPE_LEAFREF; } else { /* valid unresolved */ ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (!lyp_parse_value(t, &leaf->value_str, NULL, leaf, NULL, NULL, 1, 0, 0)) { return -1; } ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); } } success = 1; } break; case LY_TYPE_INST: ext_dep = check_instid_ext_dep(leaf->schema, (json_val ? json_val : leaf->value_str)); if ((ignore_fail == 1) || (ext_dep && (ignore_fail == 2))) { req_inst = -1; } else { req_inst = t->info.inst.req; } if (!resolve_instid((struct lyd_node *)leaf, (json_val ? json_val : leaf->value_str), req_inst, &ret)) { if (store) { if (ret && !ext_dep) { /* valid resolved */ leaf->value.instance = ret; leaf->value_type = LY_TYPE_INST; if (json_val) { lydict_remove(leaf->schema->module->ctx, leaf->value_str); leaf->value_str = json_val; json_val = NULL; } } else { /* valid unresolved */ if (json_val) { /* put the JSON val back */ leaf->value.string = json_val; json_val = NULL; } else { leaf->value.instance = NULL; } leaf->value_type = LY_TYPE_INST; leaf->value_flags |= LY_VALUE_UNRES; } } success = 1; } break; default: if (lyp_parse_value(t, &leaf->value_str, NULL, leaf, NULL, NULL, store, 0, 0)) { success = 1; } break; } if (success) { break; } /* erase possible present and invalid value data */ if (store) { lyd_free_value(leaf->value, leaf->value_type, leaf->value_flags, t, leaf->value_str, NULL, NULL, NULL); memset(&leaf->value, 0, sizeof leaf->value); } } /* turn logging back on */ ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (json_val) { if (!success) { /* put the value back for now */ assert(leaf->value_type == LY_TYPE_UNION); leaf->value.string = json_val; } else { /* value was ultimately useless, but we could not have known */ lydict_remove(leaf->schema->module->ctx, json_val); } } if (success) { if (resolved_type) { *resolved_type = t; } } else if (!ignore_fail || !type->info.uni.has_ptr_type) { /* not found and it is required */ LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, leaf, leaf->value_str ? leaf->value_str : "", leaf->schema->name); return EXIT_FAILURE; } return EXIT_SUCCESS; } /** * @brief Resolve a single unres data item. Logs directly. * * @param[in] node Data node to resolve. * @param[in] type Type of the unresolved item. * @param[in] ignore_fail 0 - no, 1 - yes, 2 - yes, but only for external dependencies. * * @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error. */ int resolve_unres_data_item(struct lyd_node *node, enum UNRES_ITEM type, int ignore_fail, struct lys_when **failed_when) { int rc, req_inst, ext_dep; struct lyd_node_leaf_list *leaf; struct lyd_node *ret; struct lys_node_leaf *sleaf; leaf = (struct lyd_node_leaf_list *)node; sleaf = (struct lys_node_leaf *)leaf->schema; switch (type) { case UNRES_LEAFREF: assert(sleaf->type.base == LY_TYPE_LEAFREF); assert(leaf->validity & LYD_VAL_LEAFREF); if ((ignore_fail == 1) || ((leaf->schema->flags & LYS_LEAFREF_DEP) && (ignore_fail == 2))) { req_inst = -1; } else { req_inst = sleaf->type.info.lref.req; } rc = resolve_leafref(leaf, sleaf->type.info.lref.path, req_inst, &ret); if (!rc) { if (ret && !(leaf->schema->flags & LYS_LEAFREF_DEP)) { /* valid resolved */ if (leaf->value_type == LY_TYPE_BITS) { free(leaf->value.bit); } leaf->value.leafref = ret; leaf->value_type = LY_TYPE_LEAFREF; leaf->value_flags &= ~LY_VALUE_UNRES; } else { /* valid unresolved */ if (!(leaf->value_flags & LY_VALUE_UNRES)) { if (!lyp_parse_value(&sleaf->type, &leaf->value_str, NULL, leaf, NULL, NULL, 1, 0, 0)) { return -1; } } } leaf->validity &= ~LYD_VAL_LEAFREF; } else { return rc; } break; case UNRES_INSTID: assert(sleaf->type.base == LY_TYPE_INST); ext_dep = check_instid_ext_dep(leaf->schema, leaf->value_str); if (ext_dep == -1) { return -1; } if ((ignore_fail == 1) || (ext_dep && (ignore_fail == 2))) { req_inst = -1; } else { req_inst = sleaf->type.info.inst.req; } rc = resolve_instid(node, leaf->value_str, req_inst, &ret); if (!rc) { if (ret && !ext_dep) { /* valid resolved */ leaf->value.instance = ret; leaf->value_type = LY_TYPE_INST; leaf->value_flags &= ~LY_VALUE_UNRES; } else { /* valid unresolved */ leaf->value.instance = NULL; leaf->value_type = LY_TYPE_INST; leaf->value_flags |= LY_VALUE_UNRES; } } else { return rc; } break; case UNRES_UNION: assert(sleaf->type.base == LY_TYPE_UNION); return resolve_union(leaf, &sleaf->type, 1, ignore_fail, NULL); case UNRES_WHEN: if ((rc = resolve_when(node, ignore_fail, failed_when))) { return rc; } break; case UNRES_MUST: if ((rc = resolve_must(node, 0, ignore_fail))) { return rc; } break; case UNRES_MUST_INOUT: if ((rc = resolve_must(node, 1, ignore_fail))) { return rc; } break; case UNRES_UNIQ_LEAVES: if (lyv_data_unique(node)) { return -1; } break; default: LOGINT(NULL); return -1; } return EXIT_SUCCESS; } /** * @brief add data unres item * * @param[in] unres Unres data structure to use. * @param[in] node Data node to use. * * @return 0 on success, -1 on error. */ int unres_data_add(struct unres_data *unres, struct lyd_node *node, enum UNRES_ITEM type) { assert(unres && node); assert((type == UNRES_LEAFREF) || (type == UNRES_INSTID) || (type == UNRES_WHEN) || (type == UNRES_MUST) || (type == UNRES_MUST_INOUT) || (type == UNRES_UNION) || (type == UNRES_UNIQ_LEAVES)); unres->count++; unres->node = ly_realloc(unres->node, unres->count * sizeof *unres->node); LY_CHECK_ERR_RETURN(!unres->node, LOGMEM(NULL), -1); unres->node[unres->count - 1] = node; unres->type = ly_realloc(unres->type, unres->count * sizeof *unres->type); LY_CHECK_ERR_RETURN(!unres->type, LOGMEM(NULL), -1); unres->type[unres->count - 1] = type; return 0; } static void resolve_unres_data_autodel_diff(struct unres_data *unres, uint32_t unres_i) { struct lyd_node *next, *child, *parent; uint32_t i; for (i = 0; i < unres->diff_idx; ++i) { if (unres->diff->type[i] == LYD_DIFF_DELETED) { /* only leaf(-list) default could be removed and there is nothing to be checked in that case */ continue; } if (unres->diff->second[i] == unres->node[unres_i]) { /* 1) default value was supposed to be created, but is disabled by when * -> remove it from diff altogether */ unres_data_diff_rem(unres, i); /* if diff type is CREATED, the value was just a pointer, it can be freed normally (unlike in 4) */ return; } else { parent = unres->diff->second[i]->parent; while (parent && (parent != unres->node[unres_i])) { parent = parent->parent; } if (parent) { /* 2) default value was supposed to be created but is disabled by when in some parent * -> remove this default subtree and add the rest into diff as deleted instead in 4) */ unres_data_diff_rem(unres, i); break; } LY_TREE_DFS_BEGIN(unres->diff->second[i]->parent, next, child) { if (child == unres->node[unres_i]) { /* 3) some default child of a default value was supposed to be created but has false when * -> the subtree will be freed later and automatically disconnected from the diff parent node */ return; } LY_TREE_DFS_END(unres->diff->second[i]->parent, next, child); } } } /* 4) it does not overlap with created default values in any way * -> just add it into diff as deleted */ unres_data_diff_new(unres, unres->node[unres_i], unres->node[unres_i]->parent, 0); lyd_unlink(unres->node[unres_i]); /* should not be freed anymore */ unres->node[unres_i] = NULL; } /** * @brief Resolve every unres data item in the structure. Logs directly. * * If options include #LYD_OPT_TRUSTED, the data are considered trusted (must conditions are not expected, * unresolved leafrefs/instids are accepted, when conditions are normally resolved because at least some implicit * non-presence containers may need to be deleted). * * If options includes #LYD_OPT_WHENAUTODEL, the non-default nodes with false when conditions are auto-deleted. * * @param[in] ctx Context used. * @param[in] unres Unres data structure to use. * @param[in,out] root Root node of the data tree, can be changed due to autodeletion. * @param[in] options Data options as described above. * * @return EXIT_SUCCESS on success, -1 on error. */ int resolve_unres_data(struct ly_ctx *ctx, struct unres_data *unres, struct lyd_node **root, int options) { uint32_t i, j, first, resolved, del_items, stmt_count; uint8_t prev_when_status; int rc, progress, ignore_fail; enum int_log_opts prev_ilo; struct ly_err_item *prev_eitem; LY_ERR prev_ly_errno = ly_errno; struct lyd_node *parent; struct lys_when *when; assert(root); assert(unres); if (!unres->count) { return EXIT_SUCCESS; } if (options & (LYD_OPT_NOTIF_FILTER | LYD_OPT_GET | LYD_OPT_GETCONFIG | LYD_OPT_EDIT)) { ignore_fail = 1; } else if (options & LYD_OPT_NOEXTDEPS) { ignore_fail = 2; } else { ignore_fail = 0; } LOGVRB("Resolving unresolved data nodes and their constraints..."); if (!ignore_fail) { /* remember logging state only if errors are generated and valid */ ly_ilo_change(ctx, ILO_STORE, &prev_ilo, &prev_eitem); } /* * when-stmt first */ first = 1; stmt_count = 0; resolved = 0; del_items = 0; do { if (!ignore_fail) { ly_err_free_next(ctx, prev_eitem); } progress = 0; for (i = 0; i < unres->count; i++) { if (unres->type[i] != UNRES_WHEN) { continue; } if (first) { /* count when-stmt nodes in unres list */ stmt_count++; } /* resolve when condition only when all parent when conditions are already resolved */ for (parent = unres->node[i]->parent; parent && LYD_WHEN_DONE(parent->when_status); parent = parent->parent) { if (!parent->parent && (parent->when_status & LYD_WHEN_FALSE)) { /* the parent node was already unlinked, do not resolve this node, * it will be removed anyway, so just mark it as resolved */ unres->node[i]->when_status |= LYD_WHEN_FALSE; unres->type[i] = UNRES_RESOLVED; resolved++; break; } } if (parent) { continue; } prev_when_status = unres->node[i]->when_status; rc = resolve_unres_data_item(unres->node[i], unres->type[i], ignore_fail, &when); if (!rc) { /* finish with error/delete the node only if when was changed from true to false, an external * dependency was not required, or it was not provided (the flag would not be passed down otherwise, * checked in upper functions) */ if ((unres->node[i]->when_status & LYD_WHEN_FALSE) && (!(when->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) || !(options & LYD_OPT_NOEXTDEPS))) { if ((!(prev_when_status & LYD_WHEN_TRUE) || !(options & LYD_OPT_WHENAUTODEL)) && !unres->node[i]->dflt) { /* false when condition */ goto error; } /* follows else */ /* auto-delete */ LOGVRB("Auto-deleting node \"%s\" due to when condition (%s)", ly_errpath(ctx), when->cond); /* only unlink now, the subtree can contain another nodes stored in the unres list */ /* if it has parent non-presence containers that would be empty, we should actually * remove the container */ for (parent = unres->node[i]; parent->parent && parent->parent->schema->nodetype == LYS_CONTAINER; parent = parent->parent) { if (((struct lys_node_container *)parent->parent->schema)->presence) { /* presence container */ break; } if (parent->next || parent->prev != parent) { /* non empty (the child we are in and we are going to remove is not the only child) */ break; } } unres->node[i] = parent; if (*root && *root == unres->node[i]) { *root = (*root)->next; } lyd_unlink(unres->node[i]); unres->type[i] = UNRES_DELETE; del_items++; /* update the rest of unres items */ for (j = 0; j < unres->count; j++) { if (unres->type[j] == UNRES_RESOLVED || unres->type[j] == UNRES_DELETE) { continue; } /* test if the node is in subtree to be deleted */ for (parent = unres->node[j]; parent; parent = parent->parent) { if (parent == unres->node[i]) { /* yes, it is */ unres->type[j] = UNRES_RESOLVED; resolved++; break; } } } } else { unres->type[i] = UNRES_RESOLVED; } if (!ignore_fail) { ly_err_free_next(ctx, prev_eitem); } resolved++; progress = 1; } else if (rc == -1) { goto error; } /* else forward reference */ } first = 0; } while (progress && resolved < stmt_count); /* do we have some unresolved when-stmt? */ if (stmt_count > resolved) { goto error; } for (i = 0; del_items && i < unres->count; i++) { /* we had some when-stmt resulted to false, so now we have to sanitize the unres list */ if (unres->type[i] != UNRES_DELETE) { continue; } if (!unres->node[i]) { unres->type[i] = UNRES_RESOLVED; del_items--; continue; } if (unres->store_diff) { resolve_unres_data_autodel_diff(unres, i); } /* really remove the complete subtree */ lyd_free(unres->node[i]); unres->type[i] = UNRES_RESOLVED; del_items--; } /* * now leafrefs */ if (options & LYD_OPT_TRUSTED) { /* we want to attempt to resolve leafrefs */ assert(!ignore_fail); ignore_fail = 1; ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0); ly_errno = prev_ly_errno; } first = 1; stmt_count = 0; resolved = 0; do { progress = 0; for (i = 0; i < unres->count; i++) { if (unres->type[i] != UNRES_LEAFREF) { continue; } if (first) { /* count leafref nodes in unres list */ stmt_count++; } rc = resolve_unres_data_item(unres->node[i], unres->type[i], ignore_fail, NULL); if (!rc) { unres->type[i] = UNRES_RESOLVED; if (!ignore_fail) { ly_err_free_next(ctx, prev_eitem); } resolved++; progress = 1; } else if (rc == -1) { goto error; } /* else forward reference */ } first = 0; } while (progress && resolved < stmt_count); /* do we have some unresolved leafrefs? */ if (stmt_count > resolved) { goto error; } if (!ignore_fail) { /* log normally now, throw away irrelevant errors */ ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0); ly_errno = prev_ly_errno; } /* * rest */ for (i = 0; i < unres->count; ++i) { if (unres->type[i] == UNRES_RESOLVED) { continue; } assert(!(options & LYD_OPT_TRUSTED) || ((unres->type[i] != UNRES_MUST) && (unres->type[i] != UNRES_MUST_INOUT))); rc = resolve_unres_data_item(unres->node[i], unres->type[i], ignore_fail, NULL); if (rc) { /* since when was already resolved, a forward reference is an error */ return -1; } unres->type[i] = UNRES_RESOLVED; } LOGVRB("All data nodes and constraints resolved."); unres->count = 0; return EXIT_SUCCESS; error: if (!ignore_fail) { /* print all the new errors */ ly_ilo_restore(ctx, prev_ilo, prev_eitem, 1); /* do not restore ly_errno, it was udpated properly */ } return -1; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_1358_0